Title: Java Introduction
1Java Introduction
- If you understand this, you will be able to
- Outline 4 key features of java
- Use simple control structures
- Declare variables
- Understand simple class declarations
2Key Features
- Portability
- Garbage collection
- No memory leaks - no need to free objects
- Support for concurrent programming
- Threads
- Secure
- Applets run in a sandbox,
- Supports digital signatures
- Many additional packages
- Communication, user-interface, etc
3Java Virtual Machine
Java Source
Class file (byte code)
Compiler
Java Application
Java Application
Windows JVM
Linux JVM
Linux
Windows
4Portability
- Uniform run-time system
- Java Virtual Machine
- Same interface on different processors
- Interpreted assembly language
- Compiler generates instructions for JVM
- No implementation dependencies
- e.g. define size of types
- C int could be 32 or 64 bits
- In Java size of int is 32 bits on every machine
- A program will give the same results on any
machine
5Robust
- Simple language
- Cut out C features
- No pointers - no direct memory access
- Strong typing checked at compile time
- Run-time bounds cast checking
- Exceptions
- Automatically jump to handler code on error
- Ensure programmer handles faults
Cant access beyond the end of an array
6Java Basics
- Syntax control structures
- if, for, while, do while () like C
- Primitive data types
- int, char, short, long, float, double like C
- Also byte, boolean
- All initialised to defined default values
- Compound data types
- Class e.g. to represent a person age, name,
- Strings a normal class holding characters
- Arrays a normal class holding a collection of
items
7Example Parity Calculation
- Parity check to detect errors
- Add extra parity bit to 7 data bits
- Ensure that total number of ones is even
- An error will make the total odd
- On receipt, count the number of bits
- If odd, there has been at least one error
- If even, assume no error
- Cannot detect even number of errors
8Parity Calculation overview
Set up using System.in like cin
- // initialisation
- String inputData formattedInput.readLine()
- int pos 0
- int parityBit 0
- / Calculate the parity bit /
-
- if (inputData.length() ! 7)
- System.out.println("There should be 7 bits
of input") - else
- System.out.println("Result
"inputDataparityBit)
String is built into Java. A string object can
tell you its length and return individual
characters.
System.out is like cout
9Parity Calculation main body
A getter function
- while (pos lt inputData.length())
- char current inputData.charAt(pos)
- pos pos1 // current
position for user (start at 1) - switch (current)
- case '0'
- break
- case '1'
- parityBit 1 - parityBit // invert
parityBit - break
- default System.out.println("Invalid
input "current" at "(pos)) -
while, switch, , if are the same as in C
10Classes
- A class defines a type of object
- An object is an instance of a class
- Data and function members
- Data members belong to an object
- Member functions affect current object
- Static data and static function members
- One per class rather than one per instance
isLeapYear()
nextDay()
Day
Month
Year
11Class Example Position
- class Position
- float x
- float y
- Position(int nx, int ny) x nx y
ny - public String toString() return "("x",
"y")" - public double distFrom(Position p)
- return Math.sqrt((p.x-x)(p.x-x)
(p.y-y)(p.y-y)) -
Data Member
Constructor
Method
12Class Example Position
- public class Coordinates
- public static void main(String args)
- Position a new Position(3,4)
- Position b new Position(6,8)
- System.out.print(a" - "b"
"a.distFrom(b)) - try System.in.read()
- catch (Exception ex) System.out.println(e
x.toString()) -
Start point like C
Just to pause
13Notes
- A class has data members functions
- Constructor
- Creates an object
- Position a new Position(3,4)
- Use as distFrom() method
- This can access as x and y data members
- Automatically use toString() method
14Example Value Reference
- int x 5
- int y 2
- x y
- String Sx new String ("five")
- String Sy new String (two")
- Sx Sy
5
2
2
Garbage cant be reached from the program
could be returned to the run-time system
15Reference Value Variables
- Primitive variables hold the value
- int, boolean variables, float
- Class variables hold a reference to an object
- String, Object, Position
- Primitive types have corresponding classes
- Boolean, Integer, Float
- Provide useful methods
16Inheritance
The child is like the base With extra facilities
Base class
Child Class
- A class automatically has the methods and
properties of its ancestor (base class) - Define new class starting from the ancestor
- Can add data members
- Can add methods
- Can change implementation of methods
- A class always inherits from 1 ancestor
- Except for the Object class
17Declaring a Descendent Class
- class GridReference extends Position
- GridReference(int nx, int ny)
- super(nx,ny)
-
-
- public String toString()
- return "("x" East, "y" North)"
-
Position
GridReference is like Position with a different
toString()
GridReference
GridReference has x and y data members by
inheritance
GridReference has a distFrom() method by
inheritance
GridReference overrides toString()
18Using the Descendent
- GridReference grA new GridReference(4,5)
- GridReference grB new GridReference(16,10)
- System.out.println(grA" - "grB"
"grA.distFrom(grB))
19What Java Hasn't Got
- Constants
- Use 'final' variables - can't be changed
- Structures
- Combine related values (e.g. name, age, address)
- Use classes instead
- Pointers
- However, objects use the reference model
- A field in a object can refer to another object
- Single byte characters
- All characters are Unicode (2 byte)
20Garbage Collection
- Memory management - major cause of bugs
- Forget to release memory - lose resources (a
leak) - Use memory after release - unpredictable contents
- Release twice confuse the memory allocator
- C
- Explicitly release allocated memory with delete
- Java
- Run-time system scans memory
- (Periodically or when a memory request cant be
met) - Release blocks not referenced by program
21Summary of Java
- Great similarities with C
- Uses reference variables not pointers
- Classes
- Group data functions together
- Inheritance
- Can define new classes by extension
- Portability through Virtual Machine
- Concerned with safety garbage collection