core java tutorial

76
Java Tutorial Write Once, Run Anywhere

Upload: jay-san

Post on 21-Jul-2016

57 views

Category:

Documents


7 download

DESCRIPTION

Java notes

TRANSCRIPT

Page 1: Core Java Tutorial

Java Tutorial

Write Once, Run Anywhere

Page 2: Core Java Tutorial

Java - General

• Java is:– platform independent programming language– similar to C++ in syntax

Page 3: Core Java Tutorial

Compile-time EnvironmentCompile-time Environment

JavaBytecodes

move locallyor through

network

JavaSource(.java)

JavaCompiler

JavaBytecode(.class )

JavaInterpreter

Just in Time

Compiler

Runtime System

Class Loader

BytecodeVerifier

Java ClassLibraries

Operating System

Hardware

JavaVirtualmachine

How it works…!

Page 4: Core Java Tutorial

How it works…!

• Java is independent only for one reason:– Only depends on the Java Virtual Machine

(JVM),– code is compiled to bytecode, which is

interpreted by the resident JVM,– JIT (just in time) compilers attempt to increase

speed.

Page 5: Core Java Tutorial

Object-Oriented

• Java supports OOD– Polymorphism– Inheritance– Encapsulation

• Java programs contain nothing but definitions and instantiations of classes– Everything is encapsulated in a class!

Page 6: Core Java Tutorial

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)• Dynamic & extensible (loads of libraries)

– Classes stored in separate files– Loaded only when needed

Page 7: Core Java Tutorial

Basic Java Syntax

Page 8: Core Java Tutorial

Primitive Types and Variables

• 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 don’t use the new operator to create

a primitive variable.• Declaring primitive variables:

float initVal;int retVal, index = 2;double gamma = 1.2, brightnessboolean valueOk = false;

Page 9: Core Java Tutorial

Initialisation

• If no value is assigned prior to use, then the compiler will give an error

• Java sets primitive variables to zero or false in the case of a boolean variable

• 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

Page 10: Core Java Tutorial

Declarationsint index = 1.2; // compiler errorboolean retOk = 1; // compiler errordouble fiveFourths = 5 / 4; // no error!float ratio = 5.8f; // correctdouble fiveFourths = 5.0 / 4.0; // correct

• 1.2f is a float value accurate to 7 decimal places.• 1.2 is a double value accurate to 15 decimal places.

Page 11: Core Java Tutorial

• All Java assignments are right associative

int a = 1, b = 2, c = 5a = b = c

System.out.print(“a= “ + a + “b= “ + b + “c= “ + c)

• What is the value of a, b & c• Done right to left: a = (b = c);

Assignment

Page 12: Core Java Tutorial

Statements & Blocks

• 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

Page 13: Core Java Tutorial

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, switchLooping: for, while, do whileEscapes: break, continue, return

Page 14: Core Java Tutorial

If – The Conditional Statement• The if statement evaluates an expression and if that

evaluation is true then the specified action is takenif ( 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; }

Page 15: Core Java Tutorial

Relational Operators

== Equal (careful)!= Not equal>= Greater than or equal<= Less than or equal> Greater than< Less than

Page 16: Core Java Tutorial

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”);

}

Page 17: Core Java Tutorial

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”);

}

Page 18: Core Java Tutorial

The switch Statementswitch ( n ) {case 1: // execute code block #1break;case 2:// execute code block #2break;default:// if all previous tests fail then //execute code block #4break;

}

Page 19: Core Java Tutorial

The for loop• Loop n times

for ( i = 0; i < n; n++ ) {// this code body will execute n times// ifrom 0 to n-1

}• Nested for:

for ( j = 0; j < 10; j++ ) {for ( i = 0; i < 20; i++ ){

// this code body will execute 200 times}

}

Page 20: Core Java Tutorial

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?

Page 21: Core Java Tutorial

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?

Page 22: Core Java Tutorial

Break

• A break statement causes an exit from the innermost containing while, do, for or switch statement.for ( int i = 0; i < maxID, i++ ) {if ( userID[i] == targetID ) {

index = i;break;

}} // program jumps here after break

Page 23: Core Java Tutorial

Continue• Can only be used with while, do or for.• The continue statement causes the innermost loop to start

the next iteration immediatelyfor ( int i = 0; i < maxID; i++ ) {if ( userID[i] != -1 ) continue;System.out.print( “UserID ” + i + “ :” +

userID);}

Page 24: Core Java Tutorial

Arrays• An array is a list of similar things• 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

Page 25: Core Java Tutorial

myArray has room for 8 elements the elements are accessed by their index in Java, array indices start at 0

3 6 3 1 6 3 4 1myArray = 0 1 2 3 4 5 6 7

Page 26: Core Java Tutorial

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

Page 27: Core Java Tutorial

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};

