Вы находитесь на странице: 1из 60

CORE JAVA

Object Oriented Programming


All the problems in real world mapped to OOP. OOP defines things (objects), which can either do something or have something done to them. OOP creates a type (class) for these objects which has properties and behavior. OOP languages: Operations (verbs) are performed by or on Actors (objects), which have names and store data (nouns)

Objects
An object is a unique programming entity that has attributes to describe it (like adjectives in grammar) and methods to retrieve or set attribute values (like verbs in grammar). Components of a program: A real world object Behavioural responsibilities (methods) Informational responsibilities (attributes) Behaviors (methods): Things an object can do like procedures and functions in other languages. Attributes (fields): Information an object knows (has-a) like data and variables in other languages (records).

Class
A class is a blueprint of an object. A class contains attributes and behavior. To access the attributes and behavior, create an object of the class. This process is called instantiation. The created object is called an instance. Example: Automobile is a class Car is an instance of class Automobile
NIIT

Java Handout 1

OOP Features

Abstraction
A programmer should focus on the overall working of an object and ignore specific details regarding the inner-workings of an object. This concept is called abstraction.

Encapsulation
Abstraction in OOP is closely related to a concept called encapsulation. The OOP offers two major benefits as flexibility and maintainability. A programmer should write the classes and code in a way that supports flexibility and maintainability. To have maintainability, flexibility and extensibility in the design, a programmer should incorporate the encapsulation. Ways to include encapsulation: Declare instance variables protected (with an access modifier, often private). Declare methods as public accessor, and force calling code to use those methods rather than directly accessing the instance variable. Encapsulation keeps code safe from outside interference and misuse. Encapsulation: Example Bank machine Hidden data: Account balance, Personal information Interface: Deposit, Withdraw, Transfer, Display account information

Inheritance
One of the main features of OOP is inheritance. A process to inherit the properties of its superclasses is called inheritance. A child class inherits its properties and attributes from its parent class. Inheritance is the process by which one object acquires the properties of another object. While implementation of inheritance define all the general properties and methods in the superclass; and general properties and methods in the subclass.

Polymorphism
Polymorphism is a Greek word and its meaning many forms. In this case subclasses can define their own unique behaviours; they share some of the similar functionality of the parent class. It changes the behavior according to what object instance is holding it.
2 Java Handout NIIT

For example, in the base class a method is defined as shape and in subclasses polymorphism enables the programmer to define different area methods as per requirement in various classes, such as circles, rectangles and triangles. In this case create an object of shape and instantiate with various classes as circles, rectangles and triangles.

Method Overloading
In this case functions share the same name, having different signature. The signature includes return type and parameter list. For example:

Method overriding:
A method defined in a superclass is redefined in a subclass with an identical method signature. As the signatures are identical, rather than overloading the method, it is instead overriding the method. For subclass objects, the definition in the subclass replaces the version in the superclass.

Features or Characteristics of Java


The features of Java are: Simple Object oriented Secure Platform independent Robust Portable Automatic garbage collection Dynamic Multithreaded Distributed

Overview of Java Virtual Machine


Java Virtual Machine (JVM) specification defines the JVM as an imaginary (virtual) machine that is implemented by emulating it in software on a real machine. Code for the JVM is stored in .class files.
Java Handout 3

NIIT

It makes Java language to be platform independent. JVM is implemented in a Java technology development tool or in a Web browser. Bytecode: Bytecode is a highly optimized set of instructions designed to be executed by the JVM. Java compiler converts the java code in bytecode at the time of compilation which enforces the security. J2SE stands for Java 2 Standard Edition. From Java SDK API version 1.5 onwards, this is referred to as Java SE (Java Standard Edition). The JRE provides the libraries, JVM, Java Interpreter, and other components necessarily for you to run applets and applications written in Java. JRE is responsible for loading, verifying, and executing the bytecodes. The JDK includes the JRE and command-line development tools, such as compilers and debuggers which are necessary for developing applets and applications. The Java API is a code that is written earlier, organized into packages of similar topics, and it is a part of JDK libraries. It allows reusability.

Java SE or J2SE Runtime Environment


Defining a Class
A class is a basic building block of an object oriented language. A class is a template that contains the data and the methods. Methods are used to manipulate the class data. Examples of class: Car The following Java program defines a class Car with data member brand:
class Car { private String brand; public void setBrand(String a Brand) { brand = aBrand; } public String getBrand() { return brand;
4 Java Handout NIIT

} }

The data members in a class can be defined as follows: Instance variable: An instance variable scope is confined to the object where it is declared. Two different objects, even if they belong to the same class, can have different values for each instance variable. Class variable: The data that is shared by all the objects are declared as class variables. One copy of each variable is maintained with one object. So multiple objects will have their own copy of class variables with respective values. These variables exist even if no object of the class is created. Data members of the class are normally declared as instance variables using the keyword private.

Creating Objects
An object is created for a class to access the defined methods. The following statement creates an object: Car BMW= new Car();

Packages
In Java library all the classes belong to a package. In the Java API, classes are grouped into packages. A class has a full name, which is a combination of the package name and the class name. For example, the class Checkbox is actually java.awt.Checkbox. To use a class in a package other than java.lang (default package), you must tell Java the full name of the class. To add a class in a package, add a package statement at the top of the source code file, before any import statement like package com.myPackage. To be in a package, a class must be in a directory structure that exactly matches the package structure. For a class, com.myPackage.Book, the Book class must be in a folder named myPackage, which is in a folder named com. Organizing your classes into packages prevents naming collisions with other classes.
Java Handout 5

NIIT

Import Statement
A set of import statements look like the following: import java.io.*; import java.util.ArrayList; import java.util.Date; import java.util.Properties; The import statements must come immediately after the package statement and before the class statement.

Object Class
Object class is the superclass. All the classes are extended from Object class. Any class that does not explicitly extend another class, implicitly extends Object class. Few of the important methods of the Object class are as follows: equals(Object obj) : Indicates whether some other object is "equal to" this one and it returns a boolean value as true or false toString() : Returns a string representation of the object hashCode() : Returns a hash code value (of integer type) for the object

The main Method


