Java Tutorial: Write Once, Run Anywhere
Java Tutorial: Write Once, Run Anywhere
Java - General
Java is:
platform independent programming language and Technology. similar to C++ in syntax Developed by James Gosling of Sun Microsystem now acquired by Oracle Corp.
Java - General
How it works!
Compile-time Environment Compile-time Environment
Class Loader Java Source (.java) Java Bytecodes move locally or through network Bytecode Verifier Java Class Libraries
Java Interpreter
Java Compiler
Runtime System
Operating System
Hardware
How it works!
Code is compiled to bytecode, which is interpreted by the resident JVM JIT (just in time) compilers attempt to increase speed.
Java - Security
Object-Oriented
Java Advantages
Portable - Write Once, Run Anywhere Security has been well thought through Robust memory management Designed for network programming Multi-threaded (multiple simultaneous tasks)
boolean, char, byte, short, int, long, float, double etc. These basic (or primitive) types are the only types that are not objects (due to performance issues). This means that you dont use the new operator to create a primitive variable. Declaring primitive variables:
float initVal; int retVal, index = 2;// declaration with initialization double gamma = 1.2; boolean valueOk = false;
Initialisation
Java sets primitive variables to default values zero or false or null if not initialized. All object references are initially set to null
An array of anything is an object Set to null on declaration Elements to zero false or null on creation
Declarations
int index = 1.2; // compiler error boolean retOk = 1; // compiler error double fiveFourths = 5 / 4; // no error! float ratio = 5.8; // incorrect double huh = 0 / 0; // AE- DBZ But for floating point: S.o.pln(-5.4/0+ + 0.0/0); // -Infinity NaN
1.2f is a float value accurate to 7 decimal places. 1.2 is a double value accurate to 15 decimal places.
double myVal = a + b % d c * d / b;
Is the same as: double myVal = (a + (b % d)) ((c * d) / b);
A simple statement is a command terminated by a semi-colon: name = Fred; A block is a compound statement enclosed in curly brackets: { name1 = Fred; name2 = Bill; } Blocks may contain other blocks
Flow of Control
Java executes one statement after the other in the order they are written Many Java statements are flow control statements: Alternation: if, if else, switch Looping: for, while, do while Escapes: break, continue, return
The if statement evaluates an expression and if that evaluation is true then the specified action is taken
if ( x < 10 ) x = 10;
If the value of x is less than 10, make x equal to 10 It could have been written:
if ( x < 10 ) x = 10;
Or, alternatively:
if ( x < 10 ) { x = 10; }
Relational Operators
== != >= <= > < Equal (careful) Not equal Greater than or equal Less than or equal Greater than Less than
If else
The if else statement evaluates an expression and performs one action if that evaluation is true or a different action if it is false. if (x != oldx) {
System.out.print(x was changed);
} else { System.out.print(x is unchanged); }
Nested if else
if ( myVal > 100 ) { if ( remainderOn == true) { myVal = mVal % 100; } else { myVal = myVal / 100.0; } } else { System.out.print(myVal is in range); }
else if
A Warning
WRONG! if( i == j )
if ( j == k ) System.out.print( i equals k); else System.out.print( i is not equal to j);
CORRECT! if( i == j ) { if ( j == k ) System.out.print( i equals k); } else System.out.print( i is not equal to j); // Correct!
Loop n times for ( i = 0; i < n; n++ ) { // this code body will execute n times // ifrom 0 to n-1 } Nested for loop: for ( j = 0; j < 10; j++ ) { for ( i = 0; i < 20; i++ ){ // this code body will execute 200 times } }
while loops
while(response == 1) { System.out.print( ID = + userID[n]); n++; response = readInt( Enter ); }
What is the minimum number of times the loop is executed? What is the maximum number of times?
do { } while loops
do { System.out.print( ID = + userID[n] ); n++; response = readInt( Enter ); }while (response == 1);
What is the minimum number of times the loop is executed? What is the maximum number of times?
Break
A break statement causes an exit from the innermost containing while, do, for or switch statement.
for ( int i = 0; i < maxID, i++ ) { while ( userID[i] == targetID ) { index = i; break; } } // program jumps here after break
Continue
Can only be used with while, do or for. The continue statement causes the innermost loop to start the next iteration immediately
for ( int i = 0; i < maxID; i++ ) { if ( userID[i] != -1 ) continue; System.out.print( UserID + i + : + userID); }
Arrays
Am array is a list of similar things sharing a common name in between in a contagious fashion. An Array is an object, in fact everything in java! An array has a fixed: name type length These must be declared when the array is created. Arrays sizes cannot be changed during the execution of the code
myArray =
3
0
6
1
3
2
1
3
6
4
3
5
4
6
1
7
myArray has room for 8 elements the elements are accessed by their index array indices start at 0
Declaring Arrays
int myArray[]; declares myArray to be an array of integers myArray = new int[8]; sets up 8 integer-sized spaces in memory, labelled myArray[0] to myArray[7] int myArray[] = new int[8]; combines the two statements in one line
Assigning Values
refer to the array elements by index to store values in them. myArray[0] = 3; myArray[1] = 6; myArray[2] = 3; ... can create and initialise in one step: int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};
Arrays of Objects
So far we have looked at an array of primitive types. integers could also use doubles, floats, characters Often want to have an array of objects Students, Books, Loans Need to follow 3 steps.
Student("Cathy", "Computing");
Encapsulation
Objects hide their functions (methods) and data (instance variables)
Inheritance
Each subclass inherits all variables of its manual superclass
car
Super class
automatic
Subclasses
Polymorphism
Interface same despite draw(3args) different data types
draw(4args)
Methods
A method is a named sequence of code with parenthesis at the end that can be invoked by other Java code. A method takes some parameters, performs some computations and then optionally returns a value (or object). Methods can be used as part of an expression statement.
Access Specifiers:
Methods/data may be declared public or private or protected meaning they may or may not be accessed by code in other classes java has a default (package or friendly ) access as well. Good practice:
keep data private keep methods public
Using objects
Here, code in one class creates an instance of another class and does something with it.
Fruit plum=new Fruit(); int cals; cals = plum.total_calories();
Dot operator allows you to access (public) data/methods inside Fruit class
Constructors
The line
plum = new Fruit();
invokes a constructor with which you can set the initial data of an object You may choose several different type of constructor with different argument lists
eg Fruit(), Fruit(a) ...
Overloading
Can have several versions of a method in class with different types, numbers or order of arguments
Fruit() {int grams=50;} Fruit(int a,int b) { grams=a; cals_per_gram=b;}
Overriding
Prototype is same but the method is in the subclass (child class). Eg: class B{p v Fruit() {grams=50;}} class C extends B{p v Fruit() {grams=100;}}
Package
Package
When you create a class in a package, the generated class file must reside in a subdirectory of a directory listed in CLASSPATH or in the same subdirectory of a JAR (or ZIP) file that resides in a directory named in the CLASSPATH.
Importing
Inner class:
A (nested) class within another class. Types:
A non final variable cant be referred (called) inside a different method of inner class.
difference between construction of a new object, and construction of a new inner class extending a class:
//An object of an inner class extending Person Person demon= new Person(Dracula){ //class code here};