Page 28: Core Java Tutorial

Iterating Through Arrays

• for loops are useful when dealing with arrays:

for (int i = 0; i < myArray.length; i++) {

myArray[i] = getsomevalue();}

Page 29: Core Java Tutorial

Java Methods & Classes

Page 30: Core Java Tutorial

Classes ARE Object Definitions

• OOP - object oriented programming• code built from objects • Java these are called classes• Each class definition is coded in a

separate .java file• Name of the object must match the

class/object name

Page 31: Core Java Tutorial

The three principles of OOP

• Encapsulation– Objects hide their functions

(methods) and data (instance variables)

• Inheritance– Each subclass inherits all

variables of its superclass• Polymorphism

– Interface same despite different data types

car

auto-maticmanual

Super class

Subclasses

draw() draw()

Page 32: Core Java Tutorial

Simple Class and Method

Class Fruit{int grams;int cals_per_gram;

int total_calories() {return(grams*cals_per_gram);}

}

Page 33: Core Java Tutorial

Methods• A method is a named sequence of code 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.

public float convertCelsius(float tempC) {return( ((tempC * 9.0f) / 5.0f) + 32.0 );

}

Page 34: Core Java Tutorial

Method Signatures• A method signature specifies:

– The name of the method.– The type and name of each parameter.– The type of the value (or object) returned by the method.– The checked exceptions thrown by the method.– Various method modifiers.– modifiers type name ( parameter list ) [throws exceptions ]public float convertCelsius (float tCelsius ) {}public boolean setUserInfo ( int i, int j, String name ) throws

IndexOutOfBoundsException {}

Page 35: Core Java Tutorial

What is an object?

• Object is a thing• An object has state, behavior and identity

– Internal variable: store state– Method: produce behavior– Unique address in memory: identity

• An object is a manifestation of a class

Page 36: Core Java Tutorial

What is class?

• Class introduces a new data type• A class describes a set of objects that have

identical characteristics (data elements) and behaviors (methods).– Existing classes provided by JRE– User defined classes

• Once a class is established, you can make as many objects of it as you like, or none.

Page 37: Core Java Tutorial

Simple example: class Person

• A Person has some attributes• The class defines these properties for all

people• Each person gets his own copy of the fields• Attributes = properties = fields

Page 38: Core Java Tutorial

Class Person: definitionclass Person {

String name;

int height; //in inches

int weight; //in pounds

public void printInfo(){

System.out.println(name+" with height="+height+", weight="+weight);

}

}

class ClassName{ /* class body goes here */ }

class: keyword

Page 39: Core Java Tutorial

Class Person: usage

Person ke; //declaration

ke = new Person(); //create an object of Person

ke.name= “Ke Wang”; //access its field

Person sal = new Person();

sal.name=“Salvatore J. Stolfo”;

ke.printInfo();

Sal.printInfo(); // error here??

Page 40: Core Java Tutorial

Class Person

Name: Ke Wang

height: 0

weight: 0

Name: Salvatore J. Stolfo

height: 0

weight: 0

ke

sal

Page 41: Core Java Tutorial

Class Person: variables

Person x;

x=ke;

x.printInfo();

x=sal;

x.printInfo();

This gives the same output as previous code !

Page 42: Core Java Tutorial

Class Person: variables

Name: Ke Wang

height: 0

weight: 0

Name: Salvatore J. Stolfo

height: 0

weight: 0

ke

sal

x

references objects

Page 43: Core Java Tutorial

Reference

• We call x, as well as ke and sal, “reference” to the object

• Handles to access an object• Reference itself is not accessible/manipulable

– Different from C/C++, cannot increment/decrement it

• Implemented as pointer+– Java runtime is watching all assignment to references – Why? – garbage collection (later)

Page 44: Core Java Tutorial

Reference

Person ke; //only created the reference, not an object. It points to nothing now (null).

ke = new Person(); //create the object (allocate storage in memory), and ke is initialized.

ke.name=“Ke Wang”; //access the object through the reference

Page 45: Core Java Tutorial

More on reference

• Have distinguished value null, meaning pointing to nothing– if( x==null) { … }

• Multiple references can point to one object• When no reference point to an object, that

object is never accessible again.

Page 46: Core Java Tutorial

Class Person: problemke.weight = 150; // too bad, but possible

ke.weight = -20; // Houston, we have a problem!!

Need to ensure the validity of value.

Solution: ask the class to do it!

ke.setWeight(150); // OK, now ke’s weight is 150

ke.setWeight(-10); ******** Error, weight must be positive number

Page 47: Core Java Tutorial