In Java, everything is written in a class. The source code file is saved with a .java extension. This is then compiled into a new class file (with a .class extension) When you run your program, you are really running a class. While execution of program Java Virtual Machine (JVM) load the class and execute its main() method. Keep running till all the code in main() method is finished. The main() method is a start-up method. Every Java application should have at least one main() method. The main() method will be written as shown in the following code:
public static void main (String[] args) { // Write the code here }

The System.out.println (SOP) Method


The System class is available in the java.lang package. The out is a field of the System class representing the standard output stream.
NIIT

6 Java Handout

To write on console following statement is used:


System.out.println(Sample Statement);

It inserts a new line after writing the statement on the console.

Code Structure in Java


Write a class in a source file Write methods in a class Write statements in a method Example
/** * Sample program to print This is my first Java program * */ class MyFirstProgram { // Declare class MyFirstProgram void displayMessage() { System.out.println("This is my first Java program"); } public static void main(String[] args) { MyFirstProgram myFirstProgram = new MyFirstProgram(); myFirstProgram.displayMessage(); } }

Save the preceding contents in a file called MyFirstProgram.java

Compile and Run a Java Program


Compile: To compile MyFirstProgram.java source file in a MS-DOS prompt, give the following command:
javac MyFirstProgram.java

After successfully compiling the earlier source file, the compiler generates MyFirstProgram.class file, which is made up of bytecodes. The compiled bytecode is platform independent. Run: To run the earlier Java program in a MS-DOS prompt, give the following command:
java MyFirstProgram

The JVM translates the bytecode into something that the underlying platform understands, and runs your program. The following output will be displayed in the command prompt after running the earlier command:
NIIT Java Handout 7

This is my first Java program

Java Keywords
Keywords are predefined identifiers reserved by Java for a specific purpose. You cannot use keywords as names for your variables, classes, methods, and so on.

A list of Java keywords are as follows:


abstract assert boolean break byte case catch char class const Continue Default Do Double Else Enum Extends Final Finally Float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while

Java Literals
Literals are tokens that do not change. They are constant in value. The different types of literals in Java are: Integer Literals Floating-Point Literals Boolean Literals Character Literals String Literals

Java Literals: Integer


decimal (base 10) hexadecimal (base 16) octal (base 8)

Java Literals: Floating point


Represents decimals with fractional parts: Example: 5.255 Can be expressed in standard or scientific notation: Example: 583.45 (standard), 5.8345e2 (scientific)
8 Java Handout NIIT

Java Literals: Boolean


Boolean literals have only two values, true or false.

Java Literals: Character


Character Literals represent single Unicode characters. To use a character literal, enclose the character in single quote delimiter. For example: The letter a, is represented as a. Special characters such as a newline character, a backslash is used followed by the character code. For example, \n for the newline character, \r for the carriage return, and \b for backspace.

Unicode character: A 16-bit character set that replaces the 8-bit ASCII character set. Unicode allows the inclusion of symbols and special characters from other languages.

Java Literals: String


String literals represent multiple characters and are enclosed by double quotes. An example of a string literal is, This is a sample.

Primitive Data Types


The Java programming language defines eight primitive data types: boolean (for logical) char (for textual) byte short int long (integral) double float (floating point)

Primitive Data Types: Logical-boolean


A boolean data type represents two states of true and false. An example is boolean result = true; In the preceding statement, declared a variable named result as boolean type and assigned it a value of true.
NIIT Java Handout 9

Primitive Data Types: Textual-char


A character data type (char), represents a single Unicode character. It must have its literal enclosed in single quotes( ). For example the following code: x //The letter x \t //a tab To represent special characters like ' (single quotes) or " (double quotes), use the escape character \. For example the following code: '\'' //for single quotes '\"' //for double quotes

Primitive Data Types: Integral byte, short, int, and, long


Integral data types in Java uses three forms of decimal, octal, or hexadecimal. Examples are: 5// The decimal value 5 088 // The leading 0 indicates an octal value 0xBABB // The leading 0x indicates a hex value Integral types has int as default data type. A long value can be defined by appending the letter l or L. For example: 20L

Integral data type have the following ranges:


Integer Length 8 bits 16 bits 32 bits 64 bits Name or Type byte short int long Range -27 to 27-1 -215 to 215-1 -231 to 231-1 -263 to 263-1

Coding Guidelines: In defining a long value, a lowercase L is not recommended because it is hard to distinguish from the digit 1.

10 Java Handout

NIIT

Variables
A variable is an item of data used to store the state of objects. A variable consist of data type and name. Data type determines what type of value it will hold.

Declaring and Initializing Variables


Declare a variable as follows: <data type> <name> [=initial value];

Reference Variables Versus Primitive Variables


Two types of variables can be created in Java as Primitive and Reference. Primitive Variables: Variables with primitive data types such as int or long. Stores data in the actual memory location of where the variable is present. Reference Variables: Variables that store the address in the memory location Points to another memory location where the actual data is present When you declare a variable of a certain class, you are actually declaring a reference variable to the object with that certain class.
Example of a reference variable and primitive variable

Suppose you have two variables with data types int and String. int num = 20; // primitive type String name = "Welcome"; // reference type

Type Casting
Type Casting is the mapping type of an object to another. Casting Primitive Types
NIIT Java Handout 11

Casting between primitive types enables you to convert the value of one data from one type to another primitive type. Commonly occurs between numeric types. Boolean data type data cannot be typecast. Types of Casting are: Implicit Casting Explicit Casting Implicit Casting Suppose you want to store a value of int data type to a variable of data type double. int numIntVar = 20; double numDoubleVar = numIntVar; //implicit cast In this example, as the data type (double) of the destination variable holds a larger value than the data type (int) of the value, the data is implicitly casted to the data type double of the destination variable.

12 Java Handout

NIIT

Example of implicit casting: int numInt1 = 1; int numInt2 = 2; //result is implicitly cast to type double double numDouble = numInt1/numInt2; Explicit Casting When you convert a data that has a large type to a smaller type, you must use an explicit cast. Explicit casts take the following form: (Type) value where, Type is the name of the type you are converting to value. It is an expression that results in the value of the source type.
Explicit Casting Examples
double valDouble = 20.12; int valInt = (int)valDouble; //convert valDouble to int type double x = 20.2; int y = 4; int result = (int)(x/y); //typecast result of operation to int

Operators
Different types of operators are: Arithmetic operators Relational operators Logical operators Conditional operators Binary operator These operators follow a certain kind of precedence so that the compiler will know which operator to evaluate first, in case multiple operators are used in one statement. Arithmetic Operators + -- add - -- Subtract * - Multiply
NIIT Java Handout 13

/ - Divide Increment and Decrement Operators There are two unary increment operator (++) and unary decrement operator (--). Logical Operators Logical operators have one or two boolean operands that yield a boolean result. There are six logical operators: && (logical AND) & (boolean logical AND) || (logical OR) | (boolean logical inclusive OR) ^ (boolean logical exclusive OR) ! (logical NOT) Logical Operators: || (logical) and | (boolean logical) inclusive OR Logical Operators: ^ (boolean logical exclusive OR) Logical Operators: Conditional Operator (?:) The instanceof Operator The instanceof operator is a binary operator that determines whether an object reference (the left operand) is an instance of the class, interface, or array type specified by the right operand. The instanceof operator cannot be used with primitive types (this results in a compilation error).

Introduction to Arrays Declaring Arrays


To declare an array, write the data type, followed by a set of square brackets[], followed by the identifier name. For example,
int []ages; or int ages[];

14 Java Handout

NIIT

Array Instantiation
Once array is created specify its length with a constructor statement.
Constructor:

A constructor is a method that is called to initialize the object and variable. To instantiate (or create) an array, use the new keyword, followed by the square brackets containing the number of elements you want the array to have. For example,
//declaration int grade[]; //instantiate object grade = new int[50]; or, can also be written as, //declare and instantiate object int grade[] = new int[50];

You can also instantiate an array by directly initializing it with data. For example,
int arr_no[] = {1, 2, 3, 4, 5};

Multidimensional Arrays
Multidimensional arrays are implemented as arrays of arrays. Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name. For example:
// integer array 200 x 300 elements int[][] twoDim = new int[200][300]; // character array 16 x 32 x 48 char[][][] threeDim = new char[16][32][48]; // String array 4 rows x 2 columns String[][] breed_color = {{ "terry", "brown" }, { "kristin", "white" }, { "toby", "gray"}, { "fido", "black"} };

NIIT

Java Handout 15

The Wrapper Classes


Primitive data types are not objects: Cannot access methods of the Object class. Only actual objects can access methods of the Object class. Need of wrapper classes: Need an object representation for the primitive type. variables to apply methods that are in-built in Java.

Definition: Object representations of simple variables that are not object variables. An instance of a wrapper contains, or wraps, a primitive value of the corresponding type. The wrappers are normal classes in the java.lang package that extend the Object superclass like all Java classes. Other than for the primitive type int, the wrappers come with the same name as the corresponding primitive type except that the first letter is capitalized: o Integer is a wrapper class of the primitive int o Character is a wrapper class of the primitive char o Double is a wrapper class of the primitive double

Primitive Types: Wrapper Classes


The following table lists the primitive types and the corresponding wrapper classes:
Primitive boolean byte char double float int long short void Wrapper java.lang.Boolean java.lang.Byte java.lang.Character java.lang.Double java.lang.Float java.lang.Integer java.lang.Long java.lang.Short java.lang.Void

Autoboxing
The autoboxing feature added to Java 5.0 does the conversion (wrapping) from primitive to wrapper object.
16 Java Handout NIIT

This "wrapping" is called "autoboxing" in the sense that the primitive value is automatically "boxed up" into the wrapper object. Autoboxing is available for all the primitive or wrapper types.

Method Arguments
If a method takes a wrapper type, then you can pass a reference to a wrapper or a primitive of the matching type. If a method takes a primitive, then you can pass in either a compatible primitive or a reference to a wrapper of that primitive type.
Example: void takeNumber(Integer i) { }

Return Values
If a method declares a primitive return type, then you can return either a compatible primitive or a reference to the wrapper of that primitive type. If a method declares a wrapper return type, then you can return either a reference to the wrapper type or a primitive of the matching type. Example:
int giveNumber() { return x; }

In the preceding example, x can be either a reference to Integer wrapper or int primitive type.

Control Structures
Control structures allows you to change the ordering of how the statements in your programs are executed Two types of control structures are: Decision control structures: Allows you to select specific sections of code to be executed Repetition control structures: Allows you to execute specific sections of the code a number of times.

Decision Control Structures

NIIT

Java Handout 17

Decision control structures are Java statements that allows you to select and execute specific blocks of code on the basis of condition. Types of decision control structures are: if-statement if-else-statement if-else if-statement

if-statement
if-statement specifies that a statement (or block of code) will be executed if and only if a certain boolean statement is true. if-statement has the form:
if( boolean_expression ) statement or if( boolean_expression ){ statement1; statement2; }

where boolean_expression is either a boolean expression or boolean variable.

switch Statement
switch allows branching on multiple outcomes. Its a substitute of if-else. switch statement has the form:
switch( switch_expression ){ case case_selector1: statement1;// statement2;//block 1 break; case case_selector2: statement1;// statement2;//block 2 break; : default: statement1;//
18 Java Handout NIIT

statement2;//block n }

Repetition Control Structures


Repetition control structures are Java statements which allows to execute specific blocks of code a number of times. Types of repetition control structures are: while-loop do-while loop for-loop

while-loop
Statement written in the while loop block are executed till the condition is satisfied. while loop has the following form:
while( boolean_expression ){ statement1; statement2; . . . }

do-while-loop
It is similar to while loop. But block of statements will be executed at least once. After that it will execute the statements based on the condition is true. do-while loop has the following form:
do{ statement1; statement2; . . . }while( boolean_expression );

for-loop

for loop allows execution of the same code a number of times. for loop has the following form:
for(InitializationExpression;LoopCondition;StepExpression) { statement1; statement2; . . .
NIIT Java Handout 19

Branching Statements
Branching statements allows you to redirect the flow of program execution. Java offers three branching statements: break continue return

Constructors
Java provides a special construct named constructor exclusively for creating an object of a class and initializing its instance variables. Constructors should have the same name as the name of the class. It is generally declared as public. It may have optional list of arguments. It does not have any return type and not even void. You cannot invoke a constructor on an existing object. You can use a constructor only in combination with the new operator.

To declare a constructor, you write,


<modifier> <className> (<parameter>*) { <statement>* }

Default Constructor (Method)


Constructor without any parameters If the class does not specify any constructors, then an implicit default constructor is created. Example: Default Constructor Method of StudRec Class
public StudRec() { //some code here }

Declaring Methods
To declare methods you write,
<modifier> <returnType>
20 Java Handout NIIT

<name>(<parameter>*) { <statement>* }

Where: <modifier> can carry a number of different modifiers <returnType> can be any data type (including void) <name> can be any valid identifier <parameter> can be one or more parameters passed as argument to the method. Each <parameter> is associated with a parameter type (primitive or object) and a parameter name.

Accessor (Getter) Methods


Accessor methods: Used to read values from your class variables (instance or static) Usually written as get<NameOfInstanceVariable> It also returns a value

Mutator (Setter) Methods


Mutator Methods: Used to write or change values of your class variables (instance or static) Usually written as set<NameOfInstanceVariable>

Static Methods
Example:
public class StudRec { private static int studentCount; public static int getStudentCount(){ return studentCount; } }

Where: public means that the method can be called from objects outside the class.

NIIT

Java Handout 21

static means that the method is static and should be called by typing, [ClassName].[methodName]. For example, in this case, you call the method StudRec.getStudentCount() int is the return type of the method. This means that the method should return a value of type int. getStudentCount is the name of the method. () means that your method does not have any parameters.

Method Overloading
Method overloading: It allows a method with the same name but different parameters, to have different implementations and return values of different types It is used when the same operation has different implementations

Access Modifiers
Access modifiers are used to define the scope of a variable or method or class. There are four different types of access modifiers in Java: public (Least restrictive) protected default private (Most restrictive)

public Accessibility
Public access: Specifies that class members (variables or methods) are accessible to anyone, both inside and outside the class and outside of the package Any object that interacts with the class can have access to the public members of the class Keyword: public

22 Java Handout

NIIT

protected Accessibility
Protected access: Specifies that the class members are accessible only to methods in that class and the subclasses of the class The subclass can be in different packages Keyword: protected

default Accessibility
Default access: Specifies that only classes in the same package can have access to the variables and methods of the class No actual keyword is their for the default modifier and it is applied in the absence of an access modifier

private Accessibility
Private accessibility: Specifies that the class members are only accessible by the class in which they are defined Keyword: private

Java Program Structure: The Access Modifiers


private Same class Yes Same package Different package (subclass) Different package (non-subclass) default/package Yes Yes protected Yes Yes Yes public Yes Yes Yes Yes

Inheritance
Inheritance is the concept, used to inherit the variables and methods defined in the parent class (super class) in the child class (sub class). Generalized variables and methods are defined in the super class and specialized variables and methods are defined in the sub class.

NIIT

Java Handout 23

Deriving a Subclass
The extends keyword is used to inherit the class. Suppose you have a parent class called Automobile.
public class Automobile { protected String brandname; protected String address; /** * Default constructor */ public Automobile (){ System.out.println(Inside Automobile:Constructor); brandname = ""; address = ""; } . . . . }

extends Keyword
Now, you want to create another class named Car. Since a car is also an automobile, therefore, use the extend keyword to inherit all the properties and methods of the existing class Automobile.

To do this, you write,


public class Car extends Automobile { public Car(){ System.out.println(Inside Car:Constructor); } . . . . }

Use of Subclass
A subclass inherits all of the public and protected members (fields or methods) of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, then it also inherits the package-private members (fields or methods) of the parent.

Fields
The inherited fields can be used directly, just like any other fields. You can declare new fields in the subclass that are not in the super class. You can declare a field in the subclass with the same name as the one in the super class, thus hiding it (not recommended).

24 Java Handout

NIIT

A subclass does not inherit the private members of its parent class. However, if the super class has public or protected methods for accessing its private fields, these can also be applied by the subclass.

Methods
The inherited methods can be used directly as they are. You can write a new instance method in the subclass that has the same signature as the one in the super class, thus overriding it. You can write a new static method in the subclass that has the same signature as the one in the super class, thus hiding it. You can declare new methods in the subclass that are not in the super class.

Object Class
Object class is mother of all classes. In Java language, all classes are subclassed (extended) from the Object super class. Object class is the only class that does not have a parent class Object class defines and implements behavior common to all classes including the ones that you write. Following are some of the important methods of the Object class: o getClass() o equals() o toString()

How Constructor Method of a Super Class gets Called


A subclass constructor invokes the constructor of the superclass implicitly. When a Car object, a subclass (child class), is instantiated, the default constructor of its super class (parent class), Automobile class, is invoked implicitly before the constructor method of the subclass is invoked. A subclass constructor can invoke the constructor of the super explicitly by using the super keyword: o The constructor of the Car class can explicitly invoke the constructor of the Automobile class using super keyword o Used when passing parameters to the constructor of the super class

Example: Constructor Calling Chain


To illustrate this, consider the following code:
public static void main( String[] args ){
NIIT Java Handout 25

Car hondacity = new Car(); }

In the code, you create an object of class Car. The output of the program is: Inside Automobile:Constructor Inside Automobile:Constructor Example: Constructor Calling Chain

The super Keyword


A subclass can also explicitly call a constructor of its immediate super class. This is done by using the super constructor call. A super constructor call in the constructor of a subclass will result in the execution of relevant constructor from the super class, based on the arguments passed. In the given the following code for Car:
public Car(){ super( "BrandName", "Address" ); System.out.println("Inside Car:Constructor"); }

Few things to remember when using the super constructor call: The super() call must occur as the first statement in a constructor. The super() call can only be used in a constructor (not in ordinary methods). Another use of super is to refer to members of the super class (just like the this reference ). For example:
public Car() { super.brandname = somename; super.address = some address; }

Overriding Methods
If a derived class needs to have a different implementation of a certain instance method from the super class, then override that instance method in the sub class. The overriding concept applies only to instance methods. For static methods, it is called hiding methods. The overriding method has the same name, number and type of parameters, and return type as the method it overrides.
NIIT

26 Java Handout

Example: Overriding Methods


Suppose you have the following implementation for the getName method in the Automobile super class:
public class Automobile { : : public String getName(){ System.out.println("Parent: getName"); return name; } } To override the getName() method of the superclass Automobile in the subclass Car, reimplement the method with the same signature. public class Car extends Automobile{ : public String getName(){ System.out.println("Car: getName"); return name; } : }

Now, when you invoke the getName() method of an object of the subclass Car, the getName() method of the Car class would be called, and the output would be: Car: getName

Modifiers in the Overriding Methods


The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the super class can be made public, but not private, in the subclass. You will get a compile-time error if you attempt to change an instance method in the super class to a class method in the subclass, or change the class method to an instance method in the super class.

Hiding Methods
If a subclass defines a class method (static method) with the same signature as a class method in the super class, then the method in the subclass hides the one in the super class.

Example: Coding of Hiding Static Method


class Animal { public static void testClassMethod() {
NIIT Java Handout 27

System.out.println("The class method in Animal."); } } // The testClassMethod() of the child class hides the one of // the super class it looks like overriding, doesn't it? class Cat extends Animal { public static void testClassMethod() { System.out.println("The class method in Cat."); } }

Abstract Methods
Methods that do not have implementation (body) are called abstract methods. To create an abstract method, just write the method declaration without the body and use the keyword abstract. No { } Please make this point that there are no parentheses will be available. For example,
// Note that there is no body public abstract void someMethod();

Abstract Class
An abstract class is a class that contains one or more abstract methods. An abstract class cannot be instantiated. You will get a compile error on the following code
MyAbstractClass a1 = new MyAbstractClass();

Another class (Concrete class) has to provide implementation of abstract methods: o Concrete class has to implement all abstract methods of the abstract class in order to be used for instantiation o Concrete class uses extends keyword

Sample Abstract Class


public abstract class LivingThing { public void breath(){ System.out.println("Living Thing breathing..."); } public void eat(){ System.out.println("Living Thing eating..."); } /** * Abstract method walk() * We want this method to be implemented by a
28 Java Handout NIIT

* Concrete class. */ public abstract void walk(); }

Extending An Abstract Class


When a concrete class extends the LivingThing abstract class, it must implement the abstract method walk() , or else, that subclass will also become an abstract class, and therefore cannot be instantiated. For example,
public class Human extends LivingThing { public void walk(){ System.out.println("Human walks..."); }

What is an Interface
All methods of an interface are abstract methods: Defines the signatures of a set of methods, without the body (implementation of the methods). A concrete class must implement the interface (all the abstract methods of the Interface). It allows classes, regardless of their locations in the class hierarchy, to implement common behaviours.

Example 1: Interface
// Note that Interface contains just set of method // signatures without any implementations. // No need to say abstract modifier for each method // since it assumed. public interface Relation { public boolean isGreater( Object a, Object b); public boolean isLess( Object a, Object b); public boolean isEqual( Object a, Object b); }

Interface versus Abstract Class


All methods of an interface are abstract methods while some methods of an abstract class are abstract methods. Abstract methods of abstract class have abstract modifier. An interface can only define constants while abstract class can have fields.

NIIT

Java Handout 29

Interfaces have no direct inherited relationship with any particular class, they are defined independently. Interfaces themselves have inheritance relationship among themselves.

When to use an Abstract Class Over Interface?


For methods that are not abstract, you want to use them when you want to provide common implementation code for all subclasses: Reducing the duplication For abstract methods, the motivation is the same with the ones in the interface to impose a common behavior for all subclasses without dictating how to implement it. Remember that a concrete can extend only one super class whether that super class is in the form of concrete class or abstract class.

Using IS-A and HAS-A


When one class inherits from another, you say that the subclass extends the super class. When you want to know if one thing should extend another, use the IS-A test. Examples for IS-A relationship: Triangle IS-A Shape Green IS-A Color When two classes are related, but not through inheritance, (for example, one class has a reference to another class) then you say that the two classes are joined by HAS-A relationship. Examples for HAS-A relationship: Bathroom HAS-A Tub Tub HAS-A Bubble

Casting Primitive Types


Casting enables us to convert the value of one data type to another primitive type. Commonly occurs between numeric types. The boolean data type cannot be cast though. Types of Casting: Implicit Casting Explicit Casting

Implicit Casting
30 Java Handout NIIT

Suppose you want to store a value of int data type to a variable of data type double.
int numInt = 10; double numDouble = numInt; //implicit cast

In this example, as the data type (double) of the destination variable holds a larger value than the data type (int) of the value, the data is implicitly casted to the data type double of the destination variable. Implicit Casting: Example
int numInt1 = 1; int numInt2 = 2; //result is implicitly casted to type double double numDouble = numInt1/numInt2;

Explicit Casting
When you convert a data that has a large type to a smaller type, you must use an explicit cast. Explicit casts take the following form:
(Type)value

where, Type is the name of the type you are converting to and value is an expression that results in the value of the source type. Explicit Casting: Example
double valDouble = 10.12; int valInt = (int)valDouble; //convert valDouble to int type double x = 10.2; int y = 2; int result = (int)(x/y); //typecast result of operation to int

Casting Objects
Instances of classes can also be cast into instances of other classes, with one restriction. The source and destination classes must be related by inheritance. One class must be a subclass of the other. Casting objects is analogous to converting a primitive value to a larger type, some objects might not need to be cast explicitly.
NIIT Java Handout 31

(classname)object

where, classname is the name of the destination class and object is a reference to the source object. Casting Objects: Example The following example casts an instance of the class VicePresident to an instance of the class Employee. VicePresident is a subclass of Employee with more information, which here defines that the VicePresident has executive room.
Employee emp = new Employee(); VicePresident veep = new VicePresident(); // no cast needed for upward use emp = veep; // must cast explicitly veep = (VicePresident)emp;

Inner Class
Inner class is a class declared within another class Accessing the members of the inner class: o Need to instantiate an object instance of an inner class first Example:
innerObj.innerMember = 5; //innerObj is an instance of the inner class //innerMember is a member of the inner class

Accessing Members of Outer Class Within an Inner Class


Methods of the inner class can directly access members of the outer class: Example:
1 2 3 4 5 6 7 class Outer { int outData; class Inner { void inMeth() { outData = 10; } }
NIIT

32 Java Handout

8 }

Java Program Structure: Inner Classes


class OuterClass1 { int data = 5; class InnerClass1 { int data2 = 10; void method() { System.out.println(data); System.out.println(data2); } }

public static void main(String args[]) { OuterClass1 ocobj = new OuterClass1(); InnerClass1 icobj = ocobj.new InnerClass1(); System.out.println(ocobj.data); System.out.println(icobj.data2); icobj.method(); } }

Static Nested Classes


A static nested class is just a class enclosed within another class, and marked with the keyword static. Static nested classes are considered a member of the enclosing or outer class. Static nested classes can access only the private static members of the outer class. Static nested class is not connected to an instance of the outer class. Static nested class cannot access the variables that are not static and methods of the outer class.

Anonymous Classes
It is common in Java programming to encounter situations where you need to create an object but do not need to bother giving it an explicit name.

NIIT

Java Handout 33

With the inner classes you can take this to another level by creating and instantiating a class without bothering to give it a name. This is called as an anonymous class. This anonymity eliminates a lot unnecessary named objects and makes the code more readable.

Exception
Exceptional event Error that occurs during run-time Cause normal program flow to be disrupted Examples are: Divide by zero errors Accessing the elements of an array beyond its range Invalid input Hard disk crash Opening a file that does not exist Heap memory exhausted
Exception Example
1 2 3 4 5 6 class DivByZero { public static void main(String args[]) { System.out.println(5/0); System.out.println(Display the output.); } }

Example: Default Exception Handling

Displays this error message:


Exception in thread "main java.lang.ArithmeticException: / by zero at DivByZero.main(DivByZero.java:3)

Default exception handler: Provided by Java run time Prints out exception description Prints the stack trace: Hierarchy of methods where the exception occurred Causes the program to terminate
34 Java Handout NIIT

What Happens when an Exception Occurs?


When an exception occurs within a method, the method creates an exception object and hands it off to the run-time system. This is called throwing an exception. Exception object contains information about the error, type of exception and the state of the program when the error occurred. The run time system searches the call stack for a method that contains an exception handler. When an appropriate handler is found, the run-time system passes the exception to the handler. o An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. o The exception handler chosen is said to catch the exception. o If the run-time system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, then the runtime system (and, consequently, the program) terminates and uses the default exception handler.

Benefits of Java Exception Handling Framework


The benefits of Java Exception Handling Framework are: Separating Error-Handling code from regular business logic code Propagating errors up the call stack Grouping and differentiating error types

Exception Class Hierarchy


The Throwable, Exception, and Error classes: Throwable class: Root class of exception classes Immediate subclasses: Error Exception

Exception class:

NIIT Java Handout 35

o Division by zero error o Array out-of-bounds error

Error class:
o Out of memory errors o Hard disk crash Used by the Java run-time system to handle errors occurring in the run-time environment

Catching Exceptions: The try-catch Statements


Syntax of try-catch statements:
try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> } ... } catch (<ExceptionTypeN> <ObjName>) { <handler if ExceptionTypeN occurs> } 1 class DivByZero { 2 public static void main(String args[]) { 3 try { 4 System.out.println(5/0); 5 System.out.println(Display the output.); 6 } catch (ArithmeticException exc) { 7 //Division by zero is an ArithmeticException 8 System.out.println(exc); 9 } 10 System.out.println(After exception.); 11 } 12 }

Throwing Exceptions: The throw Keyword


36 Java Handout NIIT

Java allows you to throw exceptions (generate exceptions).


throw <exception object>;

An exception you throw is an object. You have to create an exception object in the same way you create any other object. Example:
throw new ArithmeticException(testing...);

Example: Throwing Exceptions


class ThrowExample { public static void main(String args[]){ String input = "invalid input"; try { if (input.equals("invalid input")) { throw new RuntimeException("throw example"); } else { System.out.println(input); } System.out.println("After throwing"); } catch (RuntimeException e) { System.out.println("Exception caught:" + e); } } }

Using Java Exception Handling


Any checked exceptions that can be thrown within a method must be specified in its throws clause.
function1 { try { call function2; } catch (Exception ex) { doErrorProcessing; } } function2 throws Exception { call function3; } function3 throws Exception { call readDataFile;
NIIT Java Handout 37

Checked and Unchecked Exceptions


Checked exception: Java compiler checks if the program either catches or lists the occurring checked exception If not, then compilation error will occur Unchecked exceptions: Not subjected to checking at the time of compilation for exception handling Built-in unchecked exception classes: o Error o RuntimeException o Their subclasses Handling all these exceptions may make the program cluttered and may become a nuisance

Creating Your Own Exception Class


Steps to follow for creating your own exception class are: 1. Create a class that extends the RuntimeException or the Exception (Base class) class. 2. Customize the class: Members and constructors may be added to the class. Example:
class MyExceptionClass extends RuntimeException { /* some code */ }

How to use Your own Exceptions


class TestExceptionClass { public static void main(String args[]) { String input = "invalid input"; try { if (input.equals("invalid input")) { throw new MyExceptionClass(); } System.out.println("Good string.");
38 Java Handout NIIT

} catch (MyExceptionClass e) { System.out.println("Bad string!"); } } }

The String Class


The String class represents collection of character literals. It can be represented as array of characters. Note: A String object is different than an array of characters.

The String Class: Constructors


1 class StringConstructorsExample { 2 public static void main(String args[]) { 3 String s1 = new String(); //empty string 4 char chars[] = { 'h', 'e', 'l', 'l', 'o'}; 5 String s2 = new String(chars); //s2="hello"; 6 byte bytes[] = { 'w', 'o', 'r', 'l', 'd' }; 7 String s3 = new String(bytes); //s3="world" 8 String s4 = new String(chars, 1, 3); 9 String s5 = new String(s2); 10 String s6 = s2; 11 System.out.println(s1); 12 System.out.println(s2); 13 System.out.println(s3); 14 System.out.println(s4); 15 System.out.println(s5); 16 System.out.println(s6); 17 } 18 }

The String Class: Methods


The methods of String class are: Method
public char charAt (int index) public int compareTo (String
NIIT

Definition Returns the character located in the specified index. Compares this string with the specified
Java Handout 39

anotherString)

parameter. 1. It returns a negative value if passed string is less than the compared string. 2. It returns a positive value if passed string is greater than the compared string. 3. It returns a zero value if passed string is equal to the compared string. Like compareTo but ignores the case used in this string and the specified string. Returns true if compared and passed strings are same and both the objects are string objects. Returns false if compared and passed strings are not same and inspite of both the objects are string objects. Like equals but ignores the case used in this string and the specified string. Get the characters starting from the srcBegin index up to the srcEnd index and copies these characters to the dst array starting at the dstBegin index. Returns a length of the string. Returns the string wherein all occurences of the oldChar in the string is replaced with newChar. Returns the substring of the string starting from the specified beginIndex up to the endIndex index. Convert the string into character array and returns the same. Returns a string wherein the leading and trailing white space are removed. Takes in a simple data type such as boolean, integer, or character, or it takes in an object as a parameter and returns the String equivalent of the specified
NIIT

public int compareToIgnoreCase (String str) public boolean equals (Object anObject)

public boolean equalsIgnoreCase (String anotherString) public void getChars (int srcBegin, int srcEnd, char[] dst, int dstBegin) public int length() public String replace (char oldChar, char newChar) public String substring (int beginIndex, int endIndex) public char[] toCharArray() public String trim() public static String valueOf(-)

40 Java Handout

parameter.

The StringBuffer Class


There is a problem with String objects as once they are created they cannot be modified because String is a final class. A StringBuffer object is same as String object. But its mutable and can be modified. Like length and content may get changed through some method calls. The StringBuffer Class: Methods Method public int capcity() public StringBuffer append(-) public char charAt(int index) public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Definition Returns the current capacity of the StringBuffer object. Append the passed parameter value. Returns the character located at the specified index value. Get the characters starting from the srcBegin index up to the srcEnd index and copies these characters to the dst array starting at the dstBegin index. Delete the characters from within the range. Insert the value at the specified offset.

public String Buffer delete(int start, int end) public StringBuffer insert(int offset,-)

The java.lang.StringBuilder Class


J2SE5.0 added the StringBuilder class, which is a drop-in replacement for StringBuffer in cases where thread safety is not an issue. It should be used when multithreading implementation is required. The StringBuilder is not synchronized therefore it offers faster performance than StringBuffer. As a best practice we should apply StringBuilder instead of StringBuffer. The J2SE 5.0 javac compiler normally uses StringBuilder instead of StringBuffer whenever you perform string concatenation as in System.out.println("The result is " + result); All the methods available on StringBuffer are also available on StringBuilder, so it really is a drop-in replacement.

NIIT

Java Handout 41

The String class defines a new constructor that enables you to construct a String from a StringBuilder as shown in the following code:
String(StringBuilder strBuildObj)

Collection
A collection object groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers).

Collection Framework
A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following: Interfaces Implementations Algorithms

Benefits of Collection Framework


The benefits of collection framework are: Reduces programming effort Increases program speed and quality Allows interoperability among unrelated APIs: The collection interfaces are the vernacular by which APIs pass collections back and forth Reduce effort to learn and use new APIs Reduces effort to design new APIs Fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable

Collection Interfaces
Collection interfaces are abstract data types that represent collections. Collection interfaces are in the form of Java interfaces. Interfaces allow collections to be manipulated independently of the implementation details of their representation, which is called the polymorphic behavior.
42 Java Handout NIIT

In Java programming language (and other object-oriented languages), interfaces generally form a hierarchy. You choose one that meets your need as a type.

Implementations
Implementations are the data objects used to store collections, which implement the interfaces. Java Collections Framework also provides several implementations for special purpose situations that require nonstandard performance, usage restrictions, or other unusual behavior.

Collection Interface
Collection interface is the root of the collection hierarchy. Collection interface is the least common denominator that all collections implement. Every collection object is a type of Collection interface. Collection interface is used to pass collection objects around and to manipulate them when maximum generality is desired. Apply Collection interface as a type. JDK (Java Development Kit) does not provide any direct implementations of this interface but provides implementations of more specific sub interfaces, such as Set and List.

Set Interface
The Set interface is a collection that does not allow duplicate elements. The Set interface models the mathematical set abstraction and is used to represent sets: Cards comprising a poker hand Courses making up the schedule of a student The processes running on a machine

Set Interface (Java SE 5)


public interface Set<E> extends Collection<E> { // Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional
NIIT Java Handout 43

Iterator<E> iterator(); // Bulk operations boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); //optional boolean removeAll(Collection<?> c); //optional boolean retainAll(Collection<?> c); //optional void clear(); //optional // Array Operations Object[] toArray(); <T> T[] toArray(T[] a); }

Implementations of Set Interface


The implementations of Set interface are: HashSet TreeSet LinkedHashSet

HashSet
HashSet is much faster than TreeSet (constant-time versus log-time for most operations) but it does not arrange the data in specific order. HashSet is the most commonly used implementation.

Caveats of Using HashSet


Iteration is linear in the sum of the number of entries and the number of buckets (the capacity): Choosing an initial capacity that is too high, can waste both space and time Choosing an initial capacity that is too low, wastes time by copying the data structure each time it is forced to increase its capacity

TreeSet
The TreeSet is one of two sorted collections (the other being TreeMap). It does not allow duplicate data and it iterates in sorted order as ascending.

LinkedHashSet
LinkedHashSet is implemented as a hash table with a linked list running through it. It provides insertion-ordered iteration (least recently inserted to most recently) and runs nearly as fast as HashSet.
44 Java Handout NIIT

It spares its clients from the unspecified, generally chaotic ordering provided by HashSet without incurring the increased cost associated with TreeSet.

List Interface
List interface is an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The list elements are accessed by their integer index (position).

Additional Operations Supported by List Interface over Collection


The additional operations supported by List interface over Collection interface are: Elements are accessed based on the numerical position in the list. Search searches for a specified object in the list and returns its numerical position. Iteration extends Iterator semantics adds an advantage of the sequential nature of the list. Range-view performs arbitrary range operations on the list.

Implementations of List Interface


The implementations of List interface are: ArrayList: o Offers constant-time positional access o Provides fast iteration and fast random access o Ordered collection (by index), but not sorted o Most commonly used implementation LinkedList: It allows to add elements to the beginning of the List or iterate over the List to delete elements from its interior.

Map Interface
Map interface handles key or value pairs. A Map interface cannot contain duplicate keys. Each key can map to at most one value.

NIIT

Java Handout 45

Map Interface (Java SE 5)


public interface Map<K,V> { // Basic operations V put(K key, V value); V get(Object key); V remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); // Bulk operations void putAll(Map<? extends K, ? extends V> m); void clear(); // Collection Views public Set<K> keySet(); public Collection<V> values(); public Set<Map.Entry<K,V>> entrySet(); // Interface for entrySet elements public interface Entry { K getKey(); V getValue(); V setValue(V value); }

SortedMap Interface
The SortedMap interface maintains the mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key or value pairs, such as dictionaries and telephone directories.

Implementations of Map Interface


The implementations of the Map interface are: HashMap: To be used in case speed is the objective and iteration order is not the criteria. Most commonly used implementation. TreeMap: To be used in case SortedMap operations or key-ordered Collection-view iteration is the objective. LinkedHashMap: It is slower than HashMap for adding and removing elements but faster iteration with a LinkedHashMap.

Queue Interface
Queue interface is a collection it holds multiple elements prior to processing.
NIIT

46 Java Handout

Apart from basic Collection operations, a Queue interface provides additional insertion, extraction, and inspection operations. Typically, but do not necessarily, Queue interface order elements in a FIFO (First-In, First-Out) manner.

Implementations of Queue Interface


General purpose Queue implementations: LinkedList implements the Queue interface, provides FIFO queue operations for addition, polling, etc. PriorityQueue class is a priority queue based on the heap data structure. The order of elements can be specified at the time of construction which can be the natural order of the elements or the order imposed by an explicit Comparator.

Two Schemes of Traversing Collections


There are two ways of traversing collections are: for-each: The for-each construct allows you to concisely traverse a collection or array using a for loop
for (Object o: collection) System.out.println(o);

Iterator: An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired.

Iterator Interface
public interface Iterator { boolean hasNext(); Object next(); void remove(); //optional }

hasNext() method returns true if the iteration has more elements. next() method returns the next element in the iteration. remove() is the only safe way to modify a collection during iteration. The behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

NIIT

Java Handout 47

Use Iterator Over for-each


Iterator is used over for-each for removing the current element: The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.
static void filter(Collection<?> c) { for (Iterator<?> it = c.iterator(); it.hasNext(); ) if (!cond(it.next())) it.remove(); }

Iterating over multiple collections in parallel.

The Iterable Interface


Iterable is a generic interface that was added by Java 2, v5.0. A class must implement Iterable whenever an object needs to be used within a for-each style for loop in that class. Iterable has the following declaration:
interface Iterable<T>

It defines one method, iterator(), as shown here:


Iterator<T> iterator()

It returns an iterator to the set of elements contained in the invoking object. Although the for-each form of the for loop was designed with arrays and collections in mind, it can be used to cycle through the contents of any object that implements the Iterable interface. This enables you to create classes whose objects can be applied with the foreach form of the for loop. This is a powerful feature that substantially increases the types of programming situations to which the for can be applied.

Threads
Threads are required to handle concurrent processes. Threads provide single sequential flow of control within a program. Example: o Operating System o HotJava Web browser

48 Java Handout

NIIT

Multi-Threading in Java Platform


Every application has at least one thread which is called default thread. It may use several threads. For example, system threads that do things like memory management and signal handling. An application has one thread, called the main thread. Using this thread other thread can be created.

Thread Priorities
Priorities determine, which thread receives CPU control and gets to be executed first. Priority ranging from one to 10. Higher the thread priority larger is the chance of being executed first Example: o Two threads are ready to run o First thread: priority of 5, already running o Second thread = priority of 10, comes in while first thread is running Context switch: Occurs when a thread snatches the control of CPU from another When more than one thread having highest priority is ready to run then decision which thread will be executed dependens on the operating system. o -sliced round-robin o control

The Thread Class: Constructor


The Thread class has eight constructors. Some of the important constructors are as follows: Method
Thread() Thread(String name) Thread(Runnable target)

Description Creates a new Thread object. Creates a new Thread object with the specified name. Creates a new Thread object based on a Runnable object, target refers to the object whose run method is called. Creates a new Thread object the specified name and based on a Runnable object.

Thread(Runnable target, String name)

NIIT

Java Handout 49

The Thread Class: Constants


The Thread class contains fields for priority values. Method
public final static int MAX_PRIORITY public final static int MIN_PRIORITY public final static int NORM_PRIORITY

Description The maximum priority value, 10. The maximum priority value, 1. The default priority value,5.

The Thread Class: Methods


Some Thread methods of Thread class are as follows: Thread Methods Description public static Thread Returns a reference to the thread that is currentThread() currently running. public final String getName() Returns the name of this method. public final void setName(String Renames the thread to the specified name) argument name. May throw SecrityException. public final int get Priority() Returns the priority assigned to this thread. public final Boolean isAlive() Indicates whether this thread is running or not.

Two Ways of Creating and Starting a Thread


The two ways of creating and starting a thread are: Extending the Thread class Implementing the Runnable interface

Extending Thread Class


The subclass extends Thread class and the subclass overrides the run() method of Thread class. An object instance of the subclass can then be created. Calling the start() method of the object instance starts the execution of the thread. Java runtime starts the execution of the thread by calling run() method of object instance.

50 Java Handout

NIIT

Two Schemes of Starting a Thread from a Subclass


The two schemes of starting a thread from a subclass are: The start() method is not in the constructor of the subclass. The start() method needs to be explicitly invoked after object instance of the subclass is created in order to start the thread. The start() method is in the constructor of the subclass. Creating an object instance of the subclass will start the thread.

Runnable Interface
The Runnable interface should be implemented by any class whose instances are intended to be executed as a thread. The class must define run() method of no arguments. The run() method is like main() for the new thread. The Runnable interface provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target.

Extending Thread versus Implementing Runnable Interface


Selecting between Thread and Runnable interface is depends on the user. Implementing the Runnable interface: In this case declare a Thread object, call the Thread methods on this object. Extending the Thread class: It is easy to implement and the class which need to implement the thread, should be extended from Thread class.

Synchronization: Locking an Object


A thread is synchronized by becoming an owner of the monitor of the object: Consider it as locking an object. A thread becomes the owner of the monitor of the object in one of following ways: Option 1: Use synchronized method Option 2: Use synchronized statement on a common object

Inter-thread Communication: Methods from Object Class


Methods
public final void wait()
NIIT

Description Causes this thread to wait until some other thread


Java Handout 51

Public final void notify() Public final void notifyAll()

calls the notify or notifyAll method on this object. May throw InterruptedException. Wakes up a thread that called the wait method on the same object. Wakes up all threads that called the wait method on the same object.

Concurrency Utilities: JSR-166


Concurrency utilities enable development of simple yet powerful multithreaded applications. Like Collection it provides rich data structure handling capability. It beats C performance in high-end server applications. It provides richer set of concurrency building blocks. The wait() , notify() , and synchronized methods are too primitive. It enhances scalability, performance, readability, and thread safety of Java applications.

Why Use Concurrency Utilities


Concurrency utilities are used because: It reduces the programming effort. It increases the performance. It increases the reliability and eliminate threading hazards such as deadlock, starvation, race conditions, or excessive context switching are eliminated It improves the maintainability. It increases the productivity.

Concurrency Utilities
List of Concurrency Utilities are: Task Scheduling Framework Callable's and Future's Synchronizers Concurrent Collections Atomic Variables Locks Nanosecond-granularity timing

52 Java Handout

NIIT

Task Scheduling Framework


Executor /ExecutorService/Executors framework supports: o Standardizing invocation o Scheduling o Execution o Control of asynchronous tasks according to a set of execution policies Executor is an interface ExecutorService extends Executor Executors is factory class for creating various kinds of ExercutorService implementations Executor interface provides a way of de-coupling task submission from the execution. Execution: Mechanics of how each task will be run, including details of thread use and scheduling. Example:
Executor executor = getSomeKindofExecutor(); executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2());

Executor Interface

Many Executor implementations impose some sort of limitation on how and when tasks are scheduled.

Callables and Futures


Callable thread (Callee) implements Callable interface: Implement call() method rather than run() Calling thread (Caller) submits Callable object to Executor and then moves on through submit() and not execute() The submit() returns a Future object Calling thread (Caller) retrieves the result using get() method of Future object: If result is ready, then it is returned If result is not ready, then calling thread will block

I/O Streams
An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations like disk files, devices, other programs, a network socket, and memory arrays. Streams support many different kinds of data like simple bytes, primitive data types, localized characters, and objects.
NIIT Java Handout 53

Some streams simply pass on data, others manipulate and transform the data in useful ways. No matter how they work internally, all streams present the same simple model to programs that use them. A stream is a sequence of data.

Input Stream
A program uses an input stream to read data from a source, one item at a time.

Output Stream
A program uses an output stream to write data to a destination, one item at time.

General Stream Types


The general stream types are: Character and Byte Streams: Character streams are the streams that read and write 16-bit characters whereas Byte streams are the streams that read and write 8-bit bytes. Input and Output Streams: Based on source or destination Node and Filter Streams: Whether the data on a stream is manipulated or transformed or not.

Character and Byte Streams


Byte streams: For binary data Root classes for byte streams: o The InputStream class o The OutputStream class o Both classes are abstract Character streams: For Unicode characters Root classes for character streams: o The Reader class o The Writer class o Both classes are abstract

Input and Output Streams


Input or source streams: Can read from these streams Root classes of all input streams: o The InputStream class o The Reader class Output or sink (destination) streams: Can write to these streams
NIIT

54 Java Handout

Root classes of all output streams: o The OutputStream class o The Writer class

InputStream Abstract Class


Methods
public int read(-) throws IOException public abstract int read() public int read(byte[] bBuf) public abstract int read(char[] cbuf, int offset, int length) public abstract void close() throws IOException

Description An overloaded method, which also has three versions like that of the Reader class, Reads bytes. Reads the next byte of data from this stream. Reads some number of bytes and store them in the bBuf byte array. Reads upto length number of bytes and stores them in the byte array bBuf starting at the specified offset. Closes this stream. Calling the other Inputstream methods after closing the stream would cause an IOException to occur.

Byte Stream
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream. There are many byte stream classes like FileInputStream and FileOutputStream.

When not to use Byte Stream


Byte Stream represents a kind of low-level I/O that you should avoid: If the data contains character data, then the best approach is to use character streams. There are also streams for more complicated data types. Byte streams should only be used for the most primitive I/O. All other streams are based on byte stream.

Character Stream
The Java platform stores character values using Unicode conventions. All character stream classes are descended from Reader and Writer.
NIIT Java Handout 55

The FileReader and FileWriter classes are used for I/O operations. Reader and Writer are the abstract superclasses for character streams in java.io package. They work with character streams rather than byte streams. The Reader and Writer classes were added to JDK 1.1 to support internationalization.

Buffered Streams
In unbuffered I/O means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, because each such request often triggers disk access, network activity, or some other operation that is relatively expensive. To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer. The native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

How to Create Buffered Streams?


A program can convert an unbuffered stream into a buffered stream using the wrapping idiom. An unbuffered stream object is passed to the constructor for a buffered stream class. Example:
inputStream = new BufferedReader(new FileReader("abc.txt")); outputStream = new BufferedWriter(new FileWriter("charoutput.txt"));

Object Streams
Object streams support I/O of objects: Like Data streams support I/O of primitive data types The object has to be of Serializable type The object stream classes are ObjectInputStream and ObjectOutputStream. These classes implement ObjectInput and ObjectOutput, which are sub interfaces of DataInput and DataOutput. An object stream can contain a mixture of primitive and object values.
56 Java Handout NIIT

The File Class


The File class is not a stream class. The File class is important because stream classes manipulate File objects. The File class is an abstract representation of actual files and directory pathname.

JDBC
JDBC is a standard Java API for accessing relational database and hides database specific details from application.

JDBC API
The JDBC API is a Java API for accessing virtually any kind of tabular data. The JDBC API consists of a set of classes and interfaces written in the Java programming language that provide a standard API for tool/database developers and makes it possible to write industrial-strength database applications entirely in the Java programming language. Majority of JDBC API is located in java.sql package, which are DriverManager, Connection, ResultSet, DatabaseMetaData, ResultSetMetaData, PreparedStatement, CallableStatement and Types The javax.sql package provides many advanced functionalities. For example, an alternative to the DriverManager facility, a DataSource object is the preferred means of getting a connection. The DataSource interface is implemented by a driver vendor. With a basic implementation, the connection obtained through a DataSource object is identical to a connection obtained through the DriverManager facility.

JDBC Driver
JDBC driver is an implementation of JDBC interfaces that is specific to database. Every database server has corresponding JDBC drivers. JDBS allows: 1. Establish a connection with a data source. 2. Send queries and update statements to the data source. 3. Process the results.

NIIT

Java Handout 57

Database URL
Database URL is used to make a connection to the database and can contain server, port, protocol, and so on.
jdbc:subprotocol_name:driver_dependant_databasename: Oracle thin driver jdbc:oracle:thin:@machinename:1521:dbname:Derby jdbc:derby://localhost:1527/sample: Pointbase jdbc:pointbase:server://localhost/sample

Steps of Applying JDBC


The steps of applying JDBC are: 1. Load the JDBC driver that is specific to DB. 2. Get a Connection object. 3. Get a Statement object. 4. Execute queries and/or updates. 5. Read results. 6. Close Statement and Connection objects.

javax.sql.DataSource Interface and DataSource Object


Driver vendor implements the javax.sql.DataSource interface. DataSource object is the factory for creating database connections.

Properties of DataSource Object


A DataSource object has properties that can be modified when necessary. These are defined in the configuration file of a container: Location of the database server Name of the database Network protocol to be used to communicate with the server The benefit is: The properties of the data source can be changed. Any code accessing that data source does not need to be changed. In the Sun Java System Application Server, a data source is called a JDBC resource.

58 Java Handout

NIIT

Transaction
One of the main benefits of using a PreparedStatement is executing the statements in a transactional manner. The committing of each statement when it is first executed is very time consuming. By setting AutoCommit to false, the developer can update the database more then once and then commit the entire transaction as a whole. Also, if each statement is dependent on the other, the entire transaction can be rolled back and the user is notified.

JDBC Transaction Methods


The JDBC transaction methods are: setAutoCommit() : If set true, every executed statement is committed immediately commit() : o Relevant only if setAutoCommit(false) o Commit operations performed because the opening of a Connection or last commit() or rollback() calls rollback() : o Relevant only if setAutoCommit(false) o Cancels all operations performed

Prepared and Callable Statements


PreparedStatement: SQL is sent to the database and compiled or prepared beforehand CallableStatement: Executes SQL Stored Procedures

PreparedStatement
The contained SQL is sent to the database and compiled or prepared beforehand. From this point on, the prepared SQL is sent and this step is bypassed. The more dynamic statement requires this step on every execution. Depending on the DB engine, the SQL may be cached and reused even for a different PreparedStatement and most of the work is done by the DB engine rather than the driver. Instances of PreparedStatement contain an SQL statement that has already been compiled. This is what makes a statement "prepared. The SQL statement contained in a PreparedStatement object may have one or more IN parameters.
Java Handout 59

NIIT

An IN parameter is a parameter whose value is not specified when the SQL statement is created. Instead, the statement has a question mark (?) as a placeholder for each IN parameter. The ? is also known as a parameter marker or parameter placeholder. An application must set a value for each parameter marker in a prepared statement before executing the prepared statement. Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency. Being a subclass of Statement, PreparedStatement inherits all the functionality of Statement. In addition, it adds a set of methods that are needed for setting the values to be sent to the database in place of the placeholders for IN parameters. Also, the three methods execute, executeQuery, and executeUpdate are modified so that they take no argument. The Statement forms of these methods (the forms that take an SQL statement parameter) cannot be used with a PreparedStatement object.

CallableStatement
CallableStatement is the interface used to execute SQL stored procedures. A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. Stored procedures are used to encapsulate a set of operations or queries to execute on a database server. A CallableStatement object contains a call to a stored procedure. It does not contain the stored procedure itself. The following first line of code creates a call to the stored procedure SHOW_SUPPLIERS using the connection con. The part that is enclosed in curly braces is the escape syntax for stored procedures.
CallableStatementcs = con.prepareCall("{call SHOW_SUPPLIERS}"); ResultSetrs = cs.executeQuery();

60 Java Handout

NIIT

Вам также может понравиться