Class Person: add methodclass Person{ ... void setWeight(int w){ if(w<=0)

System.err.println("***** error, weight must be positive number! "); else

weight = w; }}

Page 48: Core Java Tutorial

Class Person: new problemke.setWeight(-10);

******** Error, weight must be positive number

ke.weight = -20; //haha, I’m the boss!

How about we forgot to use the set function? Or we just don’t want to?

Solution: just make the variable inaccessible from outside!

Page 49: Core Java Tutorial

Class Person

class Hello{

public static void main ( String[] args ) {Person ke = new Person();ke.weight = -20;

} }

>javac Hello.javaHello.java:5: weight has private access in Person ke.weight = -20; ^1 error

Page 50: Core Java Tutorial

Access functions

• Generally make fields private and provide public getField() and setField() access functions

• O-O term for this is Encapsulation• C# does this by default

Page 51: Core Java Tutorial

copy

• Primitive types get copied directly by =– int x= 10; int y=x;

• Objects and arrays just copy the reference, still only one copy of the object existing.

Name: Ke Wang

height: 0

weight: 0

ke

x

Person ke =new Person();ke.name="Ke Wang";Person x=ke;x.name="Sal"; System.out.println(ke.name); // print Sal!

Page 52: Core Java Tutorial

Static keyword• Want to have only one piece of storage for a data,

regardless how many objects are created, or even no objects created

• Need a method that isn’t associated with any particular object of this class

• static keyword apply to both fields and methods• Can be called directly by class name

– Example: java.lang.Math• Non-static fields/methods must be called through an

instance

Page 53: Core Java Tutorial

Constructor• Constructor has the same name as that of a class but

no return type.• Default Constructor is a no-argument constructor

automatically generated by the compiler.• If we define a constructor for a given class then the

compiler doesn’t generate the default constructor.

Page 54: Core Java Tutorial

Final keyword• Final can be declared at class level, method level,

variable level.• Final variable implies constant• Final method cannot be overridden• Final class cannot be extended.

Page 55: Core Java Tutorial

Access Modifiers

• In Java code, class and variable and method and constructor declarations can have “access specifiers”, that is one of: private, protected, public. (or none.)

• I) Class level access modifiers (java classes only)• Only two access modifiers is allowed, public and no

modifier• If a class is ‘public’, then it CAN be accessed from

ANYWHERE.• If a class has ‘no modifer’, then it CAN ONLY be

accessed from ‘same package’.

Page 56: Core Java Tutorial

Access Modifiers

• II) Member level access modifiers (java variables and java methods)

• All the four public, private, protected and no modifer is allowed.

• public and no modifier – the same way as used in class level.

• private – members CAN ONLY access.• protected – CAN be accessed from ‘same package’

and a subclass existing in any package can access.

Page 57: Core Java Tutorial

Access Modifiers

Access Modifiers Same Class Same Package Subclass Other packages

public Y Y Y Y

protected Y Y Y N

no access modifier Y Y N N

private Y N N N

For better understanding, member level access is formulated as a table:

First row {public Y Y Y Y} should be interpreted as:Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘same class’.Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘same package’.Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘subclass’.Y – A member declared as ‘public’ CAN be accessed from ‘Other packages’.

Second row {protected Y Y Y N} should be interpreted as:Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘same class’.Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘same package’.Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘subclass’.N – A member declared with ‘protected’ access modifier CANNOT be accessed by the members of the ‘Other package’.

Page 58: Core Java Tutorial

Inheritance• An object acquiring the properties of another is

knows an inheritance.• A class that is derived from another class is called a

subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).

• Every class has one and only one direct superclass (single inheritance).

Page 59: Core Java Tutorial

InheritanceWhat You Can Do in a Subclass•A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:•The inherited fields can be used directly, just like any other fields.•You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).•You can declare new fields in the subclass that are not in the superclass.•The inherited methods can be used directly as they are.•You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.•You can declare new methods in the subclass that are not in the superclass.•You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.

Page 60: Core Java Tutorial

Interfaces• In the Java programming language, an interface is a reference type, similar to a

class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.

• To use an interface, you write a class that implements the interface.

Page 61: Core Java Tutorial

Abstract Classes• An abstract class is a class that is declared abstract—it may or may not include

abstract methods. Abstract classes cannot be instantiated, but they can be sub classed.

• An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this: public abstract String move();

• Abstract Classes versus InterfacesUnlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.

Page 62: Core Java Tutorial

Exception HandlingAn exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:•A user has entered invalid data.•A file that needs to be opened cannot be found.•A network connection has been lost in the middle of communications, or the JVM has run out of memory..

To understand how exception handling works in Java, you need to understand the three categories of exceptions:•Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.•Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.•Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Page 63: Core Java Tutorial

Exception HandlingKeywords:Try, catch:A try/catch block is placed around the code that might generate an exception.

Finally:A finally block of code always executes, whether or not an exception has occurred.

Throw:In order to explicitly throw an exception.

Throws:If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.

Page 64: Core Java Tutorial

Collections Framework The Collections Framework is made up of a set of interfaces for working with groups of objects. The following diagram shows the framework interface hierarchy.

When designing software with the Collections Framework, it is useful to remember the following hierarchical relationships of the four basic interfaces of the framework:•The Collection interface is a group of objects, with duplicates allowed•Set extends Collection but forbids duplicates•List extends Collection also, allows duplicates and introduces positional indexing•Map extends neither Set nor Collection.

Page 65: Core Java Tutorial

Collections FrameworkMoving on to the framework implementations, the concrete collection classes follow a naming convention, combining the underlying data structure with the framework interface. The following table shows the six collection implementations introduced with the Java 2 framework, in addition to the four historical collection classes. For information on how the historical collection classes changed, like how Hashtable was reworked into the framework

•There are no implementations of the Collection interface. The historical collection classes are called such because they have been around since the 1.0 release of the Java class libraries.•If you are moving from the historical collection classes to the new framework classes, one of the primary differences is that all operations are unsynchronized with the new classes. While you can add synchronization to the new classes, you cannot remove it from the old.

Interface Implementation Historical

Set HashSet TreeSet

List ArrayList LinkedListVectorStack

Map HashMap TreeMap HashtableProperties

Page 66: Core Java Tutorial

66

What is JDBC?• “An API that lets you access virtually any tabular data source

from the Java programming language”• JDBC Data Access API – JDBC Technology Homepage

– What’s an API? • See J2SE documentation

– What’s a tabular data source?• “… access virtually any data source, from relational databases

to spreadsheets and flat files.”– JDBC Documentation

• We’ll focus on accessing Oracle databases

Page 67: Core Java Tutorial

67

General Architecture

• What design pattern is implied in this architecture?

• What does it buy for us?• Why is this architecture also

multi-tiered?

Page 68: Core Java Tutorial

68

Page 69: Core Java Tutorial

69

Basic steps to use a database in Java

• 1.Establish a connection• 2.Create JDBC Statements• 3.Execute SQL Statements• 4.GET ResultSet • 5.Close connections

Page 70: Core Java Tutorial

70

1. Establish a connection

• import java.sql.*;• Load the vendor specific driver

– Class.forName("oracle.jdbc.driver.OracleDriver");• What do you think this statement does, and how?• Dynamically loads a driver class, for Oracle database

• Make the connection – Connection con =

DriverManager.getConnection( "jdbc:oracle:thin:@oracle-prod:1521:OPROD", username, passwd);

• What do you think this statement does?• Establishes connection to database by obtaining

a Connection object

Page 71: Core Java Tutorial

71

2. Create JDBC statement(s)

• Statement stmt = con.createStatement() ;

• Creates a Statement object for sending SQL statements to the database

Page 72: Core Java Tutorial

72

Executing SQL Statements• String createLehigh = "Create table Lehigh "

+ "(SSN Integer not null, Name VARCHAR(32),

" + "Marks Integer)";stmt.executeUpdate(createLehigh);//What does this statement do?

• String insertLehigh = "Insert into Lehigh values“ +"(123456789,abc,100)";stmt.executeUpdate(insertLehigh);

Page 73: Core Java Tutorial

73

Get ResultSet

String queryLehigh = "select * from Lehigh";

ResultSet rs = Stmt.executeQuery(queryLehigh);//What does this statement do?

while (rs.next()) {int ssn = rs.getInt("SSN");String name = rs.getString("NAME");int marks = rs.getInt("MARKS");

}

Page 74: Core Java Tutorial

74

Close connection

• stmt.close();• con.close();

Page 75: Core Java Tutorial

75

Transactions and JDBC• JDBC allows SQL statements to be grouped together into a single

transaction• Transaction control is performed by the Connection object, default

mode is auto-commit, I.e., each sql statement is treated as a transaction

• We can turn off the auto-commit mode with con.setAutoCommit(false);

• And turn it back on with con.setAutoCommit(true);• Once auto-commit is off, no SQL statement will be committed until an

explicit is invoked con.commit();• At this point all changes done by the SQL statements will be made

permanent in the database.

Page 76: Core Java Tutorial

76

Handling Errors with Exceptions

• Programs should recover and leave the database in a consistent state.

• If a statement in the try block throws an exception or warning, it can be caught in one of the corresponding catch statements

• How might a finally {…} block be helpful here?• E.g., you could rollback your transaction in a

catch { …} block or close database connection and free database related resources in finally {…} block