407
Core Java 1 adrish.b@ardentcollaborati ons.com http://www.ardentcollabora tions.com By Adrish Bhattacharyay Ardent Collaborations

Core Java Ppt

Embed Size (px)

Citation preview

Page 1: Core Java Ppt

Core Java 1

[email protected] http://www.ardentcollaborations.com

ByAdrish BhattacharyayArdent Collaborations

Page 2: Core Java Ppt

COREJAVA

JAVA TECHNOLOGIES-JAVE SE(STARDARD EDITION)-FORMERLY J2SE

-JAVA EE(ENTERPRISE EDITION)-FORMERLY J2EE

-JAVA ME(MOBILE EDITION)-FORMERLY J2ME(MICRO EDITION)

Page 3: Core Java Ppt

COREJAVAStep by step java program execution(before Java2)

Page 4: Core Java Ppt

COREJAVAMore detailed explanation

Java source .java

javac

Java bytecode .class

JVM

Programming API

Platform interface of Web Browse

JVM

Programming API

Platform interface of Windows

JVM

Programming API

Platform interface of Unix

java

Page 5: Core Java Ppt

COREJAVA

Processiong .class file in JVM

JVM running Applet or

Application

.class file

JIT COMPILER

machine code

Page 6: Core Java Ppt

CORE JAVA-OOP CONCEPTS

Types of Programming

-Structured Programming Approach

-Object Oriented Programming Approach

Page 7: Core Java Ppt

CORE JAVA-OOP CONCEPTS

Types of Programming

-Structured Programming Approach

-Object Oriented Programming Approach

Structures Programming Approach

Mainly function Oriented.. Programs are based on functions.

Example C

Page 8: Core Java Ppt

CORE JAVA-OOP CONCEPTS

What is Object Orientation ??

Similar kinds of Objects which have common properties and behavior can be group together as a single unit in a class. This concept is known as Object Orientation. This approach is known as Object Orientated Approach.

Example:-Furniture

Chair Table Book self

Page 9: Core Java Ppt

CORE JAVA-OOP CONCEPTS

What is Object Orientation ??

Similar kinds of Objects which have common properties and behavior can be group together as a single unit in a class. This concept is known as Object Orientation. This approach is known as Object Orientated Approach.

Example:-Furniture

Chair Table Book self

Common Properties:HeightWidthLength

Page 10: Core Java Ppt

CORE JAVA-OOP CONCEPTS

What is Object Orientation ??

Similar kinds of Objects which have common properties and behavior can be group together as a single unit in a class. This concept is known as Object Orientation. This approach is known as Object Orientated Approach.

Example:-

RealLife Object: State-Variable

Behavior-method

Furniture

Chair Table Book self Common Behavior:Keeping something

Page 11: Core Java Ppt

CORE JAVA-OOP CONCEPTS

Features of 100% OOP Languages:

1) Encapsulation / DataHiding

2) Abstraction

3) Inheritance

4) Polymorphism

5) Dynamic Binding

6) Message Passing

Page 12: Core Java Ppt

CORE JAVA-OOP CONCEPTS

BASIC TERMINOLOGY

A class describes the data and the methods of its objects. Every object belongs to some class.

Class=Variables/Data+ Methods + Its own Members We can say class is a blue-print of Object.

An object contains data (instance variables) representing its state, and instance methods, which are the things it can do. After all Object is the Instance of a Class.

Object of a Class=Instance data/variable+ Instance methods

A class can also contain its own data (class variables) and methods (class methods). The keyword static denotes such data and methods.

Page 13: Core Java Ppt

CORE JAVA-OOP CONCEPTS

ENCAPSULATION / DATAHIDINGABSTRACTION

ENCAPSULATION Binding or Wrapping of the data and methods into a single unit is called Encapsulation.

Encapsulation is used to hide data or protect data from outside access. So this concept is also called data-hiding.

ABSTRACTION Abstraction refers to the act of representing essential features without including the background details and explanation.

explanation the capsule cures the patient.. But the patient don’t know what is capsulated inside the capsule…..

CAPSULEMEDICINE INSIDE THE CAP

Page 14: Core Java Ppt

COREJAVA

Simple java program

class A

{

public static void main(String arr[])

{

System.out.println(“Hello World”);

}

}

Page 15: Core Java Ppt

COREJAVA

Simple java program

class A name of the class

{

public static void main(String arr[])

{

System.out.println(“Hello World”);

}

}

Page 16: Core Java Ppt

COREJAVA

Simple java program

class A

{

public static void main(String arr[])

{

System.out.println(“Hello World”);

}

}

Public is a access specifier that declares the method ad unprotected and therefore making it accessible to all other classes.

Static static is a keyowrd ,which declares this method as one that belongs to the entire class and not a part of any objects of the class.

Void does not return anything.

Page 17: Core Java Ppt

COREJAVA

Simple java program

class A

{

public static void main(String arr[]) Defining main method

{

System.out.println(“Hello World”);

}

}

arr[]takes the values of command line arguments..

Suppose we are giving a b c darr[0]=a,arr[1]=b,arr[2]=c,arr[3]=d

String array as argument

Page 18: Core Java Ppt

COREJAVA

Simple java program

class A

{

public static void main(String arr[])

{

System.out.println (“ Hello World”);

}

}

System System is a class under java.lang package.java.lang.Objectjava.lang.System

outout is the object of PrintStream class.

println()is the method that prints in a new line.

Page 19: Core Java Ppt

COREJAVA

Compiling java programs

d:\mydirectory>javac A.java

d:\mydirectory>

Running java Programs

d:\mydirectory>java A

Hello World

d:\mydirectory>

Page 20: Core Java Ppt

CORE JAVA-OOP CONCEPTS

Example Showing Encapsulation

class Encapsulation{

private int height; private int width; private int length;public void init(){

height=100;width=100;length=100;

}

Page 21: Core Java Ppt

CORE JAVA-OOP CONCEPTS

public void display(){

System.out.println("height="+height);System.out.println("lenghth="+length);System.out.println("width="+width);

}public static void main(String arr[]){

Encapsulation encap=new Encapsulation()encap.init();encap.display();

}}

Declaring the Objectnew keyword for dynamic allocation of memory

Encapsulation() is theConstructor: member function having the same name as the class name,used to create object.

DEFAULT CONSTUCTORSIf we don’t define any constructor

There is a concept of default constructor.

It initialize variables to default value.and stores it

dynamically

Constructor is of two type: -Parameterized Constructor

-Non/Un-Parameterized Constructor

Page 22: Core Java Ppt

CORE JAVA-OOP CONCEPTSCONSTRUCTOR :

-Member Function

-having same name with the Class

-used at the time of Object Creation

Exampleclass Area{

Area(){

System.out.println(“No shape”);

}

Area(int a){

System.out.println(“The are of the Squre=”+(a*a));

}

Area(double a){

System.out.println(“Circles area”Math.PI*a*a);

}

public static void main(String arr[])

{

Area a=new Area();

Area a1=new Area(4);

Area a2=new Area(4.0);

}

}

parameterized

Page 23: Core Java Ppt

CORE JAVA-OOP CONCEPTSNO DESTRUCTORS IN JAVAdestructor use ‘delete’ to free the memory..

GARBAGE COLLECTION: In java there is a garbage collector, which is called automatically after the execution of the program and frees the memory.

When no reference to the object exists that object is assumed to be no longer needed and the memory occupied by the object is released by the Garbage Collector.

Area a1=new Area(4);

a1A variable holds the reference that points the address

Object is created

JVM will contain address of the object(JVM-maintains addressing)

[reference]allias with the addressJVM(REF,ADDRESS)

REFOBJ

GARBAGE COLLECTION

DELETE THE REFERENCE

OBJECT WILL BE FREE

THEN GC WILL DELETE THE OBJECT..

GC

You can run the garbage collector on demand by calling the gc( ) method.Runtime r = Runtime.getRuntime();

r.gc();

Page 24: Core Java Ppt

CORE JAVA-OOP CONCEPTS

PREVENTING GARBAGE COLLECTION

Suppose an Object is Holding some Non-Java Resources (e.g- font or file) and if garbage collector is default then it will check the object and delete all the reference also and the system will be traped.

So there is a provision for handling a reference of non-java resource called finalize.

To add finalize to a class you can simply define finalize method. In the finalize method you will specify those action that must be performed before an object is destroyed. The Garbage Collector runs periodically checking for objects that are no longer referenced by any Running State. Finalize is called just before Garbage Collection . ( Otherwise it will delete all the Objetcs that are referenced and the Sytem will be trapped ).

protected void finalize(){ //code}

Page 25: Core Java Ppt

CORE JAVA-OOP CONCEPTS

INHERITANCE

Inheritance is a process, through which we can create a new class from an existing class.

In Java ‘extends’ key word is used

Parent , Super, Base Class

Child , Sub , Derived Class

Page 26: Core Java Ppt

CORE JAVA-OOP CONCEPTSclass Furniture{

int height;int width;int length;

}class Table extends Furniture{

int no-of-legs;void init(){height=10;width=20;length=30;no-of-legs=4;}

void display(){

System.out.println(“height=”+hei ght);System.out.println(“width=”+width);System.out.println(“length=”+length);System.out.println(“Number of Legs=”+no-of-legs);

}public static void main(String arr[]){Table t1=new Table();t1.init();t1.display();}

}

Page 27: Core Java Ppt

CORE JAVA-OOP CONCEPTS

POLYMORPHISM

=PLOY MORPH(MANY FORMS)

Anything which has more than one form depending on the situation.

Two types of Polymorphism

-Compile-time/Static Polymorphism early binding or static binding.. ex: Method Overloading

-Run-time/Dynamic Polymorphism late binding or dynamic binding.. ex: Method Overriding

Page 28: Core Java Ppt

CORE JAVA-OOP CONCEPTS

MESSAGE PASSING

When a project is executed the objects interact with each other by sending messages to other.

For example:

In a banking system there is two object one is customer & other is account number. when any customer object sent a message to the account object requesting for the balance, the account object replies with the figure..

Page 29: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

Method Overloading is a process where the same function name is used for more than one type/Functions can be overloaded based on the function signature.

Method Signature are: The no of Parameters Type of Parameters Sequence of Parameters

**Functions can not be overloaded based on return type….

Page 30: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

class Overloadingclass Overloading

{{

static int add(int x,int y)static int add(int x,int y)

{{

return x+y;return x+y;

}}

static float add(float x,float y)static float add(float x,float y)

{{

return x+y;return x+y;

}}

static int add(int x,int y,int z)static int add(int x,int y,int z)

{{

return x+y+z;return x+y+z;

}}

public static void main(String arr[])public static void main(String arr[])

{{

int result;int result;

result=add(10,20,30);result=add(10,20,30);

System.out.println("Addition is:"+result);System.out.println("Addition is:"+result);

result=add(100,50);result=add(100,50);

System.out.println("Addition is:"+result);System.out.println("Addition is:"+result);

float result1;float result1;

result1=add(10.25f,20.50f);result1=add(10.25f,20.50f);

System.out.println("Addition is:"+result1);System.out.println("Addition is:"+result1);

}}

}}

class Overloadingclass Overloading

{{

int add(int x,int y)int add(int x,int y)

{{

return x+y;return x+y;

}}

float add(float x,float y)float add(float x,float y)

{{

return x+y;return x+y;

}}

int add(int x,int y,int z)int add(int x,int y,int z)

{{

return x+y+z;return x+y+z;

}}

public static void main(String arr[])public static void main(String arr[])

{{

int result;int result;

float result1;float result1;

Overloading ovrld=new Overloading();Overloading ovrld=new Overloading();

result=overld.add(10,20,30);result=overld.add(10,20,30);

System.out.println("Addition is:"result);System.out.println("Addition is:"result);

result=overld.add(100,50);result=overld.add(100,50);

System.out.println("Addition is:"result);System.out.println("Addition is:"result);

result1=overld.add(10.25f,20.50f);result1=overld.add(10.25f,20.50f);

System.out.println("Addition is:"result1);System.out.println("Addition is:"result1);

}}

}}

Page 31: Core Java Ppt

@

Ardent Collaborations

by

Adrish Bhattacharyay

CORE JAVACLOSER LOOKS TO METHODS

Page 32: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

CONSTRUCTOR OVERLOADING: Why?This is essential because without Constructor Overloading it is not

possible to identify which of the constructor will be invoked.

Example class Area{ Area(){ System.out.println(“No shape”); } Area(int a){ System.out.println(“The are of the

Squre=”+(a*a)); } Area(double a){ System.out.println(“Circles

area”Math.PI*a*a); }

Page 33: Core Java Ppt

public static void main(String arr[]) { Area a=new Area(); Area a1=new Area(4); Area a2=new Area(4.0); } }

[email protected] http://www.ardentcollaborations.com

33

Page 34: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

Difference: Method Overloading and Constructor Overloading

Method OverloadingMethod Overloading

Using one object we Using one object we can call all the can call all the methods having methods having same namesame name

Example:Example:

A a=new A();A a=new A();

a.add(12,14);a.add(12,14);

a.add(11.5,16.8);a.add(11.5,16.8);

a.add(10,15,20); a.add(10,15,20);

Constructor OverloadingConstructor Overloading

We need different objects We need different objects to call each constructorsto call each constructors

Example:Example:

Area a=new Area();Area a=new Area();

Area a1=new Area(4);Area a1=new Area(4);

Area a2=new Area(4.0);Area a2=new Area(4.0);

Page 35: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

Inheritance: Inheritance is a process, through which we can create a new class from an existing class.

Types:-1.Single 2.Multilevel 3.Multiple 4.Hierarchical

Page 36: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

Inheritance: Inheritance is a process, through which we can create a new class from an existing class.

Types:-1.Single 2.Multilevel 3.Multiple 4.Hierarchical 1.Single Inheritance: class A { //code } class B extends A { //code }

A

B

Page 37: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

Inheritance: Inheritance is a process, through which we can create a new class from an existing class.

Types:-1.Single 2.Multilevel 3.Multiple 4.Hierarchical 2.Multilevel Inheritance: class A { //code } class B extends A { //code } class C extends B { //code }

A

B

C

Page 38: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

Inheritance: Inheritance is a process, through which we can create a new class from an existing class.

Types:-1.Single 2.Multilevel 3.Multiple 4.Hierarchical 3.Multiple Inheritance:

A

BC D

Page 39: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

Inheritance: Inheritance is a process, through which we can create a new class from an existing class.

Types:-1.Single 2.Multilevel 3.Multiple 4.Hierarchical 3.Multiple Inheritance: Not supported by Java.

A

B

C D

Page 40: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

Inheritance: Inheritance is a process, through which we can create a new class from an existing class.

Types:-1.Single 2.Multilevel 3.Multiple 4.Hierarchical 3.Multiple Inheritance: Not supported by Java. Diamond Problem…But supported by C++ To Overcome this problem we have the concept

of Interface..

A

B

C D

Page 41: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

Inheritance: Inheritance is a process, through which we can create a new class from an existing class.

Types:-1.Single 2.Multilevel 3.Multiple 4.Hierarchical 4.Hierarchical Inheritance: class A { //code } class B extends A { //code } class C extends A { //code } class D extends A { //code }

A

BC D

Page 42: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

SIMPLE EXAMPLE OF INHERITANCE class Furniture { int height; int width; int length; } class Table extends Furniture { int no-of-legs; void init() { height=10; width=20; length=30;

Page 43: Core Java Ppt

no-of-legs=4; } void display() { System.out.println(“height=”+height); System.out.println(“width=”+width); System.out.println(“length=”+length); System.out.println(“Number of Legs=”+no-of-legs); } public static void main(String arr[]) { Table t1=new Table(); t1.init(); t1.display(); } }[email protected] http://www.ardentcollaborations.com

43

Page 44: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

static keyword There will be times when you will want to define a class member that will be used independently of any object of

that class. Normally a class member must be accessed only in conjunction with an object of its class. However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist.

If you need to do computation in order to initialize your static variables, you can declare a static block which gets executed exactly once, when the class is first loaded. The following example shows a class that has a static method, some static variables, and a static initialization block:

class UseStatic

{ static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static //Static Block

{ System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[])

{ meth(42); }

}

As soon as the As soon as the UseStatic UseStatic class is loaded, all of the class is loaded, all of the static static statements statements are run. First, are run. First, a a is set to is set to 33, then the , then the static static block executes (printing a block executes (printing a message), and finally, message), and finally, b b is initialized to is initialized to a * 4 a * 4 or or 1212. Then . Then main( ) main( ) is is called, which calls called, which calls meth( )meth( ), passing , passing 42 42 to to xx. The three . The three println( ) println( ) statements refer to the two statements refer to the two static static variables variables a a and and bb, as well as to the , as well as to the local variable local variable xx..

Note Note It is illegal to refer to any instance variables inside of a It is illegal to refer to any instance variables inside of a static static method. Here is the output of the program:method. Here is the output of the program:

Static block initialized. Static block initialized. x = 42 x = 42 a = 3 a = 3 b = 12b = 12

Outside of the class in which they are defined, Outside of the class in which they are defined, static static methods and methods and variables can be used independently of any object. To do so, you need variables can be used independently of any object. To do so, you need only specify the name of their class followed by the dot operator. For only specify the name of their class followed by the dot operator. For example, if you wish to call a example, if you wish to call a static static method from outside its class, you method from outside its class, you can do so using the following general form:can do so using the following general form:

classname.methodclassname.method( )( )

Page 45: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

static keyword There will be times when you will want to define a class member that will be used independently of any object

of that class. Normally a class member must be accessed only in conjunction with an object of its class. However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist.

If you need to do computation in order to initialize your static variables, you can declare a static block which gets executed exactly once, when the class is first loaded. The following example shows a class that has a static method, some static variables, and a static initialization block:

class UseStatic

{ static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static //Static Block

{ System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[])

{ meth(42); }

}

Here, Here, classname classname is the name of the class in which the is the name of the class in which the static static method is declared. As you can see, this format is similar to that method is declared. As you can see, this format is similar to that used to call non-used to call non-static static methods through object reference methods through object reference variables. A variables. A static static variable can be accessed in the same way—by variable can be accessed in the same way—by use of the dot operator on the name of the class. This is how Java use of the dot operator on the name of the class. This is how Java implements a controlled version of global functions and global implements a controlled version of global functions and global variables. variables.

Page 46: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

static keyword There will be times when you will want to define a class member that will be used independently of any object

of that class. Normally a class member must be accessed only in conjunction with an object of its class. However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist.

If you need to do computation in order to initialize your static variables, you can declare a static block which gets executed exactly once, when the class is first loaded. The following example shows a class that has a static method, some static variables, and a static initialization block:

class UseStatic

{ static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static //Static Block

{ System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[])

{ meth(42); }

}

Here is an example. Inside Here is an example. Inside main( )main( ), the , the static static method method callme( ) callme( ) and the and the static static variable variable b b are accessed outside of their class are accessed outside of their class

class StaticDemo { class StaticDemo { static int a = 42; static int a = 42; static int b = 99; static int b = 99; static void callme() { static void callme() { System.out.println("a = " + a); System.out.println("a = " + a); } } } } class StaticByName { class StaticByName { public static void main(String args[]) { public static void main(String args[]) { StaticDemo.callme(); StaticDemo.callme(); System.out.println("b = " + StaticDemo.b); System.out.println("b = " + StaticDemo.b); } } } }

Here is the output of this program: Here is the output of this program: a = 42 a = 42 b = 99 b = 99

Page 47: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

static keyword There will be times when you will want to define a class member that will be used independently of any object of

that class. Normally a class member must be accessed only in conjunction with an object of its class. However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist.

If you need to do computation in order to initialize your static variables, you can declare a static block which gets executed exactly once, when the class is first loaded. The following example shows a class that has a static method, some static variables, and a static initialization block:

class UseStatic

{ static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static //Static Block

{ System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[])

{ meth(42); }

}

Methods declared as static have several restrictions:Methods declared as static have several restrictions:

They can only call other static methods.They can only call other static methods.

They must only access static data.They must only access static data.

They can’t refer to They can’t refer to thisthis or or supersuper in any way. in any way.

Page 48: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

this keyword: this keyword is used to refer to the current object. ‘this’- is always a reference to object on which the method was invoked. Example:

class Box{ double width; double height; double depth; Box(double w,double h,double d) { width=w; height=h; depth=d; } double volume() { return width*height*depth; } } class BoxDemo{ public static void main(String arr[]) { Box mybox1=new Box(10,20,30); Box mybox2=new Box(3,6,9); double vol; vol=mybox1.volume(); System.out.println("Volume is"+vol); vol=mybox2.volume(); System.out.println("Volume is"+vol); } }

Output:

Volume is6000.0Volume is162.0

Page 49: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

this keyword: this keyword is used to refer to the current object. ‘this’- is always a reference to object on which the method was invoked. Example:

class Box{ double width; double height; double depth; Box(double w,double h,double d) { this.width=w; this.height=h; this.depth=d; } double volume() { return width*height*depth; } } class BoxDemo{ public static void main(String arr[]) { Box mybox1=new Box(10,20,30); Box mybox2=new Box(3,6,9); double vol; vol=mybox1.volume(); System.out.println("Volume is"+vol); vol=mybox2.volume(); System.out.println("Volume is"+vol); } }

Output:

Volume is6000.0Volume is162.0

Page 50: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

this keyword: this keyword is used to refer to the current object. ‘this’- is always a reference to object on which the method was invoked. Example:

class Box{ double width; double height; double depth; Box(double w,double h,double d) { this.width=w; this.height=h; this.depth=d; } double volume(){ return width*height*depth; } } class BoxDemo{ public static void main(String arr[]) { Box mybox1=new Box(10,20,30); Box mybox2=new Box(3,6,9); double vol; vol=mybox1.volume(); System.out.println("Volume is"+vol); vol=mybox2.volume(); System.out.println("Volume is"+vol); } }

It is illegal in Java to declare two local variables with the same It is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes . name inside the same or enclosing scopes .

When a local variable has the same name as an instance When a local variable has the same name as an instance variable, the local variable hides the instance variable.variable, the local variable hides the instance variable.

That’s why That’s why width, height and depth width, height and depth were not used as the were not used as the names of the parameters to the Box() constructor inside the names of the parameters to the Box() constructor inside the Box class.Box class.

This can used to solve this name-space collision that might This can used to solve this name-space collision that might occur between instance variables and local variables.occur between instance variables and local variables.

We can useWe can useBox(double width,double height,double depth)Box(double width,double height,double depth)

{{

this.width=width;this.width=width;

this.height=height;this.height=height;

this.depth=depththis.depth=depth

}}

Output:

Volume is6000.0Volume is162.0

Page 51: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

super: super keyword has two general forms

It calls superclass constructor.

used to access a member of the superclass that has been hidden by member of a subclass.

Page 52: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

METHOD OVERRIDING: Method Overriding is a process through which a base class method overridden by a derived

class method For method Overriding Method name and signature should be same. class Furniture{ int height; int width; int length; Furniture(int height,int width,int length) { this.height=height; this.width=width; this.length=length; } void display(){ System.out.println("height"+height); System.out.println("width"+width); System.out.println("length"+length); } }

Page 53: Core Java Ppt

class Table1 extends Furniture{ int no_of_legs; Table1(int height,int width,int length,int no_of_legs){ super(height,width,length); this.no_of_legs=no_of_legs; } void display(){ super.display(); System.out.println("no_of_legs"+no_of_legs); } public static void main(String arr[]){ Table1 t1=new Table1(100,200,200,4); t1.display(); } }

[email protected] http://www.ardentcollaborations.com

53

Page 54: Core Java Ppt

CORE JAVACORE JAVACLOSER LOOKS TO METHODSCLOSER LOOKS TO METHODS

Difference between Method Overloading and Method Overridiing:

Preventing method Inheritance and Overriding:

Using final keyword

final class A{

//Code

}

class B extends A{

//Code

}

Java runtime System will generate an Error:

Can not inherit

for any method we can apply final keyword to prevent overriding

final void show(){

//code

}

Method overloading:Method overloading:

Compile-time PolymorphismCompile-time Polymorphism

Early/Static BindingEarly/Static Binding

Within one classWithin one class

Method Overriding:Method Overriding:

Runtime PolymorphismRuntime Polymorphism

Late/Dynamic BindingLate/Dynamic Binding

Base class and Child classBase class and Child class

Page 55: Core Java Ppt

Abstract Class and Interfaces

By

Adrish Bhattacharyay

Ardent Collaborations

http://www.ardentcollaborations.com

[email protected]

Page 56: Core Java Ppt

Meaning of Abstract

The word abstract literally means INCOMPLETE

Now in the Concept of Programming we may have incomplete methods of classes.

i abstract methods ii abstract class

Page 57: Core Java Ppt

ABSTRACT METHODS

Definition: The methods that does not have any method body ( that is the method definiton) are called abstract methods.

abstract <data type> method-name(parameter-list); Any class that contains one or more than one abstract

methods must also be declared abstract .To declare a class abstract ,you simple use the ‘abstract’ keyword in front of the class keyword at the beginning of the class declaration.

Page 58: Core Java Ppt

Abstract Class

Abstract Classes may contain abstract methods.

They are capable to contain abstract methods.

Inheritance of the abstrsct classes is possible.

Page 59: Core Java Ppt

Abstract Class

What about the object of abstract classes? There can not be any object of any

Abstract Classes.i.e-An abstract class can not be directly

instantiated with the “new” operator

Why?As the abstract class is not fully defined..

Page 60: Core Java Ppt

Abstract Class

SOME FACTS ABOUT ABSTRACT CLASS:We can not declare abstract constructors

We can not declare abstract static methods

Any sub class of an abstract class must either implement all the abstract methods in the super class or be itself a abstract method

Page 61: Core Java Ppt

Abstract Class

SIMPLE EXAMPLE:abstract class A

{

abstract void show();

void display()

{

System.out.println(“In class A”);

}

}

abstract class B extends A

{

abstract void show1();

void display1()

{

System.out.println(“In class B”);

}

}

class C extends B

{

void show()

{

System.out.println(“Definiton of show”);

}

void show1()

{

System.out.println(“Definition of show1”);

}

}

class Ex

{

public static void main(String arr[])

{

C c=new C();

c.display();

c.display1();

c.show();

c.show1();

}

}

Page 62: Core Java Ppt

Implementing Abstract Class

abstract class Figure {

double dim1;

double dim2;

Figure(double a, double b) {

dim1 = a;

dim2 = b;

}

// area is now an abstract method

abstract double area();

}

class Rectangle extends Figure {

Rectangle(double a, double b) {

super(a, b);

}

// override area for rectangle

double area() {

System.out.println("Inside Area for Rectangle.");

return dim1 * dim2;

}

}

class Triangle extends Figure {

Triangle(double a, double b) {

super(a, b);

}

// override area for right triangle

double area() {

System.out.println("Inside Area for Triangle.");

return dim1 * dim2 / 2;

}

}

class AbstractAreas {

public static void main(String args[]) {

// Figure f = new Figure(10, 10); // illegal now

Rectangle r = new Rectangle(9, 5);

Triangle t = new Triangle(10, 8);

Figure figref; // this is OK, no object is created

figref = r;

System.out.println("Area is " + figref.area());

figref = t;

System.out.println("Area is " + figref.area());

}

}

Page 63: Core Java Ppt

Explanation

As the comment inside main( ) indicates, it is no longer possible to declare objects of type Figure, since it is now abstract. And, all subclasses of Figure must override area( ). To prove this to yourself, try creating a subclass that does not override area( ). You will receive a compile-time error.Although it is not possible to create an object of type Figure, you can create a reference variable of type Figure. The variable figref is declared as a reference to Figure, which means that it can be used to refer to an object of any class derived from Figure. As explained, it is through superclass reference variables that overridden methods are resolved at run time.

Page 64: Core Java Ppt

Interfaces

Interface is nothing but a prototype.

All the methods in an Interface are abstract. An Interface can not have any non-abstract method.

Using the keyword interface.Interfaces are fully abstract.

Page 65: Core Java Ppt

Interfaces

Few fact about InterfacesNo Class can inherit an Interface, but

can implement.In Java Multiple Inheritance can be

implemented through Interfaces. That is one class implement more than one interfaces.

Page 66: Core Java Ppt

Interfaces

One Interface can inherit another Interface.

Page 67: Core Java Ppt

Simple Example on Interface

interface A{

void display();

}

interface B extends A{

void show();

}

class C implements B{

void display(){

System.out.println(“interface A”);

}

void show(){

System.out.println(“Interface B”);

}

}

class D

{

public static void main(String arr[])

{

C c=new C();

c.display();

c.show();

}

}

Page 68: Core Java Ppt

Assignment

Assignment Write a Java program to find the area

and perimeter of following different Shapes: Squre , Circle

Write a simple example to implement multiple inheritance using interface concept.

Page 69: Core Java Ppt

CORE JAVA

CONCEPT OF PACKAGE

BY

ADRISH BHATTACHARYAY

ARDENT COLLABORATIONS

www.ardentcollaborations.com

[email protected]

Page 70: Core Java Ppt

What is package??Under Java package is used to contain

different classes.Types of packages:

www.ardentcollaborations.com

[email protected]

Page 71: Core Java Ppt

Creating User Deifned Packages:package mypack;

public class Pack

{

public void show()

{

System.out.println("Inside mypack");

}

}

Directory name of the package should be as same as the package name

From the source file directory compile in the following way:

>javac -d . Pack.java

Accessing Package

import mypack.Pack;

class PackageExample

{

public static void main(String arr[])

{

Pack pack=new Pack();

pack.show();

}

}

www.ardentcollaborations.com

[email protected]

Page 72: Core Java Ppt

Example of using system package:import java.util.Date;class{

public static void main(String arr[]){

Date dt=new Date();System.out.println (“Now=”+dt);

}}

www.ardentcollaborations.com

[email protected]

Page 73: Core Java Ppt

Example of using system package:import java.util.*;//it imports all the classes under this

package(java.util)

class UserIn

{

public static void main(String arr[])

{

Scanner sc=new Scanner(System.in);

int i=Integer.parseInt(sc.nextLine());

System.out.println(i);

}

}

www.ardentcollaborations.com

[email protected]

Page 74: Core Java Ppt

ASSIGNMENT:

Create a packge. Define a method for addition in it.

Now import the package in a class and add two numbers.

Take the inputs from user using Scanner class of java.util package.

www.ardentcollaborations.com

[email protected]

Page 75: Core Java Ppt

By-Adrish Bhattacharyay

Phone:+91-9433249290

[email protected]

http://www.ardentcollaborations.com

CORE JAVA-EXCEPTION HANDLING

Page 76: Core Java Ppt

Exceptions

Exception is the short hand of the phrase “Exceptional Event”

Definition: Abnormal conditions that arises in a code sequence at run-time.

We can say these are runtime errors.

Page 77: Core Java Ppt

Exception Handling Fundamentals Java has its built-in capability to ensure

that exceptions are handled within the java program.

Exceptions handled by:

Programmer

JVM(Java Runtime System)

Page 78: Core Java Ppt

Exception Handling Fundamentals Basically Exceptions occurs due to some

run-time errors.ex: When to try to divide some number by

zero.

When we try to connect to a database but the DSN is not created in the system. i.e in case of external resources.

Page 79: Core Java Ppt

Exception Handling FundamentalsWhen Exception occurs Object

Creation(thrown)

A method may choose to handle exception itself and pass it on.

Page 80: Core Java Ppt

Exception Handling FundamentalsWhen Exception occurs Object Creation(thrown)

A method may choose to handle exception itself and pass it on.

At the point exception is caught it can be processed or can be passed again.

Exceptions can be generated by Java Runtime System or can be manually generated by your code.

Page 81: Core Java Ppt

Java Key Words for - Exception Handlingtry contains block of code that may throw

exception.catch Catch the exception thrown.finally contains the block of code that must be

executed in the program.throwit manually throws the Exception.throws when a method throws some exception we

specify with throws key word.Ex: m1(int a,int b)throws IOException{

throw new IOException();}

Page 82: Core Java Ppt

Exception Hierarchy

Page 83: Core Java Ppt

try catch finally

try

{

int d=0;

int a=42/d;

S.O.P(a);

}

catch(ArithmeticException e)

{

e.printStackTrace();

}

finally

{

int z=d*42;

S.O.P(z);

}

Page 84: Core Java Ppt

Multiple catch clausesPSVM(String arr[]){

Scanner sc=new Scanner(System.in);

int x=sc.nextLine();int y=sc.nextLine();int a[]={x,y};int b=5;try{int x=a[2]/b-a[1];}catch(ArithmeticException e){System.out.println(e);}

catch(ArrayIndexOutOfBoundException e)

{e.printStackTrace();}

finally{ int y=a[1]/a[ ]; System.out.println(“y=”+y);}

Page 85: Core Java Ppt

Nested try

try

{

try

{

}

catch(Exception e)

{

}

}

catch(Exception e)

{

}

Page 86: Core Java Ppt

throw

Till now whatever be the Exceptions we handled are thrown by Java Runtime System.

Now we will manually throw the Exception explicitly.

General Form

throw ThrowableInstance;Object of type Throwable or a subclass of Throwable.

Two ways to obtain Throwable object Using parameters in catch block .

Creating one with new Operator.

Page 87: Core Java Ppt

throw

Ex:

class ThrowDemo

{

public void demoproc()

{

try

{

throw new NullPointerException(“demo”);

}

catch(NullPointerException e)

{S.O.P(“caught”);

e.printStackTrace();

throw e;

}

}

Page 88: Core Java Ppt

throw

public static void main(String arr[])

{

try

{

demoproc();

}

catch(NullPointerException e)

{

S.O.P(“ReCaught”);

e.printStackTrace();

}

}

}

Page 89: Core Java Ppt

throws

If a method is capable of causing an exception that it does not handle , it must

specify this behaviour so that callers of the method can ground themselves

against that exception.

You do this by including a throws clause in the method declaration. A throw

clause in the method declaration. A throws clause list s the types of exceptions

that a method might throw.

Necessary for all exceptions except error and RuntimeExceptions.

FORMAT:

type mthod-name(parameter list) throws exception-list

{

//body of method….

}

Page 90: Core Java Ppt

throws

Example:class ThrowsDemo

{

static void throwOne() throws IllegalAccessException

{

S.O.P(“inside throwOne”);

throw new IllegalAccessException(“demo”)’

}

public static void main(String arr[])

{

try

{

throwOne();

}

catch(IllegalAccessExample e)

{

e.printStackTrace();

}

}

}

Page 91: Core Java Ppt

Creating Own Exception SubClass

class MyException extends Exception{

private int detail;MyException(int a){detail=a;}public String toString(){return

“MyException[“+detail+”]”;}

}class ExceptionDemo{ static void compute (int a)throws MyException { S.O.P(“Called compute (“+a+”)”); if(a>10) throw new MyException(a); S.O.P(“Normal exit”); }

public static void main(String arr[]){ try{ compute(1); compute(2); } catch(Exception e) { S.O.P(e); }}}

Page 92: Core Java Ppt

92

Multithreaded Programming using Java Threads

ADRISH BHATTACHARYAYArdent Collaborationsemail- [email protected] www.ardentcollaborations.com

Page 93: Core Java Ppt

A single threaded program

class ABC{….

public void main(..){…..}

}

93

begin

body

end

www.ardentcollaborations.com

Page 94: Core Java Ppt

A Multithreaded Program94

Main Thread

Thread A Thread B Thread C

start startstart

Threads may switch or exchange data/results

www.ardentcollaborations.com

Page 95: Core Java Ppt

Single and Multithreaded Processes

95

Single-threaded Process

Single instruction stream Multiple instruction stream

Multiplethreaded ProcessThreads of

Execution

CommonAddress Space

threads are light-weight processes within a process

www.ardentcollaborations.com

Page 96: Core Java Ppt

Multithreaded Server: For Serving Multiple Clients Concurrently96

ServerThreads

Server ProcessClient 1 Process

Client 2 Process

Internet

www.ardentcollaborations.com

Page 97: Core Java Ppt

Web/Internet Applications:Serving Many Users Simultaneously97

Internet Server

PC client

Local Area Network

PDA

www.ardentcollaborations.com

Page 98: Core Java Ppt

Modern Applications need Threads (ex1):Editing and Printing documents in background.98

Printing ThreadPrinting Thread

Editing Thread

Editing Thread

www.ardentcollaborations.com

Page 99: Core Java Ppt

What are Threads?

A piece of code that run in concurrent with other threads.

Each thread is a statically ordered sequence of instructions.

Threads are being extensively used express concurrency on both single and multiprocessors machines.

Programming a task having multiple threads of control – Multithreading or Multithreaded Programming.

99

www.ardentcollaborations.com

Page 100: Core Java Ppt

Java Threads

Java has built in thread support for Multithreading

Synchronization Thread Scheduling Inter-Thread Communication:

currentThread start setPriority yield run getPriority sleep stop suspend resume

Java Garbage Collector is a low-priority thread.

100

www.ardentcollaborations.com

Page 101: Core Java Ppt

Threading Mechanisms...

Create a class that extends the Thread class

Create a class that implements the Runnable interface

101

Thread

MyThread

Runnable

MyClass

Thread

(objects are threads) (objects with run() body)

[a] [b]

www.ardentcollaborations.com

Page 102: Core Java Ppt

1st method: Extending Thread class Create a class by extending Thread class and

override run() method: class MyThread extends Thread {

public void run() { // thread body of execution } } Create a thread: MyThread thr1 = new MyThread(); Start Execution of threads: thr1.start(); Create and Execute: new MyThread().start();

102

www.ardentcollaborations.com

Page 103: Core Java Ppt

An example

class MyThread extends Thread { public void run() { System.out.println(" this thread is running ... "); }}

class ThreadEx1 { public static void main(String [] args ) {

MyThread t = new MyThread(); t.start();

}}

103

www.ardentcollaborations.com

Page 104: Core Java Ppt

2nd method: Threads by implementing Runnable interface Create a class that implements the interface Runnable and

override run() method:class MyThread implements Runnable{ ..... public void run() { // thread body of execution }} Creating Object: MyThread myObject = new MyThread(); Creating Thread Object: Thread thr1 = new Thread( myObject ); Start Execution: thr1.start();

104

www.ardentcollaborations.com

Page 105: Core Java Ppt

An example

class MyThread implements Runnable { public void run() { System.out.println(" this thread is running ... "); }}

class ThreadEx2 { public static void main(String [] args ) { Thread t = new Thread(new MyThread()); t.start(); } }

105

www.ardentcollaborations.com

Page 106: Core Java Ppt

Life Cycle of Thread106 new

ready

start()

running

deadstop()

dispatch

completion

wait()

waitingsleeping blocked

notify()

sleep()

Block on I/O

I/O completed

Time expired/interrupted

suspend()

suspend()

www.ardentcollaborations.com

Page 107: Core Java Ppt

A Program with Three Java Threads Write a program that creates 3 threads

107

www.ardentcollaborations.com

Page 108: Core Java Ppt

Three threads example class A extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("\t From ThreadA: i= "+i); } System.out.println("Exit from A"); } } class B extends Thread { public void run() { for(int j=1;j<=5;j++) { System.out.println("\t From ThreadB: j= "+j); } System.out.println("Exit from B"); } }

108

www.ardentcollaborations.com

Page 109: Core Java Ppt

class C extends Thread { public void run() { for(int k=1;k<=5;k++) { System.out.println("\t From ThreadC: k= "+k); }

System.out.println("Exit from C"); } }

class ThreadTest { public static void main(String args[]) { new A().start(); new B().start(); new C().start(); } }

109

www.ardentcollaborations.com

Page 110: Core Java Ppt

Run 1 [raj@mundroo] threads [1:76] java ThreadTest

From ThreadA: i= 1

From ThreadA: i= 2

From ThreadA: i= 3

From ThreadA: i= 4

From ThreadA: i= 5

Exit from A

From ThreadC: k= 1

From ThreadC: k= 2

From ThreadC: k= 3

From ThreadC: k= 4

From ThreadC: k= 5

Exit from C

From ThreadB: j= 1

From ThreadB: j= 2

From ThreadB: j= 3

From ThreadB: j= 4

From ThreadB: j= 5

Exit from B

110

www.ardentcollaborations.com

Page 111: Core Java Ppt

Run2 [raj@mundroo] threads [1:77] java ThreadTest

From ThreadA: i= 1

From ThreadA: i= 2

From ThreadA: i= 3

From ThreadA: i= 4

From ThreadA: i= 5

From ThreadC: k= 1

From ThreadC: k= 2

From ThreadC: k= 3

From ThreadC: k= 4

From ThreadC: k= 5

Exit from C

From ThreadB: j= 1

From ThreadB: j= 2

From ThreadB: j= 3

From ThreadB: j= 4

From ThreadB: j= 5

Exit from B

Exit from A

111

www.ardentcollaborations.com

Page 112: Core Java Ppt

Thread Priority

In Java, each thread is assigned priority, which affects the order in which it is scheduled for running. The threads so far had same default priority (NORM_PRIORITY) and they are served using FCFS policy. Java allows users to change priority:

ThreadName.setPriority(intNumber) MIN_PRIORITY = 1 NORM_PRIORITY=5 MAX_PRIORITY=10

112

www.ardentcollaborations.com

Page 113: Core Java Ppt

Thread Priority Example

class A extends Thread

{

public void run()

{

System.out.println("Thread A started");

for(int i=1;i<=4;i++)

{

System.out.println("\t From ThreadA: i= "+i);

}

System.out.println("Exit from A");

}

}

class B extends Thread{

public void run() {

System.out.println("Thread B started");

for(int j=1;j<=4;j++)

{

System.out.println("\t From ThreadB: j= "+j);

}

System.out.println("Exit from B");

}

}

113

www.ardentcollaborations.com

Page 114: Core Java Ppt

Thread Priority Example

class C extends Thread

{

public void run()

{

System.out.println("Thread C started");

for(int k=1;k<=4;k++)

{

System.out.println("\t From ThreadC: k= "+k);

}

System.out.println("Exit from C");

}

}

class ThreadPriority

{

public static void main(String args[])

{

A threadA=new A();

B threadB=new B();

C threadC=new C();

114

www.ardentcollaborations.com

Page 115: Core Java Ppt

Thread Priority Example

threadC.setPriority(Thread.MAX_PRIORITY); threadB.setPriority(threadA.getPriority()+1); threadA.setPriority(Thread.MIN_PRIORITY); System.out.println("Started Thread A"); threadA.start(); System.out.println("Started Thread B"); threadB.start(); System.out.println("Started Thread C"); threadC.start(); System.out.println("End of main thread"); }}

[email protected] http://www.ardentcollaborations.com

115

Page 116: Core Java Ppt

Accessing Shared Resources

Applications Access to Shared Resources need to be coordinated. Printer (two person jobs cannot be printed at

the same time) Simultaneous operations on your bank account. Can the following operations be done at the

same time on the same account? Deposit() Withdraw() Enquire()

116

www.ardentcollaborations.com

Page 117: Core Java Ppt

Online Bank: Serving Many Customers and Operations

117

Internet Bank Server

PC client

Local Area Network

PDABankDatabase

www.ardentcollaborations.com

Page 118: Core Java Ppt

Shared Resources

If one thread tries to read the data and other thread tries to update the same data, it leads to inconsistent state.

This can be prevented by synchronising access to the data.

Use “Synchronized” method: public synchronized void update() {

… }

118

www.ardentcollaborations.com

Page 119: Core Java Ppt

the driver: 3rd Threads sharing the same object

119

class InternetBankingSystem { public static void main(String [] args ) { Account accountObject = new Account (); Thread t1 = new Thread(new MyThread(accountObject)); Thread t2 = new Thread(new YourThread(accountObject)); Thread t3 = new Thread(new HerThread(accountObject));

t1.start(); t2.start(); t3.start(); // DO some other operation } // end main()}

www.ardentcollaborations.com

Page 120: Core Java Ppt

Shared account object between 3 threads

120class MyThread implements Runnable { Account account; public MyThread (Account s) { account = s;} public void run() { account.deposit(); }} // end class MyThread

class YourThread implements Runnable { Account account; public YourThread (Account s) { account = s;} public void run() { account.withdraw(); } } // end class YourThread

class HerThread implements Runnable { Account account; public HerThread (Account s) { account = s; } public void run() {account.enquire(); }} // end class HerThread

account(shared object)

www.ardentcollaborations.com

Page 121: Core Java Ppt

Monitor (shared object access): serializes operation on shared objectclass Account { // the 'monitor' int balance;

// if 'synchronized' is removed, the outcome is unpredictable public synchronized void deposit( ) { // METHOD BODY : balance += deposit_amount; }

public synchronized void withdraw( ) { // METHOD BODY: balance -= deposit_amount;

} public synchronized void enquire( ) {

// METHOD BODY: display balance. }

}

121

www.ardentcollaborations.com

Page 122: Core Java Ppt

Multithreaded Server122

ServerThreads

Message PassingFacility

Server ProcessClient Process

Client Process

User Mode

Kernel Mode

Multithreaded Server

www.ardentcollaborations.com

Page 123: Core Java Ppt

CORE JAVA-String Handling

--------by-------

Adrish Bhattacharyay

@

ARDENT COLLABORATIONS

04/09/23

123

http://[email protected]

Page 124: Core Java Ppt

String HandlingIntroduction:. As is the case in most other programming languages, in Java a string is a sequence of characters. But, unlike many other languages that implement strings as character arrays, Java implements strings as objects of type String

When you create a String object, you are creating a string that cannot be changed. That is, once a String object has been created, you cannot change the characters that comprise that string. At first, this may seem to be a serious restriction.

However, such is not the case. You can still perform all types of string operations. The difference is that each time you need an altered version of an existing string, a new String object is created that contains the modifications. The original string is left unchanged. This approach is used because fixed, immutable strings can be implemented more efficiently than changeable ones. For those cases in which a modifiable string is desired, there are two companion class to String called StringBuffer and StringBuilder, whose objects contain strings that can be modified after they are created.

String , StringBuilder and StringBuffer classes are defined in java.lang. Thus, they are available to all programs automatically. All are declared final, which means that neither of these classes may be sub classed.

String , StringBuffer,StringBuilder implement the CharSequence interface.

04/09/23

http://[email protected]

124

Page 125: Core Java Ppt

String ConstructorsThe String class supports several constructors. To create an empty String, you call the default constructor.

For example,

String s=new String();

will create an instance of String with no characters in it.

The String class provides a variety of constructors to handle this. To create a String initialized by an array of characters, use the constructor shown here:

String(char chars[ ])

Here is an example:

char chars[] = { 'a', 'b', 'c' };

String s = new String(chars);

This constructor initializes s with the string “abc”.04/09/23

http://www.ardentcollaborations.com [email protected]

125

Page 126: Core Java Ppt

String ConstructorsYou can specify a subrange of a character array as an initializer using the following constructor:

String(char chars[ ], int startIndex, int numChars)

Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use.

Here is an example:

char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

String s = new String(chars, 2, 3);

This initializes s with the characters cde.

04/09/23

http://www.ardentcollaborations.com [email protected]

126

Page 127: Core Java Ppt

String ConstructorsYou can construct a String object that contains the same character sequence as another String object using this constructor:

String(String strObj)Here, strObj is a String object. Consider this example:

// Construct one String from another.

class MakeString

{

public static void main(String args[])

{

char c[] = {'J', 'a', 'v', 'a'};

String s1 = new String(c);

String s2 = new String(s1);

System.out.println(s1);

System.out.println(s2);

}

}The output from this program is as follows:

Java

Java As you can see, s1 and s2 contain the same string.04/09/23

http://www.ardentcollaborations.com [email protected]

127

Page 128: Core Java Ppt

String ConstructorsThough Java’s char type uses 16 bits to represent the Unicode character set, the

typical format for strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set. Because 8-bit ASCII strings are common, the String class provides constructors that initialize a string when given a byte array. Their forms are shown here:

String(byte asciiChars[ ])

String(byte asciiChars[ ], int startIndex, int numChars)

Here, asciiChars specifies the array of bytes. The second form allows you to specify a

subrange. In each of these constructors, the byte-to-character conversion is done by

using the default character encoding of the platform.

04/09/23

http://www.ardentcollaborations.com [email protected]

128

Page 129: Core Java Ppt

String ConstructorsExample:

class SubStringCons

{

public static void main(String args[])

{

byte ascii[] = {65, 66, 67, 68, 69, 70 };

String s1 = new String(ascii);

System.out.println(s1);

String s2 = new String(ascii, 2, 3);

System.out.println(s2);

}

}

This program generates the following output:

ABCDEF

CDE04/09/23

http://www.ardentcollaborations.com [email protected]

129

Page 130: Core Java Ppt

String ConstructorsConstructing String from a StringBuffer by using constructor:

String(StringBuffer sb)

Constructing String from a StringBuilder by using constructor

String (StringBuilder sb)

Extended unicode character set:

String(int codePoints[],int startIndex,int numChars)

04/09/23

http://www.ardentcollaborations.com [email protected]

130

Page 131: Core Java Ppt

String LengthThe length of a string is the number of characters that it contains. To

obtain this value,

call the length( ) method, shown here:

int length( )

The following fragment prints “3”, since there are three characters in the string s:

char chars[] = { 'a', 'b', 'c' };String s = new String(chars);System.out.println(s.length());

04/09/23

http://www.ardentcollaborations.com [email protected]

131

Page 132: Core Java Ppt

String LiteralsThe earlier examples showed how to explicitly create a String instance from an

array

Of characters by using the new operator. However, there is an easier way to do this

using a string literal. For each string literal in your program, Java automatically

constructs a String object. Thus, you can use a string literal to initialize a String

object. For example,the following code fragment creates two equivalent strings:

char chars[] = { 'a', 'b', 'c' };

String s1 = new String(chars);

String s2 = "abc"; // use string literal

Because a String object is created for every string literal, you can use a string literal

any place you can use a String object. For example, you can call methods directly on a

quoted string as if it were an object reference, as the following statement shows. It

calls the length( ) method on the string “abc”. As expected, it prints “3”.

System.out.println("abc".length());

04/09/23

http://www.ardentcollaborations.com [email protected]

132

Page 133: Core Java Ppt

String ConcatenationJava does not allow operators to be applied to String objects. The one exception

to

this rule is the + operator, which concatenates two strings, producing a String object

as the result. This allows you to chain together a series of + operations.

For example, the following fragment concatenates three strings:

String age = "9";

String s = "He is " + age + " years old.";

System.out.println(s);

This displays the string “He is 9 years old.”

class ConCat

{

public static void main(String args[])

{

String longStr = "This could have been " +"a very long line that would have " +

"wrapped around. But string concatenation " +"prevents this.";

System.out.println(longStr);

}}04/09/23

http://www.ardentcollaborations.com [email protected]

133

Page 134: Core Java Ppt

String Concatenation with Other Data TypesYou can concatenate strings with other types of data. For example, consider this

slightly different version of the earlier

example:

int age = 9;

String s = "He is " + age + " years old.";

System.out.println(s);

In this case, age is an int rather than another String, but the output produced is the

same as before. This is because the int value in age is automatically converted into its

string representation within a String object. This string is then concatenated as

before.The compiler will convert an operand to its string equivalent whenever the

other operand of the +is an instance of String.

04/09/23

http://www.ardentcollaborations.com [email protected]

134

Page 135: Core Java Ppt

Be careful when you mix other types of operations with string concatenation

expressions, however. You might get surprising results. Consider the following:

String s = "four: " + 2 + 2;

System.out.println(s);

This fragment displays

four: 22

rather than the

four: 4

that you probably expected. Here’s why. Operator precedence causes the

concatenation of “four” with the string equivalent of 2 to take place first. This result is

then concatenated with the string equivalent of 2 a second time. To complete the

integer addition first, you must use parentheses, like this:

String s = "four: " + (2 + 2);

Now s contains the string “four: 4”.

04/09/23

http://www.ardentcollaborations.com [email protected]

135

String Concatenation with Other Data Types

Page 136: Core Java Ppt

String Conversion and toString( )

When Java converts data into its string representation during concatenation, it does so

by calling one of the overloaded versions of the string conversion method valueOf( )

defined by String. valueOf( ) is overloaded for all the simple types and for type

Object. For the simple types, valueOf( ) returns a string that contains the

human-readable

equivalent of the value with which it is called. For objects, valueOf( ) calls the

toString( ) method on the object.

Every class implements toString( ) because it is defined by Object. general form:

String toString( )

136

[email protected] http://www.ardentcollaborations.com

Page 137: Core Java Ppt

String Conversion and toString( )

Using:

toString()

class Box {

double width;

double height;

double depth;

Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

}

public String toString() {

return "Dimensions are " + width + " by " +

depth + " by " + height + ".";

}

}

137

[email protected] http://www.ardentcollaborations.com

Page 138: Core Java Ppt

String Conversion and toString( )

Using:

toString()class toStringDemo {

public static void main(String args[]) {

Box b = new Box(10, 12, 14);

String s = "Box b: " + b; // concatenate Box object

System.out.println(b); // convert Box to string

System.out.println(s);

}

}

The output of this program is shown here:

Dimensions are 10.0 by 14.0 by 12.0

Box b: Dimensions are 10.0 by 14.0 by 12.0

138

[email protected] http://www.ardentcollaborations.com

Page 139: Core Java Ppt

Character Extraction

charAt( )To extract a single character from a String, you can refer directly

to an Individual character via the charAt( ) method. It has this general

form:char charAt(int where)

Here, where is the index of the character that you want to obtain. The value of

where must be nonnegative and specify a location within the string. charAt( )

returns the character at the specified location. For example,char ch;ch = "abc".charAt(1);

assigns the value “b” to ch.

139

[email protected] http://www.ardentcollaborations.com

Page 140: Core Java Ppt

Character Extraction

getChars( )If you need to extract more than one character at a time, you can use the

getChars( )method. It has this general form:

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd

specifies an index that is one past the end of the desired substring. Thus, the substring

contains the characters from sourceStart through sourceEnd–1. The array that will receive

the characters is specified by target. The index within target at which the substring will

be copied is passed in targetStart. Care must be taken to assure that the target array is

large enough to hold the number of characters in the specified substring.

140

[email protected] http://www.ardentcollaborations.com

Page 141: Core Java Ppt

Character Extraction

Using-

getChars()

class getCharsDemo {public static void main(String args[]) {

String s = "This is a demo of the getChars method.";int start = 10;int end = 14;char buf[] = new char[end - start];s.getChars(start, end, buf, 0);System.out.println(buf);

}} Here is the output of this program:demo

141

[email protected] http://www.ardentcollaborations.com

Page 142: Core Java Ppt

Character Extraction

getBytes( )

There is an alternative to getChars( ) that stores the characters in an array of bytes. This method is called

getBytes( ), and it uses the default character-to-byte conversions provided by the platform. Here is its

simplest form:

byte[ ] getBytes( )

Other forms of getBytes( ) are also available. getBytes( ) is most useful when you are exporting a String

value into an environment that does not support 16-bit Unicode characters. For example, most Internet

protocols and text file formats use 8-bit ASCII for all text interchange.

toCharArray( )

If you want to convert all the characters in a String object into a character array, the easiest way is to call toCharArray( ). It returns an array of characters for the entire string. It has this general form:

char[ ] toCharArray( )

This function is provided as a convenience, since it is possible to use getChars( ) to achieve the same result.

142

[email protected] http://www.ardentcollaborations.com

Page 143: Core Java Ppt

String Comparison

equals( )To compare two strings for equality, use equals( ). It

has this general form:

boolean equals(Object str) str is the String object being compared with

the invoking String object. It returns true if the strings contain the same characters in the same order, and false otherwise.

The comparison is case-sensitive.

143

[email protected] http://www.ardentcollaborations.com

Page 144: Core Java Ppt

String Comparison

equalsIgnoreCase( ) To perform a comparison that ignores case differences, call

equalsIgnoreCase( ).When it compares two strings, it

considers A-Z to be the same as a-z. It has this general

form:

boolean equalsIgnoreCase(String str)

str is the String object being compared with the invoking String

object. It too, returns true if the strings contain the same

characters in the same order, and false otherwise.

144

[email protected] http://www.ardentcollaborations.com

Page 145: Core Java Ppt

String Comparison

Sample program illustrating equals() and equalsIgnoreCase()

class equalsDemo {

public static void main(String args[]) {

String s1 = "Hello";

String s2 = "Hello";

String s3 = "Good-bye";

String s4 = "HELLO";

System.out.println(s1 + " equals " + s2 + " -> " +

s1.equals(s2));

System.out.println(s1 + " equals " + s3 + " -> " +

s1.equals(s3));

System.out.println(s1 + " equals " + s4 + " -> " +

s1.equals(s4));

System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +

s1.equalsIgnoreCase(s4));

}

}

145

[email protected] http://www.ardentcollaborations.com

Page 146: Core Java Ppt

String Comparison

Sample program illustrating equals() and equalsIgnoreCase()

class equalsDemo {

public static void main(String args[]) {

String s1 = "Hello";

String s2 = "Hello";

String s3 = "Good-bye";

String s4 = "HELLO";

System.out.println(s1 + " equals " + s2 + " -> " +

s1.equals(s2));

System.out.println(s1 + " equals " + s3 + " -> " +

s1.equals(s3));

System.out.println(s1 + " equals " + s4 + " -> " +

s1.equals(s4));

System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +

s1.equalsIgnoreCase(s4));

}

}

OUTPUT Hello equals Hello -> trueHello equals Good-bye -> falseHello equals HELLO -> falseHello equalsIgnoreCase HELLO -> true

146

[email protected] http://www.ardentcollaborations.com

Page 147: Core Java Ppt

String Comparison

regionMatches( )This method compares a specific region inside a string with another specific region in another

string. There

is an overloaded form that allows you to ignore case in such comparisons. Here are the general forms for

these two methods:

boolean regionMatches(int startIndex, String str2,int str2StartIndex, int numChars)

boolean regionMatches(boolean ignoreCase,int startIndex, String str2,int str2StartIndex, int numChars)

For both versions, startIndex specifies the index at which the region begins within the invoking String object.

The String being compared is specified by str2. The index at which the comparison will start

within str2 is specified by str2StartIndex. The length of the substring being compared is passed in

numChars. In the second version, if ignoreCase is true, the case of the characters is ignored.

Otherwise, case is significant.

147

[email protected] http://www.ardentcollaborations.com

Page 148: Core Java Ppt

startsWith( ) and endsWith( )

String defines two routines that are, more or less, specialized forms of regionMatches( ). The startsWith( ) method determines whether a given String begins with a specified string. Conversely, endsWith( ) determines whether the String in question ends with a specified string. They have the following general forms:

boolean startsWith(String str)

boolean endsWith(String str) Here, str is the String being tested. If the string matches, true is returned.

Otherwise, false is returned. For example,

"Foobar".endsWith("bar“) and "Foobar".startsWith("Foo“) are both true. A second form of startsWith( ), shown here, lets you

specify a starting point:

boolean startsWith(String str, int startIndex) Here, startIndex specifies the index into the invoking string at which point the

search will begin. For example,

"Foobar".startsWith("bar", 3)

returns true.

[email protected] http://www.ardentcollaborations.com

148

Page 149: Core Java Ppt

equals( ) Versus ==

The equals( ) method compares the characters inside

a String object. The == operator compares two object references to see whether they refer to the same instance. The following program shows how twodifferent String objects can contain the same characters, but references to these objects will

not compare as equal.

[email protected] http://www.ardentcollaborations.com

149

Page 150: Core Java Ppt

equals( ) Versus ==

equals( ) Versus ==

class EqualsNotEqualTo

{

public static void main(String args[])

{

String s1 = "Hello";

String s2 = new String(s1);

System.out.println(s1 + " equals " + s2 + " -> " +

s1.equals(s2));

System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));

}

}[email protected] http://www.ardentcollaborations.com

150

Page 151: Core Java Ppt

equals( ) Versus ==

equals( ) Versus ==

class EqualsNotEqualTo

{

public static void main(String args[])

{

String s1 = "Hello";

String s2 = new String(s1);

System.out.println(s1 + " equals " + s2 + " -> " +

s1.equals(s2));

System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));

}

}[email protected] http://www.ardentcollaborations.com

151

OUTPUTHello equals Hello -> trueHello == Hello -> false

Page 152: Core Java Ppt

Searching Strings

The String class provides two methods that allow you to

search a string for a specified character or substring:

■ indexOf( ) Searches for the first occurrence of a character or substring.

■ lastIndexOf( ) Searches for the last occurrence of a character or substring.

[email protected] http://www.ardentcollaborations.com

152

Page 153: Core Java Ppt

Searching Strings

indexOf()

& lastIndexOf()

class indexOfDemo {

public static void main(String args[]) {

String s = "Now is the time for all good men " +"to come to the aid of their country.";

System.out.println(s);

System.out.println("indexOf(t) = " +s.indexOf('t'));

System.out.println("lastIndexOf(t) = " +s.lastIndexOf('t'));

System.out.println("indexOf(the) = " +s.indexOf("the"));

[email protected] http://www.ardentcollaborations.com

153

Page 154: Core Java Ppt

Searching Strings

indexOf()

& lastIndexOf()

System.out.println("lastIndexOf(the) = " +s.lastIndexOf("the"));

System.out.println("indexOf(t, 10) = " +s.indexOf('t', 10));

System.out.println("lastIndexOf(t, 60) = " +s.lastIndexOf('t', 60));

System.out.println("indexOf(the, 10) = " +s.indexOf("the", 10));

System.out.println("lastIndexOf(the, 60) = " +s.lastIndexOf("the", 60));

}

}

[email protected] http://www.ardentcollaborations.com

154

Now is the time for all good men to come to the aid of their country. indexOf(t) = 7lastIndexOf(t) = 65indexOf(the) = 7lastIndexOf(the) = 55indexOf(t, 10) = 11lastIndexOf(t, 60) = 55indexOf(the, 10) = 44lastIndexOf(the, 60) = 55

Page 155: Core Java Ppt

Modifying a String

String objects are immutable, whenever you want to modify a String, you must either copy it into a

StringBuffer or StringBuilder or use one of the following Stringmethods, which will construct a new copy of the string with your modifications complete.substringconcatreplacetrim

[email protected] http://www.ardentcollaborations.com

155

Page 156: Core Java Ppt

substring()

You can extract a substring using substring( ). It has

two forms.

String substring(int startIndex)

String substring(int startIndex, int endIndex)

[email protected] http://www.ardentcollaborations.com

156

Page 157: Core Java Ppt

substring()

Program using subString()

class StringReplace {

public static void main(String args[]) {

String org = "This is a test. This is, too.";

String search = "is";

String sub = "was";

String result = "";

int i;

do { // replace all matching substrings

System.out.println(org);

[email protected] http://www.ardentcollaborations.com

157

Page 158: Core Java Ppt

substring()

Program using subString()

i = org.indexOf(search);

if(i != -1) {

result = org.substring(0, i);

result = result + sub;

result = result + org.substring(i + search.length());

org = result;

}

} while(i != -1);

}

}[email protected] http://www.ardentcollaborations.com

158

This is a test. This is, too.Thwas is a test. This is, too.Thwas was a test. This is, too.Thwas was a test. Thwas is, too.Thwas was a test. Thwas was, too.

Page 159: Core Java Ppt

concat( )

You can concatenate two strings using concat( ), shown here:

String concat(String str)

This method creates a new object that contains the invoking string with the

contents of str appended to the end. concat( ) performs the same function as +. For example,

String s1 = "one";

String s2 = s1.concat("two");

puts the string “onetwo” into s2. It generates the same result as the following

sequence:

String s1 = "one";

String s2 = s1 + "two";[email protected] http://www.ardentcollaborations.com

159

Page 160: Core Java Ppt

replace( )

The replace( ) method replaces all occurrences of one character in the invoking string with another character. It has the following general form:

String replace(char original, char replacement)

Here, original specifies the character to be replaced by the

character specified by replacement. The resulting string is returned. For example,

String s = "Hello".replace('l', 'w');

puts the string “Hewwo” into [email protected] http://www.ardentcollaborations.com

160

Page 161: Core Java Ppt

trim()

The trim( ) method returns a copy of the invoking string from

which any leading and trailing whitespace has been removed. It

has this general form:

String trim( )

example:

String s = " Hello World ".trim();

This puts the string “Hello World” into s. The trim( ) method is

quite useful when you process user commands. For example,

the following program prompts the user for the name of a state

and then displays that state’s capital. It uses trim( ) to remove any leading or

trailing whitespace that may have inadvertently been entered by the user.

[email protected] http://www.ardentcollaborations.com

161

Page 162: Core Java Ppt

trim()

Program showing trim().

import java.io.*; class UseTrim { public static void main(String args[]) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter 'stop' to quit."); System.out.println("Enter State: "); do {

[email protected] http://www.ardentcollaborations.com

162

Page 163: Core Java Ppt

trim()

Program showing trim().

str = br.readLine(); str = str.trim(); // remove whitespace if(str.equals("Illinois")) System.out.println("Capital is Springfield."); else if(str.equals("Missouri")) System.out.println("Capital is Jefferson City."); else if(str.equals("California")) System.out.println("Capital is Sacramento."); else if(str.equals("Washington")) System.out.println("Capital is Olympia."); // ... } while(!str.equals("stop")); } }

[email protected] http://www.ardentcollaborations.com

163

Page 164: Core Java Ppt

Data Conversion Using valueOf( )

The valueOf( ) method converts data from its internal format into a

human-readable form. It is a static method that is overloaded within

String for all of Java’s built-in types, so that each type can be

converted properly into a string. valueOf( ) is also overloaded

for type Object, so an object of any class type you create can also be

used as an argument.(Recall that Object is a superclass for all classes.)

Here are a few of its forms: static String valueOf(double num) static String valueOf(long num) static String valueOf(Object ob) static String valueOf(char chars[ ])

[email protected] http://www.ardentcollaborations.com

164

Page 165: Core Java Ppt

Changing the Case of CharactersWithin a String

String toLowerCase( )

String toUpperCase( )

[email protected] http://www.ardentcollaborations.com

165

Page 166: Core Java Ppt

Changing the Case of CharactersWithin a Stringusing toUpperCase()

and

toLowerCase()

class ChangeCase { public static void main(String args[]) { String s = "This is a test."; System.out.println("Original: " + s); String upper = s.toUpperCase(); String lower = s.toLowerCase(); System.out.println("Uppercase: " + upper); System.out.println("Lowercase: " + lower); } }adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

166

Original: This is a test.Uppercase: THIS IS A TEST.Lowercase: this is a test.

Page 167: Core Java Ppt

String Buffer

StringBuffer is a peer class of String that provides much of the functionality of strings.As you know, String represents fixed-length, immutable character sequences. In contrast, StringBuffer represents growable and writeable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end.

StringBuffer will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth. Java uses both classes heavily, but many programmers deal only with String and let Java manipulate StringBuffers behind the scenes by using the overloaded + operator.

[email protected] http://www.ardentcollaborations.com

167

Page 168: Core Java Ppt

String Buffer

StringBuffer Constructors StringBuffer defines these three constructors:

StringBuffer( ) StringBuffer(int size) StringBuffer(String str)

The default constructor (the one with no parameters) reserves room for 16 characters without reallocation. The second version accepts an integer argument that explicitly sets the size of the buffer. The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.StringBuffer allocates room for 16 additionalcharacters when no specific buffer length is requested, because reallocation is a costly process in terms of time. Also, frequent reallocations can fragment memory. By allocating room for a few extra characters, StringBuffer reduces the number of reallocations that take place.adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

168

Page 169: Core Java Ppt

String Buffer

length( ) and capacity( ) The current length of a StringBuffer can be found via

the length( ) method, while the total allocated capacity can be found through the capacity( ) method. They have the following general forms:

int length( )

int capacity( )

[email protected] http://www.ardentcollaborations.com

169

Page 170: Core Java Ppt

String Buffer

length( ) and capacity( )

class StringBufferDemo {

public static void main(String args[]) {

StringBuffer sb = new StringBuffer("Hello");

System.out.println("buffer = " + sb);

System.out.println("length = " + sb.length());

System.out.println("capacity = " + sb.capacity());

}

}[email protected] http://www.ardentcollaborations.com

170

buffer = Hellolength = 5capacity = 21

Page 171: Core Java Ppt

String Buffer

ensureCapacity( )If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer. ensureCapacity( ) has this general form:

void ensureCapacity(int capacity)

Here, capacity specifies the size of the [email protected] http://www.ardentcollaborations.com

171

Page 172: Core Java Ppt

String Buffer

setLength( )To set the length of the buffer within a StringBuffer object,

use setLength( ).

Its general form is shown here:

void setLength(int len)

[email protected] http://www.ardentcollaborations.com

172

Page 173: Core Java Ppt

String Buffer

charAt( ) and setCharAt( )The value of a single character can be obtained from a

StringBuffer via the

charAt( ) method. You can set the value of a character within a StringBuffer

using setCharAt( ).

Their general forms are shown here:

char charAt(int where) void setCharAt(int where, char ch)

[email protected] http://www.ardentcollaborations.com

173

Page 174: Core Java Ppt

String Buffer

Program explanning charAt(),setCharAt(),setLength()

class setCharAtDemo {

public static void main(String args[]) {

StringBuffer sb = new StringBuffer("Hello");

System.out.println("buffer before = " + sb);

System.out.println("charAt(1) before = " + sb.charAt(1));

sb.setCharAt(1, 'i');

sb.setLength(2);

System.out.println("buffer after = " + sb);

System.out.println("charAt(1) after = " + sb.charAt(1));

}

}[email protected] http://www.ardentcollaborations.com

174

buffer before = HellocharAt(1) before = ebuffer after = HicharAt(1) after = i

Page 175: Core Java Ppt

String Buffer

getChars( )To copy a substring of a StringBuffer into an array, use the getChars( ) method. It hasthis general form:

void getChars(int sourceStart, int sourceEnd, char target[ ],int targetStart)

Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from sourceStart through sourceEnd–1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring.adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

175

Page 176: Core Java Ppt

String Buffer

append( ) The append( ) method concatenates the string

representation of any other type of data to the end of the invoking StringBuffer object. It has overloaded versions for all the built-in types and for Object. Here are a few of its forms:

StringBuffer append(String str)

StringBuffer append(int num)

StringBuffer append(Object obj)

String.valueOf( ) is called for each parameter to obtain its string representation. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append( ). This allows subsequent calls to be chained together.adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

176

Page 177: Core Java Ppt

String Buffer

Program showing

append()

class appendDemo {

public static void main(String args[]) {

String s;

int a = 42;

StringBuffer sb = new StringBuffer(40);

s = sb.append("a=").append(a).append("!").toString();

System.out.println(s);

}

}

[email protected] http://www.ardentcollaborations.com

177

a = 42!

Page 178: Core Java Ppt

String Buffer

insert( )The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects.

Few forms: StringBuffer insert(int index, String str) StringBuffer insert(int index, char ch) StringBuffer insert(int index, Object obj)

Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer object.

[email protected] http://www.ardentcollaborations.com

178

Page 179: Core Java Ppt

String Buffer

insert( ) class insertDemo {public static void main(String

args[]) {StringBuffer sb = new

StringBuffer("I Java!"); sb.insert(2, "like "); System.out.println(sb); } }adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

179

I like Java!

Page 180: Core Java Ppt

String Buffer

reverse( ) You can reverse the characters within a StringBuffer object

using reverse( ), shown here:

StringBuffer reverse( )

This method returns the reversed object on which it was called.

[email protected] http://www.ardentcollaborations.com

180

Page 181: Core Java Ppt

String Buffer

reverse() class ReverseDemo {public static void main(String args[]) {StringBuffer s = new StringBuffer("abcdef");System.out.println(s);s.reverse();System.out.println(s);}}

[email protected] http://www.ardentcollaborations.com

181

abcdeffedcba

Page 182: Core Java Ppt

String Buffer

delete( ) and deleteCharAt( )

Used to delete chararcters from StringBuffer.

Forms:

StringBuffer delete(int startIndex, int endIndex)

StringBuffer deleteCharAt(int loc)

[email protected] http://www.ardentcollaborations.com

182

Page 183: Core Java Ppt

String Buffer

delete()

and

deleteCharAt()

class deleteDemo {

public static void main(String args[]) {

StringBuffer sb = new StringBuffer("This is a test.");

sb.delete(4, 7);

System.out.println("After delete: " + sb);

sb.deleteCharAt(0);

System.out.println("After deleteCharAt: " + sb);

}

}[email protected] http://www.ardentcollaborations.com

183

After delete: This a test.After deleteCharAt: his a test.

Page 184: Core Java Ppt

String Buffer

replace( ) It replaces one set of characters with another set inside

a StringBuffer object. Its signature is shown here:

StringBuffer replace(int startIndex, int endIndex, String str)

The substring being replaced is specified by the indexes

startIndex and endIndex. Thus, the substring at startIndex

through endIndex–1 is replaced. The replacement string is

passed in str. The resulting StringBuffer object is returned.

[email protected] http://www.ardentcollaborations.com

184

Page 185: Core Java Ppt

String Buffer

repalce() class replaceDemo {public static void main(String args[]) {StringBuffer sb = new StringBuffer("This is a test.");sb.replace(5, 7, "was");System.out.println("After replace: " + sb);}}adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

185

After replace: This was a test.

Page 186: Core Java Ppt

String Buffer

substring( )Java also added the substring( ) method, which returns a portion of a StringBuffer. It has the following two forms:

String substring(int startIndex)

String substring(int startIndex, int endIndex)

The first form returns the substring that starts at startIndex and runs to the end of the invoking StringBuffer object. The second form returns the substring that starts at startIndex and runs through endIndex–1. These methods work just like those defined for String that were described earlier.

[email protected] http://www.ardentcollaborations.com

186

Page 187: Core Java Ppt

StringBuilder

StringBuilder is introduced from jdk5StringBuilder is identical to StringBuffer

except for one important diference : it is not synchronized,which means that it is not thread-safe.

Adv: Faster Performance

[email protected] http://www.ardentcollaborations.com

187

Page 188: Core Java Ppt

Explore java.lang package

188

[email protected] http://www.ardentcollaborations.com

ByAdrish BhattacharyayArdent Collaborations

Page 189: Core Java Ppt

Introduction

java.lang is automatically imported into all programs. It contains classes and interfaces that are fundamental to virtually all of Java programming. It is Java’s most widely used package.

[email protected] http://www.ardentcollaborations.com

189

Page 190: Core Java Ppt

java.lang.*(classes)

Boolean InheritableThreadLocal

Runtime System

Byte Integer RuntimePermission

Thread

Character Long SecurityManager ThreadGroup

Class Math Short ThreadLocal

ClassLoader Number StackTraceElement

Throwable

Compiler Object StrictMath Void

Double Package String

Enum Process StringBuffer

Float ProcessBuilder [email protected] http://www.ardentcollaborations.com

190

There are two classes defined by Character: Character.Subset andCharacter.UnicodeBlock.

Page 191: Core Java Ppt

java.lang.*(interfaces)

Appendable Comparable Runnable

CharSequence Iterable

Cloneable Readable

[email protected] http://www.ardentcollaborations.com

191

Page 192: Core Java Ppt

Primitive Type Wrapper

Number The abstract class Number defines a superclass that is

implemented by the classes that wrap the numeric types byte, short, int, long, float, and double. Number has abstract methods that return the value of the object in each of the different number formats.That is, doubleValue( ) returns the value as a double, floatValue( ) returns the value as a float, and so on. These methods are shown here:

The values returned by these methods can be rounded.Number has six concrete subclasses that hold explicit values of each numeric type:adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

192

byte byteValue( ) double doubleValue( )

float floatValue( )

int intValue( ) long longValue( ) short shortValue( )

Double Float

Byte Short Integer Long

Page 193: Core Java Ppt

Primitive Type Wrapper

Number

Double and Float:

Double and Float are wrappers for floating-point values of type double and float, respectively. The constructors for Float are shown here:

Float(double num) Float(float num) Float(String str) throws NumberFormatException

Float objects can be constructed with values of type float or double. They can also be constructed from the string representation of a floating-point number.

[email protected] http://www.ardentcollaborations.com

193

Page 194: Core Java Ppt

Primitive Type Wrapper

Number

Double and Float:

The constructors for Double are shown here: Double(double num) Double(String str) throws NumberFormatException

Double objects can be constructed with a double value or a string containing a

floating-point value.

[email protected] http://www.ardentcollaborations.com

194

Page 195: Core Java Ppt

Primitive Type Wrapper

Number

Double and Float: Both Float and Double define the following constants:

[email protected] http://www.ardentcollaborations.com

195

MAX_VALUE Maximum positive value

MIN_VALUE Minimum positive value

NaN Not a number

POSITIVE_INFINITY Positive infinity

NEGATIVE_INFINITY Negative infinity

TYPE The Class object for float or double

SIZE The bit width of the wrapped value(from J2SE5)

MAX_EXPONENT Maximum exponent(from JSE6)

MIN_EXPONENT Minimum exponent(from JSE6)

MIN_NORMAL Minimum positive normal value(from JSE6)

Page 196: Core Java Ppt

Primitive Type Wrapper

Number Double and Float: Methods defined by Float

[email protected] http://www.ardentcollaborations.com

196

Method Description

byte byteValue( ) Returns the value of the invoking object asa byte.

static int compare(float num1,float num2) Compares the values of num1 and num2.Returns 0 if the values are equal. Returns anegative value if num1 is less than num2.Returns a positive value if num1 is greaterthan num2.

int compareTo(Float f) Compares the numerical value of theinvoking object with that of f. Returns 0 ifthe values are equal. Returns a negativevalue if the invoking object has a lowervalue. Returns a positive value if theinvoking object has a greater value.(Added by Java 2)

Page 197: Core Java Ppt

Primitive Type Wrapper

Number Double and Float: Methods defined by Float

[email protected] http://www.ardentcollaborations.com

197

Method Description

int compareTo(Object obj) Operates identically to compareTo(Float)if obj is of class Float. Otherwise, throws aClassCastException.

double doubleValue( ) Returns the value of the invoking object asa double.

boolean equals(Object FloatObj) Returns true if the invoking Float object isequivalent to FloatObj. Otherwise, itreturns false

static int floatToIntBits(float num) Returns the IEEE-compatible,single-precision bit pattern that corresponds to the num.

static int floatToRawIntBits(float num) Returns the IEEE-compatible,single-precision bit pattern that corresponds to the num.A NaN value is returned.

Page 198: Core Java Ppt

Primitive Type Wrapper

Number Double and Float: Methods defined by Float

[email protected] http://www.ardentcollaborations.com

198

Method Description

float floatValue( ) Returns the value of the invoking object asa float.

int hashCode( ) Returns the hash code for the invoking object.

static float intBitsToFloat(int num) Returns float equivalent of the IEEE-compatible, single-precision bit pattern specified by num.

int intValue( ) Returns the value of the invoking object as an int.

boolean isInfinite( ) Returns true if the invoking object containsan infinite value. Otherwise, it returns false.

static boolean isInfinite(float num) Returns true if num specifies an infinitevalue. Otherwise, it returns false.

Page 199: Core Java Ppt

Primitive Type Wrapper

Number Double and Float: Methods defined by Float

[email protected] http://www.ardentcollaborations.com

199

Method Description

boolean isNaN( ) Returns true if the invoking object contains a value that is not a number. Otherwise, it returns false.

static boolean isNaN(float num) Returns true if num specifies a value that isnot a number. Otherwise, it returns false.

long longValue( ) Returns the value of the invoking object asa long.

static float parseFloat(String str)throws NumberFormatException

Returns the float equivalent of the numbercontained in the string specified by strusing radix 10.

short shortValue( ) Returns the value of the invoking object asa short.

static String toHexString(float num) Returns a string containing the value of num in hexadecimal format.

Page 200: Core Java Ppt

Primitive Type Wrapper

Number Double and Float: Methods defined by Float

[email protected] http://www.ardentcollaborations.com

200

Method Description

String toString( ) Returns the string equivalent of theinvoking object.

static String toString(float num) Returns the string equivalent of the valuespecified by num.

static Float valueOf(String str)throws NumberFormatException

Returns the Float object that contains thevalue specified by the string in str.

static Float valueOf(float num) Returns the Float object containing value specified by string in str.

Page 201: Core Java Ppt

Primitive Type Wrapper

Number Double and Float: Methods defined by Double

[email protected] http://www.ardentcollaborations.com

201

Method Description

byte byteValue( ) Returns the value of the invoking object asa byte.

static int compare(double num1, double num2)

Compares the values of num1 and num2.Returns 0 if the values are equal. Returns anegative value if num1 is less than num2.Returns a positive value if num1 is greaterthan num2.

int compareTo(Double f) Compares the numerical value of theinvoking object with that of f. Returns 0 ifthe values are equal. Returns a negativevalue if the invoking object has a lowervalue. Returns a positive value if theinvoking object has a greater value.(Added by Java 2)

Page 202: Core Java Ppt

Primitive Type Wrapper

Number Double and Float: Methods defined by Double

[email protected] http://www.ardentcollaborations.com

202

Method Description

int compareTo(Object obj) Operates identically to compareTo(Float)if obj is of class Float. Otherwise, throws aClassCastException.

double doubleValue( ) Returns the value of the invoking object asa double.

boolean equals(Object DoubleObj) Returns true if the invoking Double object isequivalent to DoubleObj. Otherwise, itreturns false

static long doubleToLongBits(float num) Returns the IEEE-compatible,single-precision bit pattern that corresponds to the num.

static long doubleToRawLongBits(float num)

Returns the IEEE-compatible,single-precision bit pattern that corresponds to the num.A NaN value is returned.

Page 203: Core Java Ppt

Primitive Type Wrapper

Number Double and Float: Methods defined by Double

[email protected] http://www.ardentcollaborations.com

203

Method Description

float floatValue( ) Returns the value of the invoking object asa float.

int hashCode( ) Returns the hash code for the invoking object.

static double longBitsToDouble (int num) Returns double equivalent of the IEEE-compatible, single-precision bit pattern specified by num.

int intValue( ) Returns the value of the invoking object as an int.

boolean isInfinite( ) Returns true if the invoking object containsan infinite value. Otherwise, it returns false.

static boolean isInfinite(double num) Returns true if num specifies an infinitevalue. Otherwise, it returns false.

Page 204: Core Java Ppt

Primitive Type Wrapper

Number Double and Float: Methods defined by Double

[email protected] http://www.ardentcollaborations.com

204

Method Description

boolean isNaN( ) Returns true if the invoking object contains a value that is not a number. Otherwise, it returns false.

static boolean isNaN(double num) Returns true if num specifies a value that isnot a number. Otherwise, it returns false.

long longValue( ) Returns the value of the invoking object asa long.

static double parseDouble (String str)throws NumberFormatException

Returns the double equivalent of the numbercontained in the string specified by strusing radix 10.

short shortValue( ) Returns the value of the invoking object asa short.

static String toHexString(double num) Returns a string containing the value of num in hexadecimal format.

Page 205: Core Java Ppt

Primitive Type Wrapper

Number Double and Float: Methods defined by Double

[email protected] http://www.ardentcollaborations.com

205

Method Description

String toString( ) Returns the string equivalent of theinvoking object.

static String toString(double num) Returns the string equivalent of the valuespecified by num.

static Double valueOf(String str)throws NumberFormatException

Returns the Double object that contains thevalue specified by the string in str.

static Double valueOf(double num) Returns the Double object containing value specified by string in str.

Page 206: Core Java Ppt

Example

Demonstrating ifInfinite() and isNan():

[email protected] http://www.ardentcollaborations.com

206

Float and Double provide the methods isInfinite( ) and isNaN( ), which help whenmanipulating two special double and float values. These methods test for two uniquevalues defined by the IEEE floating-point specification: infinity and NaN (not a number). isInfinite( ) returns true if the value being tested is infinitely large or small in magnitude. isNaN( ) returns true if the value being tested is not a number.

Page 207: Core Java Ppt

Example

Demonstrating ifInfinite() and isNan():

class InfNaN {

public static void main(String args[]) {

Double d1 = new Double(1/0.);

Double d2 = new Double(0/0.);

System.out.println(d1 + ": " + d1.isInfinite() + ", " + d1.isNaN());

System.out.println(d2 + ": " + d2.isInfinite() + ", " + d2.isNaN());

}

}[email protected] http://www.ardentcollaborations.com

207

Page 208: Core Java Ppt

Example

Demonstrating ifInfinite() and isNan():

class InfNaN {

public static void main(String args[]) {

Double d1 = new Double(1/0.);

Double d2 = new Double(0/0.);

System.out.println(d1 + ": " + d1.isInfinite() + ", " + d1.isNaN());

System.out.println(d2 + ": " + d2.isInfinite() + ", " + d2.isNaN());

}

}[email protected] http://www.ardentcollaborations.com

208

Infinity: true, falseNaN: false, true

Page 209: Core Java Ppt

Primitive Type Wrapper

Number

Byte, Short, Integer, and Long:

The Byte, Short, Integer, and Long classes are wrappers for byte, short, int, and long

integer types, respectively.

CONSTRUCTORS: Byte(byte num)

Byte(String str) throws NumberFormatException

Short(short num)

Short(String str) throws NumberFormatException

Integer(int num)

Integer(String str) throws NumberFormatException

Long(long num)

Long(String str) throws [email protected] http://www.ardentcollaborations.com

209

Page 210: Core Java Ppt

Primitive Type Wrapper

Number

Byte, Short, Integer, and Long:

CONSTANTS:

[email protected] http://www.ardentcollaborations.com

210

MIN_VALUE Minimum value

MAX_VALUE Maximum value

TYPE The Class object for byte, short, int, or long

SIZE The bit width of the wrapped value.

Page 211: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long:METHODS

[email protected] http://www.ardentcollaborations.com

211

Method Description

byte byteValue( ) Returns the value of the invoking object as a byte.

int compareTo(Byte b) Compares the numerical value of the invoking object with that of b. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value.Returns a positive value if the invoking object has a greater value.

int compareTo(Object obj) Operates identically to compareTo(Byte) if obj is of classByte. Otherwise, throws a ClassCastException.

Page 212: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long:METHODS

[email protected] http://www.ardentcollaborations.com

212

Method Description

static Byte decode(String str)throws NumberFormatException

Returns a Byte object that contains the value specified by the string in str.

double doubleValue( ) Returns the value of the invoking object as a double.

boolean equals(Object ByteObj)

Returns true if the invoking Byte object is equivalent to ByteObj. Otherwise, it returns false.

float floatValue( ) Returns the value of the invokingobject as a float.

int hashCode( ) Returns the hash code for the invoking object.

Page 213: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long:METHODS

[email protected] http://www.ardentcollaborations.com

213

Method Description

int intValue( ) Returns the value of the invoking object as an int.

long longValue() Returns the value of the invoking object as a long.

static byte parseByte(String str)throws NumberFormatException

Returns the byte equivalent of the number contained in the string specified by str using radix 10.

static byte parseByte(String str, int radix)throws NumberFormatException

Returns the byte equivalent of the number contained in the string specified by str using the specified radix

Page 214: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long:METHODS

[email protected] http://www.ardentcollaborations.com

214

Method Description

short shortValue( ) Returns the value of the invoking object as a short.

String toString( ) Returns a string that contains the decimal equivalent of the invoking object

static String toString(byte num)

Returns a string that contains the decimal equivalent of num.

static Byte valueOf(String str)throws NumberFormatException

Returns a Byte object that contains the value specified by the string in str.

static Byte valueOf(String str, int radix)throws NumberFormatException

Returns a Byte object that containsthe value specified by the string instr using the specified radix.

Page 215: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long:METHODS

[email protected] http://www.ardentcollaborations.com

215

Method Description

byte byteValue( ) Returns the value of the invoking object as a short.

int compareTo(Short s) Compares the numerical value of the invoking object with that of b. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value.Returns a positive value if the invoking object has a greater value.

int compareTo(Object obj) Operates identically to compareTo(Short) if obj is of classShort. Otherwise, throws a ClassCastException.

Page 216: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long:METHODS

[email protected] http://www.ardentcollaborations.com

216

Method Description

static Short decode(String str)throws NumberFormatException

Returns a Short object that contains the value specified by the string in str.

double doubleValue( ) Returns the value of the invoking object as a double.

boolean equals(Object ShortObj)

Returns true if the invoking Short object is equivalent to ByteObj. Otherwise, it returns false.

float floatValue( ) Returns the value of the invokingobject as a float.

int hashCode( ) Returns the hash code for the invoking object.

Page 217: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long:METHODS

[email protected] http://www.ardentcollaborations.com

217

Method Description

int intValue( ) Returns the value of the invoking object as an int.

long longValue() Returns the value of the invoking object as a long.

static short parseShort (String str)throws NumberFormatException

Returns the short equivalent of the number contained in the string specified by str using radix 10.

static short parseShort (String str, int radix)throws NumberFormatException

Returns the short equivalent of the number contained in the string specified by str using the specified radix

Page 218: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long:METHODS

[email protected] http://www.ardentcollaborations.com

218

Method Description

short shortValue( ) Returns the value of the invoking object as a short.

String toString( ) Returns a string that contains the decimal equivalent of the invoking object

static String toString(short num)

Returns a string that contains the decimal equivalent of num.

static Short valueOf(String str)throws NumberFormatException

Returns a Short object that contains the value specified by the string in str.

static Short valueOf(String str,int radix)throws NumberFormatException

Returns a Short object that contains the value specified by the string in str using the specified radix.

Page 219: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long:METHODS

[email protected] http://www.ardentcollaborations.com

219

Method Description

byte byteValue( ) Returns the value of the invoking object as a short.

int compareTo(Integer i) Compares the numerical value of the invoking object with that of b. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value.Returns a positive value if the invoking object has a greater value.

int compareTo(Object obj) Operates identically to compareTo(Integer) if obj is of classInteger. Otherwise, throws a ClassCastException.

static int bitCount(int num) Returns the number of set bits in num.

Page 220: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long:METHODS

[email protected] http://www.ardentcollaborations.com

220

Method Description

static Integer decode(String str)throws NumberFormatException

Returns a Integer object that contains the value specified by the string in str.

double doubleValue( ) Returns the value of the invoking object as a double.

boolean equals(Object IntegerObj)

Returns true if the invoking Short object is equivalent to IntegerObj. Otherwise, it returns false.

float floatValue( ) Returns the value of the invokingobject as a float.

int hashCode( ) Returns the hash code for the invoking object.

static int lowestOneBit(int num)

Method Description

static Integer decode(String str)throws NumberFormatException

Returns a Integer object that contains the value specified by the string in str.

double doubleValue( ) Returns the value of the invoking object as a double.

boolean equals(Object IntegerObj)

Returns true if the invoking Short object is equivalent to IntegerObj. Otherwise, it returns false.

float floatValue( ) Returns the value of the invokingobject as a float.

int hashCode( ) Returns the hash code for the invoking object.

static int lowestOneBit(int num)

Determines the number of high-order zero bits that precede the first high-order set bit in num.If num is zero,32 is returned.

Page 221: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long:METHODS

[email protected] http://www.ardentcollaborations.com

221

Method Description

int intValue( ) Returns the value of the invoking object as an int.

static Integer getInteger(String propertyName)

Returns the value associated with the environmental property specified by propertyName. A null is returned on failure.

static Integer getInteger(String propertyName,int default)

Returns the value associated with the environmental propertyspecified by propertyName. The value of default is returnedon failure.

long longValue() Returns the value of the invoking object as a long.

static int parseInt (String str)throws NumberFormatException

Returns the integer equivalent of the number contained in the string specified by str using radix 10.

static int parseInt (String str, int radix)throws NumberFormatException

Returns the integer equivalent of the number contained in the string specified by str using the specified radix

Page 222: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long:METHODS

[email protected] http://www.ardentcollaborations.com

222

Method Description

short shortValue( ) Returns the value of the invoking object as a short.

String toString( ) Returns a string that contains the decimal equivalent of the invoking object

static String toString(short num)

Returns a string that contains the decimal equivalent of num.

static Integer valueOf(String str)throws NumberFormatException

Returns a Integer object that contains the value specified by the string in str.

static Integer valueOf(String str,int radix)throws NumberFormatException

Returns a Integer object that contains the value specified by the string in str using the specified radix.

Page 223: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long: METHODS

[email protected] http://www.ardentcollaborations.com

223

Method Description

byte byteValue( ) Returns the value of the invoking object as a short.

int compareTo(Long l) Compares the numerical value of the invoking object with that of b. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value.Returns a positive value if the invoking object has a greater value.

int compareTo(Object obj) Operates identically to compareTo(Long) if obj is of classLong. Otherwise, throws a ClassCastException.

static int bitCount(int num) Returns the number of set bits in num.

Page 224: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long: METHODS

[email protected] http://www.ardentcollaborations.com

224

Method Description

static Integer decode(String str)throws NumberFormatException

Returns a Integer object that contains the value specified by the string in str.

double doubleValue( ) Returns the value of the invoking object as a double.

boolean equals(Object IntegerObj)

Returns true if the invoking Short object is equivalent to IntegerObj. Otherwise, it returns false.

float floatValue( ) Returns the value of the invokingobject as a float.

int hashCode( ) Returns the hash code for the invoking object.

static int lowestOneBit(int num)

Method Description

static Long decode(String str)throws NumberFormatException

Returns a Long object that contains the value specified by the string in str.

double doubleValue( ) Returns the value of the invoking object as a double.

boolean equals(Object LongObj)

Returns true if the invoking Short object is equivalent to LongObj. Otherwise, it returns false.

float floatValue( ) Returns the value of the invokingobject as a float.

int hashCode( ) Returns the hash code for the invoking object.

static long lowestOneBit(long num)

Determines the number of high-order zero bits that precede the first high-order set bit in num.If num is zero,32 is returned.

Page 225: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long: METHODS

[email protected] http://www.ardentcollaborations.com

225

Method Description

int intValue( ) Returns the value of the invoking object as an int.

static Long getLong (String propertyName)

Returns the value associated with the environmental property specified by propertyName. A null is returned on failure.

static Long getLong (String propertyName,int default)

Returns the value associated with the environmental propertyspecified by propertyName. The value of default is returnedon failure.

long longValue() Returns the value of the invoking object as a long.

static long parseLong (String str)throws NumberFormatException

Returns the long equivalent of the number contained in the string specified by str using radix 10.

static long parseLong (String str, int radix)throws NumberFormatException

Returns the long equivalent of the number contained in the string specified by str using the specified radix

Page 226: Core Java Ppt

Primitive Type Wrapper

Number

Byte , Short, Integer, and Long: METHODS

[email protected] http://www.ardentcollaborations.com

226

Method Description

short shortValue( ) Returns the value of the invoking object as a short.

String toString( ) Returns a string that contains the decimal equivalent of the invoking object

static String toString(short num)

Returns a string that contains the decimal equivalent of num.

static Integer valueOf(String str)throws NumberFormatException

Returns a Integer object that contains the value specified by the string in str.

static Integer valueOf(String str,int radix)throws NumberFormatException

Returns a Integer object that contains the value specified by the string in str using the specified radix.

Page 227: Core Java Ppt

Primitive Type Wrapper

Converting Numbers to and from Strings The Byte, Short, Integer, and Long classes provide the

parseByte(),parseShort( ), parseInt( ), and parseLong( )

methods, respectively.

These methods return byte ,short,int and long equivalent of the input string respectively.

[email protected] http://www.ardentcollaborations.com

227

Page 228: Core Java Ppt

Example of parseInt()

This program sums a list of numbers entered by the user. It converts the string representation of each number into an int using parseInt()

import java.io.*;

class ParseDemo {

public static void main(String args[])

throws IOException

{

BufferedReader(new InputStreamReader(System.in));

String str;

int i;

int sum=0;

System.out.println("Enter numbers, 0 to quit.");[email protected] http://www.ardentcollaborations.com

228

Page 229: Core Java Ppt

Example of parseInt()

This program sums a list of numbers entered by the user. It converts the string representation of each number into an int using parseInt()

do {

str = br.readLine();

try {

i = Integer.parseInt(str);

} catch(NumberFormatException e) {

System.out.println("Invalid format");

i = 0;

}

sum += i;

System.out.println("Current sum is: " + sum);

} while(i != 0);

}

}

[email protected] http://www.ardentcollaborations.com

229

Page 230: Core Java Ppt

Primitive Type Wrapper

Converting Numbers to and from Strings

To convert a whole number into a decimal string, use the versions of toString( )

defined in the Byte, Short, Integer, or Long classes.

The Integer and Long classes also provide the methods toBinaryString( ),

toHexString( ), and toOctalString( ), which convert a value into a binary,

hexadecimal, or octal string, [email protected] http://www.ardentcollaborations.com

230

Page 231: Core Java Ppt

Example showing number to string conv.

Convert an integer into binary, hexadecimal, and octal string.

class StringConversions {

public static void main(String args[]) {

int num = 19648;

System.out.println(num + " in binary: " +

Integer.toBinaryString(num));

System.out.println(num + " in octal: " +

Integer.toOctalString(num));

System.out.println(num + " in hexadecimal: " +

Integer.toHexString(num));

}

}[email protected] http://www.ardentcollaborations.com

231

19648 in binary: 10011001100000019648 in octal: 4630019648 in hexadecimal: 4cc0

OUTPUT

Page 232: Core Java Ppt

Primitive Type Wrapper

CharacterCharacter is a simple wrapper around a char.

The constructor for Character is

Character(char ch)

To obtain the char value contained in a Character object, call charValue( ),shown here:

char charValue( )[email protected] http://www.ardentcollaborations.com

232

Page 233: Core Java Ppt

Primitive Type Wrapper

CharacterCOSTANTS

[email protected] http://www.ardentcollaborations.com

233

MAX_RADIX The largest radix

MIN_RADIX The smallest radix

MAX_VALUE The largest character value

MIN_VALUE The smallest character value

TYPE The Class object for char

Page 234: Core Java Ppt

Primitive Type Wrapper

Character:Methods

[email protected] http://www.ardentcollaborations.com

234

METHOD DESCRIPTION

static boolean isDefined(char ch) Returns true if ch is defined by Unicode. Otherwise, it returns false.

static boolean isDigit(char ch) Returns true if ch is a digit.Otherwise, it returns false.

static boolean isIdentifierIgnorable(char ch)

Returns true if ch should be ignored in an identifier.Otherwise, it returns false.

static boolean isISOControl(char ch) Returns true if ch is an ISO control character. Otherwise, it returns false.

static boolean isJavaIdentifierPart(char ch)

Returns true if ch is allowed as part of a Java identifier (other than the first character). Otherwise, it returns false.

Page 235: Core Java Ppt

Primitive Type Wrapper

Character:Methods

[email protected] http://www.ardentcollaborations.com

235

METHOD DESCRIPTION

static boolean isJavaIdentifierStart(char ch)

Returns true if ch is allowed as the first character of a Java identifier. Otherwise,it returns false.

static boolean isLetter(char ch) Returns true if ch is a letter.Otherwise, it returns false.

static boolean isLetterOrDigit(char ch) Returns true if ch is a letter or a digit. Otherwise, it returns false.

static boolean isLowerCase(char ch) Returns true if ch is a lowercase letter. Otherwise, it returns false.

static boolean isMirrored(char ch) Returns true if ch is a mirrored Unicode character. A mirrored character is one that is reversed for text that is displayed right-to-left.

Page 236: Core Java Ppt

Primitive Type Wrapper

Character:Methods

[email protected] http://www.ardentcollaborations.com

236

METHOD DESCRIPTION

static boolean isSpaceChar(char ch) Returns true if ch is a Unicode space character. Otherwise, it returns false.

static boolean isTitleCase(char ch) Returns true if ch is a Unicode titlecase character. Otherwise, it returns false.

static boolean isUnicodeIdentifierPart(char ch)

Returns true if ch is allowed as part of a Unicode identifier (other than the first character).Otherwise, it returns false.

static boolean isUnicodeIdentifierStart(char ch)

Returns true if ch is allowed as the first character of a Unicode identifier. Otherwise,it returns false.

static boolean isUpperCase(char ch) Returns true if ch is an uppercase letter. Otherwise, it returns false.

Page 237: Core Java Ppt

Primitive Type Wrapper

Character:Methods

[email protected] http://www.ardentcollaborations.com

237

METHOD DESCRIPTION

static boolean isWhitespace(char ch) Returns true if ch is whitespace. Otherwise, it returns false.

static char toLowerCase(char ch) Returns lowercase equivalent of ch.

static char toTitleCase(char ch) Returns titlecase equivalent of ch.

static char toUpperCase(char ch) Returns uppercase equivalent of ch.

Page 238: Core Java Ppt

Primitive Type Wrapper

Character:Methods Character defines the forDigit( )

and digit( ) methods, shown here:

static char forDigit(int num, int radix) static int digit(char digit, int radix)

[email protected] http://www.ardentcollaborations.com

238

Page 239: Core Java Ppt

Primitive Type Wrapper

Character:Methods int compareTo(Character c) int compareTo(Object obj) The first form returns 0 if the invoking object

and c have the same value. It returns a negative value if the invoking object has a lower value. Otherwise, it returns a positive value. The second form works just like the first if obj is a reference to a Character. Otherwise, a ClassCastException is thrown.adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

239

Page 240: Core Java Ppt

Demonstrate several Is... methods.

Demonstrate several Is... methods.

class IsDemo { public static void main(String args[]) { char a[] = {'a', 'b', '5', '?', 'A', ' '}; for(int i=0; i<a.length; i++) { if(Character.isDigit(a[i])) System.out.println(a[i] + " is a digit."); if(Character.isLetter(a[i])) System.out.println(a[i] + " is a letter."); if(Character.isWhitespace(a[i])) System.out.println(a[i] + " is whitespace."); if(Character.isUpperCase(a[i])) System.out.println(a[i] + " is uppercase."); if(Character.isLowerCase(a[i])) System.out.println(a[i] + " is lowercase."); } } }adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

240

a is a letter.a is lowercase.b is a letter.b is lowercase.5 is a digit.A is a letter.A is uppercase.is whitespace.

Page 241: Core Java Ppt

Primitive Type Wrapper

Boolean Boolean is a very thin wrapper around boolean values,

which is useful mostly when you want to pass a boolean variable by reference. It contains the constants TRUE and FALSE, which define true and false Boolean objects. Boolean also defines the TYPE field, which is the Class object for boolean. Boolean defines these constructors:

Boolean(boolean boolValue)

Boolean(String boolString) In the first version, boolValue must be either true or false. In the

second version, if boolString contains the string “true” (in uppercase or lowercase), then the new Boolean

object will be true. Otherwise, it will be [email protected] http://www.ardentcollaborations.com

241

Page 242: Core Java Ppt

Primitive Type Wrapper

Boolean -Methods

[email protected] http://www.ardentcollaborations.com

242

Method Description

boolean booleanValue( ) Returns boolean equivalent.

boolean equals(Object boolObj) Returns true if the invoking object is equivalent to boolObj. Otherwise, it returns false.

static booleangetBoolean(String propertyName)

Returns true if the system property specifiedby propertyName is true. Otherwise, it returnsFalse.

int hashCode( ) Returns the hash code for the invoking object.

static boolean parseBoolean(String str) Returns true if str contains the string “true”.Case is not significant. Otherwise ,returns false.

Page 243: Core Java Ppt

Primitive Type Wrapper

Boolean -Methods

Void The Void class has one field, TYPE, which holds a reference to

the Class object for type void. You do not create instances of this class.

[email protected] http://www.ardentcollaborations.com

243

Method Description

String toString( ) Returns the string equivalent of the invokingobject.

static String toString(boolean boolVal)

Returns the string equivalent of boolVal.

static Boolean valueOf(boolean boolVal)

Returns the Boolean equivalent of boolVal.

static Boolean valueOf(String boolString)

Returns true if boolString contains the string“true” (in uppercase or lowercase).Otherwise, it returns false.

Page 244: Core Java Ppt

Process -class

Abstract class encapsulates a process i.e a excuting program.

It is used primarily as a superclass for the type of objects created by exec( ) in the Runtime class

[email protected] http://www.ardentcollaborations.com

244

Page 245: Core Java Ppt

Process -class

Method Description

void destroy( ) Terminates the process.

int exitValue( ) Returns an exit code obtained from a subprocess.

InputStream getErrorStream( ) Returns an input stream that reads input from the process’ err output stream.

InputStream getInputStream( ) Returns an input stream that reads input from the process’ out output stream.

OutputStream getOutputStream( )

Returns an output stream that writes output to the process’ in input stream.

int waitFor( )throws InterruptedException

Returns the exit code returned by the process. This method does not return until the process on which it is called terminates.

[email protected] http://www.ardentcollaborations.com

245

Page 246: Core Java Ppt

Runtime -class

The Runtime class encapsulates the run-time environment. We cannot instantiate a Runtime object. However, we can get a reference to the current Runtime object by calling the static method Runtime.getRuntime( ).

With this reference we can call several methods that control the state and behavior of the Java Virtual Machine.adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

246

Page 247: Core Java Ppt

Runtime -class

Method Description

void addShutdownHook(Thread thrd)

Registers thrd as a thread to be run whenthe Java virtual machine terminates.

Process exec(String progName) throws IOException

Executes the program specified byprogName as a separate process. An objectof type Process is returned that describesthe new process.

Process exec(String progName,String environment[ ])throws IOException

Executes the program specified byprogName as a separate process with theenvironment specified by environment. Anobject of type Process is returned thatdescribes the new process.

[email protected] http://www.ardentcollaborations.com

247

Page 248: Core Java Ppt

Runtime -class

Method Description

Process exec(String comLineArray[ ])throws IOException

Executes the command line specified bythe strings in comLineArray as a separateprocess. An object of type Process isreturned that describes the new process.

Process exec(String comLineArray[ ],String environment[ ])throws IOException

Executes the command line specified bythe strings in comLineArray as a separateprocess with the environment specified byenvironment. An object of type Process isreturned that describes the new process.

void exit(int exitCode) Halts execution and returns the value ofexitCode to the parent process. Byconvention, 0 indicates normaltermination. All other values indicatesome form of error.

[email protected] http://www.ardentcollaborations.com

248

Page 249: Core Java Ppt

Runtime -class

Method Description

long freeMemory( ) Returns the approximate number of bytesof free memory available to the Javarun-time system.

void gc( ) Initiates garbage collection.

static Runtime getRuntime( ) Returns the current Runtime object.

void halt(int code) Immediately terminates the Java virtualmachine. No termination threads orfinalizers are run. The value of code isreturned to the invoking process.

void load(String libraryFileName) Loads the dynamic library whose file isspecified by libraryFileName, which mustspecify its complete path.

[email protected] http://www.ardentcollaborations.com

249

Page 250: Core Java Ppt

Runtime -class

Method Description

void loadLibrary(String libraryName)

Loads the dynamic library whose name isassociated with libraryName.

boolean removeShutdownHook(Thread thrd)

Removes thrd from the list of threadsto run when the Java virtual machineterminates. It returns true ifsuccessful that is, if the thread wasremoved.

void runFinalization( ) Initiates calls to the finalize( ) methods ofunused but not yet recycled objects.

long totalMemory( ) Returns the total number of bytes ofmemory available to the program.

[email protected] http://www.ardentcollaborations.com

250

Page 251: Core Java Ppt

Runtime -class

Method Description

void traceInstructions(boolean traceOn)

Turns on or off instruction tracing,depending upon the value of traceOn. IftraceOn is true, the trace is displayed. If itis false, tracing is turned off.

void traceMethodCalls(boolean traceOn)

Turns on or off method call tracing,depending upon the value of traceOn. IftraceOn is true, the trace is displayed. If itis false, tracing is turned off.adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

251

Page 252: Core Java Ppt

Memory Management

Java has the feature of automatic garbage collection , then

also sometimes we need to know how large the object heap

is and how much of it is left.

Sometimes we also need to run garbage collection on

Demand to free up the [email protected] http://www.ardentcollaborations.com

252

Page 253: Core Java Ppt

Memory Management

Showing memory operations using Runtime class..using totalMemory(),freeMemory() and gc()

class MemoryDemo {

public static void main(String args[]) {

Runtime r = Runtime.getRuntime();

long mem1, mem2;

Integer someints[] = new Integer[1000];

System.out.println("Total memory is: " +r.totalMemory());

mem1 = r.freeMemory();

System.out.println("Initial free memory: " + mem1);

r.gc();

mem1 = r.freeMemory();

System.out.println("Free memory after garbage collection: “+ mem1);

[email protected] http://www.ardentcollaborations.com

253

Page 254: Core Java Ppt

Memory Management

Showing memory operations using Runtime class..using totalMemory(),freeMemory() and gc()

for(int i=0; i<1000; i++)

someints[i] = new Integer(i); // allocate integers

mem2 = r.freeMemory();

System.out.println("Free memory after allocation: “+ mem2);

System.out.println("Memory used by allocation: “+ (mem1-mem2));

for(int i=0; i<1000; i++) someints[i] = null;

r.gc();

mem2 = r.freeMemory();

System.out.println("Free memory after collecting" +" discarded Integers: "+ mem2);

}

}[email protected] http://www.ardentcollaborations.com

254

Total memory is: 1048568Initial free memory: 751392Free memory after garbage collection: 841424Free memory after allocation: 824000Memory used by allocation: 17424Free memory after collecting discarded Integers: 842640

Page 255: Core Java Ppt

Executing Other Programs

In safe environments, you can use Java to execute other heavyweight processes (that is,programs) on your multitasking operating system. Several forms of the exec( ) method allow you to name the program you want to run as well as its input parameters. The exec( ) method returns a Process object, which can then be used to control how your Java program interacts with this new running process. Because Java can run on a variety of platforms and under a variety of operating systems, exec( ) is inherently environment-dependent.

[email protected] http://www.ardentcollaborations.com

255

Page 256: Core Java Ppt

Executing Other Programs

exec( ) to launch notepad

class ExecDemo {

public static void main(String args[]) {

Runtime r = Runtime.getRuntime();

Process p = null;

try {

p = r.exec("notepad");

} catch (Exception e) {

System.out.println("Error executing notepad.");

}

}

}[email protected] http://www.ardentcollaborations.com

256

Page 257: Core Java Ppt

Executing Other Programs

The Process object returned by exec( ) can be manipulated by Process’ methods after the new program starts running. You can kill the subprocess with the destroy( ) method. The waitFor( ) method causes your program to wait until the subprocess finishes. The exitValue( ) method returns the value returned by the subprocess when it is finished.

[email protected] http://www.ardentcollaborations.com

257

Page 258: Core Java Ppt

Executing Other Programs

class ExecDemoFini {

public static void main(String args[]) {

Runtime r = Runtime.getRuntime();

Process p = null;

try {

p = r.exec("notepad");

p.waitFor();

} catch (Exception e) {

System.out.println("Error executing notepad.");

}

System.out.println("Notepad returned " + p.exitValue());

}

}[email protected] http://www.ardentcollaborations.com

258

Page 259: Core Java Ppt

System

The System class holds a collection of static methods and variables. The standard input,output, and error output of the Java run time are stored in the in, out, and err variables.

[email protected] http://www.ardentcollaborations.com

259

Page 260: Core Java Ppt

System

Method Description

static void arraycopy(Object source,int sourceStart,Object target,int targetStart,int size)

Copies an array. The array to be copied is passed in source, and the index at which pointthe copy will begin within source is passed in sourceStart. The array that will receive thecopy is passed in target, and the index at which point the copy will begin within targetis passed in targetStart. size is the number of elements that are copied.

static long currentTimeMillis( ) Returns the current time in terms of milliseconds since midnight, January 1, 1970.

static void exit(int exitCode) Halts execution and returns the value of exitCode to the parent process (usually theoperating system). By convention, 0 indicates normal termination. All other valuesindicate some form of error.

[email protected] http://www.ardentcollaborations.com

260

Page 261: Core Java Ppt

currentTimeMillis( )

class Elapsed { public static void main(String args[]) { long start, end; System.out.println("Timing a for loop from 0 to 1,000,000"); // time a for loop from 0 to 1,000,000 start = System.currentTimeMillis(); // get starting time for(int i=0; i < 1000000; i++) ; end = System.currentTimeMillis(); // get ending time System.out.println("Elapsed time: " + (end-start)); } }[email protected] http://www.ardentcollaborations.com

261

Timing a for loop from 0 to 1,000,000Elapsed time: 10

Page 262: Core Java Ppt

arraycopy( ) class ACDemo { static byte a[] = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 }; static byte b[] = { 77, 77, 77, 77, 77, 77, 77, 77, 77, 77 }; public static void main(String args[]) { System.out.println("a = " + new String(a)); System.out.println("b = " + new String(b)); System.arraycopy(a, 0, b, 0, a.length); System.out.println("a = " + new String(a)); System.out.println("b = " + new String(b)); System.arraycopy(a, 0, a, 1, a.length - 1); System.arraycopy(b, 1, b, 0, b.length - 1); System.out.println("a = " + new String(a)); System.out.println("b = " + new String(b)); } }

[email protected] http://www.ardentcollaborations.com

262

a = ABCDEFGHIJb = MMMMMMMMMMa = ABCDEFGHIJb = ABCDEFGHIJa = AABCDEFGHIb = BCDEFGHIJJ

Page 263: Core Java Ppt

Class-class

Class encapsulates the run-time state of an object or interface. Objects of type Class are created automatically, when classes are loaded. You cannot explicitly declare a Class object. Generally, you obtain a Class object by calling the getClass( ) method defined by Object.

[email protected] http://www.ardentcollaborations.com

263

Page 264: Core Java Ppt

Class-class

Impotant methods forName() getClass() boolean isInterface( ) String getName( )

[email protected] http://www.ardentcollaborations.com

264

Page 265: Core Java Ppt

Class-class

class X { int a; float b; } class Y extends X { double c; } class RTTI { public static void main(String args[]) { X x = new X(); Y y = new Y();[email protected] http://www.ardentcollaborations.com

265

Page 266: Core Java Ppt

Class-class

Class clObj; clObj = x.getClass(); // get Class reference System.out.println("x is object of type: " + clObj.getName()); clObj = y.getClass(); // get Class reference System.out.println("y is object of type: " + clObj.getName()); clObj = clObj.getSuperclass(); System.out.println("y's superclass is " + clObj.getName()); } }[email protected] http://www.ardentcollaborations.com

266

Page 267: Core Java Ppt

java.util package(part-1) - Collection

267

[email protected] http://www.ardentcollaborations.com

ByAdrish BhattacharyayArdent Collaborations

Page 268: Core Java Ppt

Collection Framework

The Collections Framework provides a well-designed set of interfaces and classes for

storing and manipulating groups of data as a single unit, a collection. The framework

provides a convenient API to many of the abstract data types familiar from computer

science data structure curriculum: maps, sets, lists, trees,arrays, hashtables, and other

collections. Because of their object-oriented design, the Java classes in the Collections

Framework encapsulate both the data structures and the algorithms associated with

these abstractions. The framework provides a standard programming interface to many

of the most common abstractions, without burdening the programmer with too many

procedures and interfaces.

[email protected] http://www.ardentcollaborations.com

268

Page 269: Core Java Ppt

[email protected] http://www.ardentcollaborations.com

269

19-269

Overview Framework (in software): a general

system of components and architectural solutions that provides development tools to programmers for use with a relatively wide range of applications.

Collection: any collection of elements

Page 270: Core Java Ppt

[email protected] http://www.ardentcollaborations.com

270

19-270

Overview (cont’d) Collection, Iterator Lists, ListIterator

List ArrayList LinkedList

Stack Queue, PriorityQueue

Sets Set TreeSet HashSet

Maps Map TreeMap HashMap

All these interfaces and classes are part of the java.util package. Names of interfaces are in italics.

Page 271: Core Java Ppt

[email protected] http://www.ardentcollaborations.com

271

«interface» Collection

«interface» Iterator

«interface» Comparable

«interface» Comparator

«interface» Queue

«interface» Map

Stack PriorityQueue

HashMap TreeMap

LinkedList ArrayList TreeSet HashSet

«interface» List

«interface» Set

«interface» ListIterator

Collection Set

TreeSet HashSet

List

ArrayList LinkedList

TreeSet TreeMap

PriorityQueue

Overview

Page 272: Core Java Ppt

[email protected] http://www.ardentcollaborations.com

272

Overview (cont’d) A collection holds references to objects

(but we say informally that it “holds objects”).

A collection can contain references to two equal objects (a.equals (b)) as well as two references to the same object (a == b).

An object can belong to several collections.

An object can change while in a collection (unless it is immutable).

Page 273: Core Java Ppt

[email protected] http://www.ardentcollaborations.com

273

19-273

Collection, Iterator

Collection interface represents any collection.

An iterator is an object that helps to traverse the collection (process all its elements in sequence).

A collection supplies its own iterator(s), (returned by collection’s iterator method); the traversal sequence depends on the collection.

«interface»Collection

«interface»Iterator

Page 274: Core Java Ppt

[email protected] http://www.ardentcollaborations.com

274

19-274

Collection<E> Methods

boolean isEmpty ()

int size ()

boolean contains (Object obj)

boolean add (E obj)

boolean remove (E obj)

Iterator<E> iterator ()

// ... other methodsSupplies an iterator for this collection

«interface»Collection

«interface»Iterator

Page 275: Core Java Ppt

[email protected] http://www.ardentcollaborations.com

275

19-275

Iterator<E> Methods

boolean hasNext ()

E next ()

void remove ()

«interface»Collection

«interface»Iterator

What’s “next” is determined by a particular collection

Removes the last visited element

Page 276: Core Java Ppt

[email protected] http://www.ardentcollaborations.com

276

Iterator “For Each” Loop

Iterator<String> iter = words.iterator(); while (iter.hasNext ()) { String word = iter.next (); < ... process word > }

Collection<String> words = new ArrayList<String>(); ...

for (String word : words) { < ... process word > }

A “for each” loop is a syntactic shortcut that replaces an iterator

Page 277: Core Java Ppt

Format of Code

Collection collection = ...; Iterator iterator = collection.iterator(); while (iterator.hasNext()) { Object element = iterator.next(); if (removalCheck(element)) { iterator.remove(); } }[email protected] http://www.ardentcollaborations.com

277

Page 278: Core Java Ppt

278

Lists, ListIterator

A list represents a collection in which all elements are numbered by indices:

a0, a1, ..., an-1

java.util: List interface ArrayList LinkedList

ListIterator is an extended iterator, specific for lists (ListIterator is a subinterface of Iterator)

Page 279: Core Java Ppt

279

Lists (cont’d)

«interface»Collection

«interface»Iterator

«interface»ListIterator

ArrayList LinkedList

«interface»Set

«interface»List

etc.

Page 280: Core Java Ppt

280

List<E> Methods

«interface»Collection

«interface»Iterator

«interface»ListIterator

«interface»List

// All Collection<E> methods, plus:

E get (int i)

E set (int i, E obj)

void add (int i, E obj)

E remove (int i)

int indexOf (Object obj)

ListIterator<E> listIterator ()

ListIterator<E> listIterator (int i)Returns a ListIterator that starts iterations at index i

Page 281: Core Java Ppt

19

ListIterator<E> Methods «interface»

Collection«interface»

Iterator

«interface»ListIterator

«interface»List

// The three Iterator<E> methods, plus:

int nextIndex ()

boolean hasPrevious ()

E previous ()

int previousIndex ()

void add (E obj)

void set (E obj)

Can traverse the list backward

Can add elements to the list (inserts after the last visited element)

Can change elements (changes the last visited element)

Page 282: Core Java Ppt

Demo Code

List list = ...; ListIterator iterator =

list.listIterator(list.size()); while (iterator.hasPrevious()) { Object element =

iterator.previous(); // Process element }

[email protected] http://www.ardentcollaborations.com

282

Page 283: Core Java Ppt

19

ArrayList

Represents a list as a dynamic array (array that is resized when full)

Provides random access to the elements

Implements all the methods of List<E>

«interface»Iterator

«interface»ListIterator

«interface»List

ArrayList LinkedList

a1 a2 an-1...a0

Page 284: Core Java Ppt

284

java.util.ArrayList<E>

Implements a list using an array. Can only hold objects (of a specified

type), not elements of primitive data types.

Keeps track of the list capacity (the length of the allocated array) and list size (the number of elements currently in the list)

"Cat" "Hat" "Bat"

capacitysize

...

Page 285: Core Java Ppt

285

ArrayList Generics

Starting with Java 5, ArrayList and other collection classes hold objects of a specified data type.

The elements’ data type is shown in angle brackets and becomes part of the ArrayList type. For example:

ArrayList<String> words = new ArrayList<String>();

ArrayList<Integer> nums = new ArrayList<Integer>();

Page 286: Core Java Ppt

286

ArrayList<E> Constructors

ArrayList<E> ( )

ArrayList<E> (int capacity)

Creates an empty ArrayList<E> of default capacity (ten)

Java docs use the letter E as the type parameter for elements in generic collections

Creates an empty ArrayList<E> of the specified capacity

Page 287: Core Java Ppt

287

ArrayList<E> Methods (a Subset)

int size()

boolean isEmpty ()

boolean add (E obj)

void add (int i, E obj)

E set(int i, E obj)

E get(int i)

E remove(int i)

boolean contains(E obj)

int indexOf(E obj)use equals to compare objects

i must be from 0 to size() -1

inserts obj as the i-th value; i must be from 0 to size()

returns true

Page 288: Core Java Ppt

288

ArrayList Example

ArrayList<String> names = new ArrayList<String>( ); names.add("Ben"); names.add("Cat"); names.add(0, "Amy"); System.out.println(names);

[Amy, Ben, Cat]

OutputArrayList’s toString method returns a string of all the elements, separated by commas, within [ ].

Page 289: Core Java Ppt

289

ArrayList<E> Details

Automatically increases (doubles) the capacity when the list runs out of space (allocates a bigger array and copies all the values into it).

get(i) and set(i, obj) are efficient because an array provides random access to its elements.

Throws IndexOutOfBoundsException wheni < 0 or i size()

(or i > size() in add (i, obj) )

Page 290: Core Java Ppt

290

LinkedList

Represents a list as a doubly-linked list with a header node

Implements all the methods of List<E>

a0 a1 a2 an-1...

«interface»Iterator

«interface»ListIterator

«interface»List

ArrayList LinkedList

header

Page 291: Core Java Ppt

291

LinkedList (cont’d)

Additional methods specific to LinkedList:

«interface»Iterator

«interface»ListIterator

«interface»List

ArrayList LinkedList

void addFirst (E obj)

void addLast (E obj)

E getFirst ()

E getLast ()

E removeFirst ()

E removeLast ()

Page 292: Core Java Ppt

292

Singly-Linked List

Each node holds a reference to the next node

In the last node, next is null A linked list is defined by a reference to

its first node (often named head or front)

value 0 value 1 value 2

value ... value n-1

head

Page 293: Core Java Ppt

293

Singly-Linked List (cont’d)

public class ListNode{ private Object value; private ListNode next;

public ListNode (Object v, ListNode nx) { value = v; next = nx; }

public Object getValue ( ) { return value; } public ListNode getNext ( ) { return next; } public void setValue (Object v) { value = v; } public void setNext (ListNode nx) { next = nx; }}

A reference to the next node

Represents a node of a singly-linked list

Page 294: Core Java Ppt

294

Singly-Linked List — Example 1

Append x at the head of a linked list and return the head of the new list.

public ListNode append (ListNode head, Object x) { return new ListNode (value, head); }

value 0 value 1 value 2

value ... value n-1

x

head

Page 295: Core Java Ppt

295

Singly-Linked List — Example 2

Assuming the list has at least two nodes, remove the last node.

public void removeLast (ListNode head) { ListNode node = head; while (node.getNext ().getNext () != null) node = node.getNext ( ); node.setNext (null); }

null

nullA B C D

node

head

Page 296: Core Java Ppt

296

Singly-Linked List — Traversal

public void printList (ListNode head) { for (ListNode node = head; node != null; node = node.getNext ()) System.out.println (node.getValue ()); }

Page 297: Core Java Ppt

297

Singly-Linked List with a Tail

Keeps a reference to the last node Suitable for implementing a queue

value 0 value 1 value 2

value ... value n-1

head tail

Page 298: Core Java Ppt

298

Doubly-Linked List

Each node has references to the next and previous nodes

In the last node, next is null; in the first node, previous is null.

Can be traversed backward

a0 a1 a2 an-1...

head tail

Page 299: Core Java Ppt

299

Doubly-Linked Circular List

next in the last node points to the first node

previous in the first node points to the last node

a0 a1 a2 an-1...

head

Page 300: Core Java Ppt

300

Doubly-Linked Circular List with a Header Node

That’s how java.util.LinkedList is implemented

a0 a1 a2 an-1...

private ListNode2 header;

a field in the DoublyLinkedList class

Page 301: Core Java Ppt

ArrayList vs. LinkedList

Implements a list as an array

+ Provides random access to the elements

- Inserting and removing elements

requires shifting of subsequent elements

- Needs to be resized when runs out of space

301 Implements a list as a

doubly-linked list with a header node

- No random access to the elements — needs to traverse the list to get to thei-th element

+ Inserting and removing elements is done by rearranging the links — no shifting

+ Nodes are allocated and released as necessary

Page 302: Core Java Ppt

ArrayList vs. LinkedList (cont’d)

302

Works well for an ArrayList O(n)inefficient for a LinkedList O(n2)

for (int i = 0; i < list.size(); i++) { Object x = list.get (i); ... }

Iterator iter = list.iterator ( ); while (iter.hasNext ( )) { Object x = iter.next ( ); ... }

for (Object x : list) { ... }

Work well for both an ArrayList and a LinkedList O(n)

Page 303: Core Java Ppt

List Example

import java.util.*; public class ListExample { public static void main(String args[]) { List list = new ArrayList(); list.add("Bernadine"); list.add("Elizabeth"); list.add("Gene"); list.add("Elizabeth"); list.add("Clara"); System.out.println(list); System.out.println("2: " + list.get(2));

[email protected] http://www.ardentcollaborations.com

303

Page 304: Core Java Ppt

List Example System.out.println("0: " + list.get(0)); LinkedList queue = new LinkedList(); queue.addFirst("Bernadine"); queue.addFirst("Elizabeth"); queue.addFirst("Gene"); queue.addFirst("Elizabeth"); queue.addFirst("Clara"); System.out.println(queue); queue.removeLast(); queue.removeLast(); System.out.println(queue); } }

[email protected] http://www.ardentcollaborations.com

304

Page 305: Core Java Ppt

Vector

The Vector<T> parameterized type defines a sequence collection of elements of any type T. A Vector<> object works rather like an array, but with the additional feature that it can grow itself automatically when you need more capacity. The Vector<> type implements the List<> interface, so you can also access the contents of containers of this type as a list.

constructorsVector<String> transactions = new Vector<String>();

Vector<String> transactions = new Vector<String>(100);

Vector<String> transactions = new Vector<String>(100,10);adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

305

Page 306: Core Java Ppt

Vector -Example import java.util.Vector; public class TrySimpleVector { public static void main(String[] args) { Vector<String> names = new Vector<String>(); String[] firstnames = { “Jack”, “Jill”, “John”,“Joan”, “Jeremiah”,

“Josephine”}; for(String firstname : firstnames) { names.add(firstname); } for(String name : names) { System.out.println(name); } } }adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

306

Page 307: Core Java Ppt

Vector

[email protected] http://www.ardentcollaborations.com

307java.util.Iterator<String> iter = names.iterator();while(iter.hasNext()) {System.out.println(iter.next());}for(int i = 0 ; i<names.size() ; i++) {

System.out.println(names.get(i));}

int namesMax = names.capacity(); // Get current capacitynames.ensureCapacity(150); // Set minimum capacity to 150int freeCount = names.capacity() – names.size();//counting free spaceString name = names.get(4);//retrieving from vector

Page 308: Core Java Ppt

308

Stacks

A stack provides temporary storage in the LIFO (Last-In-First-Out) manner.

Stacks are useful for dealing with nested structures and branching processes: pictures within pictures folders within folders methods calling other methods

Controlled by two operations: push and pop.

Implemented as java.util.Stack<E> class

Page 309: Core Java Ppt

309

Stack<E> Methods

boolean isEmpty ()

E push (E obj)

E pop ()

E peek ()

Stack

Returns obj; use as void

Returns the top element without removing it from the stack

Page 310: Core Java Ppt

310

Queues A queue provides temporary storage in

the FIFO (First-In-First-Out) manner Useful for dealing with events that

have to be processed in order of their arrival

java.util: Queue interface LinkedList (implements Queue)

Page 311: Core Java Ppt

311

Queues (cont’d)

LinkedList

«interface»Queue

Page 312: Core Java Ppt

312

Queue<E> Methods

LinkedList

«interface»Queue

boolean isEmpty ()

boolean add (E obj)

E remove ()

E peek () Returns the first element without removing it from the queue

Page 313: Core Java Ppt

313

Queues (cont’d)

Queue<Message> q = new LinkedList<Message> ();

Methods have been added to LinkedList to implement the Queue interface:

add == addLastremove == removeFirstpeek == getFirst

All of the above work in O(1) time

Page 314: Core Java Ppt

314

Priority Queues In a priority queue, items are

processed NOT in order of arrival, but in order of priority.

java.util: Queue interface PriorityQueue (implements Queue)

Page 315: Core Java Ppt

315

PriorityQueue

«interface»Queue

Priority Queues (cont’d)

The same methods as in Queue: isEmpty, add, remove, peek.

Page 316: Core Java Ppt

316

PriorityQueue<E> Class

Works with Comparable objects (or takes a comparator as a parameter).

The smallest item has the highest priority.

Implements a priority queue as a min-heap

PriorityQueue

«interface»Queue

Page 317: Core Java Ppt

317

push

pop

Stack Queue

LIFO (Last-In-First-Out) access method

add

remove

FIFO (First-In-First-Out) access method

Stacks and queues are used for temporary storage, but in different situations

Page 318: Core Java Ppt

318

Stacks are Used for

handling nested structures: processing directories within directories evaluating expressions within expressions

handling branching processes: traversing a branching tree structure planning a move in a chess game tracking the sequence of method calls in a

Java program

Page 319: Core Java Ppt

319

Stack: Array Implementation

Stack pointer

sp

myElements[5]

myElements[4]

myElements[3] value3

myElements[2] value2

myElements[1] value1 myElements[0] value0

public void push (Object x) { myElements [sp] = x; sp++; }

public Object pop ( ) { sp--; return myElements [sp]; }

Page 320: Core Java Ppt

320

ArrayList Implementation

import java.util.ArrayList;

public class ArrayStack { private ArrayList<Object> items;

public ArrayStack () { items = new ArrayList<Object>(); } public boolean isEmpty () { return items.isEmpty (); } public void push (Object x) { items.add (x); } public Object pop () { return items.remove (items.size () - 1); } public Object peek ( ) { return items.get (items.size () - 1); } }

Page 321: Core Java Ppt

321

LinkedList Implementation

import java.util.LinkedList;

public class ListStack { private LinkedList<Object> items;

public ListStack () { items = new LinkedList<Object> (); } public boolean isEmpty () { return items.isEmpty (); }

public void push (Object x) { items.addFirst (x); }

public Object pop () { return items.removeFirst (); }

public Object peek () { return items.getFirst (); } }

Page 322: Core Java Ppt

322

Properties of Stacks

In an efficient implementation, push, pop, and peek methods run in O(1) time.

A stack of objects holds references to objects.

If necessary, a stack can hold multiple references to the same object.

If you are not careful, an object can change while stored on the stack (unless that object is immutable).

Page 323: Core Java Ppt

323

java.util.Stack class

Part of the Java Collections Framework.

A “generic” class (works with objects of specified type).

Based on the legacy Vector class, similar to ArrayList.

Methods: isEmpty, push, pop, peek. Has other methods do not use

them!

Page 324: Core Java Ppt

324

Stack Example: Matching Brackets

public boolean bracketsMatch (String str) { Stack<Integer> stk = new Stack<Integer> (); for (int pos = 0; pos < str.length(); pos++) { if (str.charAt (pos) == ' [ ' ) ) stk.push (pos); else if (str.charAt (pos) == ' ] ' )) { if (stk.isEmpty ()) return false; int pos0 = stk.pop (); System.out.println (pos0 + " - " + pos); } } return stk.isEmpty (); }

Autounboxing

Autoboxing(Save pos of ' [ ‘)

import java.util.Stack;

Page 325: Core Java Ppt

325

Stack Example:Traversing a Tree Stack stk = new Stack<TreeNode>(); TreeNode node = root; while (node != null) { System.out.println (node.getValue ()) ; if (node.getLeft () != null ) { if (node.getRight () != null ) stk.push (node.getRight ()); node = node.getLeft (); } else if (node.getRight () != null ) node = node.getRight (); else if (! stk.isEmpty ()) node = stk.pop (); else node = null; }

Save for future processing

if no children, take the next node from the stack

Page 326: Core Java Ppt

326

Queues are used for:

Processing events or messages in order of their arrival

System tasks Queueing print jobs Entering keystrokes Processing mouse clicks

Page 327: Core Java Ppt

327

Queue: Ring-Buffer Implementation

front rear

1 1 2 3 5 8 13

rear front

Before:

After: (removed 1, 1; inserted 21, 34, 55)

2 3 5 8 13 21 34 55

Page 328: Core Java Ppt

328

Properties of Queues

In an efficient implementation, add, remove, and peek methods run in O(1) time.

A queue of objects holds references to objects.

If necessary, a queue can hold multiple references to the same object.

If you are not careful, an object can change while stored in the queue (unless that object is immutable).

Page 329: Core Java Ppt

329

The java.util.Queue Interface

A “generic” interface, part of the Java Collections Framework

Implemented by java.util.LinkedList

boolean isEmpty ()

boolean add (E obj)

E remove ()

E peek ()

Page 330: Core Java Ppt

330

Queue Example

public Queue<String> findMatches (Scanner input, String target) { Queue<String> q = new LinkedList<String>(); while (input.hasNextLine ()) { String line = input.nextLine (); if (line.indexOf (target) >= 0 ) q.add (line); } return q; }

Returns a queue of all the lines that contain target

public void process (Queue<String> q) { while (! q.isEmpty ()) { String s = q.remove (); ... // process s } }

Processes the contents of q (leaves the queue empty)

Page 331: Core Java Ppt

331

Sets

A set is a collection without duplicate values

What is a “duplicate” depends on the implementation

Designed for finding a value quickly java.util:

Set interface TreeSet HashSet

Page 332: Core Java Ppt

332

Sets (cont’d)

«interface»Collection

«interface»Iterator

TreeSet HashSet

«interface»Set

Methods of Set<E> are the same as methods of Collection<E>

Set’s semantics are different from Collection (no duplicates), but Set does not add any new methods.

Page 333: Core Java Ppt

333

TreeSet<E>

Works with Comparable objects (or takes a comparator as a parameter)

Implements a set as a Binary Search Tree

contains, add, and remove methods run in O(log n) time

Iterator returns elements in ascending order

TreeSet HashSet

«interface»Set

Page 334: Core Java Ppt

334

HashSet<E>

Works with objects for which reasonable hashCode and equals methods are defined

Implements a set as a hash table contains, add, and remove methods run

in O(1) time Iterator returns elements in no

particular order

TreeSet HashSet

«interface»Set

Page 335: Core Java Ppt

Example1 import java.util.*; public class SetExample { public static void main(String args[]) { Set set = new HashSet(); set.add("Bernadine"); set.add("Elizabeth"); set.add("Gene"); set.add("Elizabeth"); set.add("Clara"); System.out.println(set); Set sortedSet = new TreeSet(set); System.out.println(sortedSet); } }

[email protected] http://www.ardentcollaborations.com

335

Page 336: Core Java Ppt

Example 2<with Generics>

import java.util.*;

public class SetExample {

public static void main(String args[]) {

Set<String> set = new HashSet<String>();

set.add("Bernadine");

set.add("Elizabeth");

set.add("Gene");

set.add("Elizabeth");

set.add("Clara");

Integer a = 10;

[email protected] http://www.ardentcollaborations.com

336

Page 337: Core Java Ppt

Example 2<with Generics>

System.out.println(set);

Set<String> sortedSet = new TreeSet<String>(set);

System.out.println(sortedSet);

for(String temp: sortedSet)

System.out.println(temp);

Iterator it = sortedSet.iterator();

while(it.hasNext()){

System.out.println(it.next());

}

}

}[email protected] http://www.ardentcollaborations.com

337

NOTICE : Unlike Set, List permits duplicates.

Page 338: Core Java Ppt

338

Maps

A map is not a collection; it represents a correspondence between a set of keys and a set of values

Only one value can correspond to a given key; several keys can be mapped onto the same value

keys values

Page 339: Core Java Ppt

339

Maps (cont’d)

java.util: Map interface TreeMap HashMap

TreeMap HashMap

«interface»Map

Page 340: Core Java Ppt

340

Map<K, V> Methods

TreeMap HashMap

«interface»Map

boolean isEmpty ()

int size ()

V get (K key)

V put (K key, V value)

V remove (K key)

boolean containsKey (Object key)

Set<K> keySet () Returns the set of all keys

Page 341: Core Java Ppt

341

TreeMap<K,V>

Works with Comparable keys (or takes a comparator as a parameter)

Implements the key set as a Binary Search Tree

containsKey, get, and put methods run in O(log n) time

TreeMap HashSet

«interface»Map

Page 342: Core Java Ppt

342

HashMap<K,V>

Works with keys for which reasonable hashCode and equals methods are defined

Implements the key set as a hash table

containsKey, get, and put methods run in O(1) time

TreeMap HashMap

«interface»Map

Page 343: Core Java Ppt

Miscellaneous Example1

ArrayList import java.util.*; public class ArrayListSample { public static void main( String [] args ) { ArrayList al = new ArrayList(); al.add("String"); al.add(1, "String"); al.add( new Long(5) ); String s = (String) al.get(1);adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

343

Page 344: Core Java Ppt

Miscellaneous Example1

ArrayList Long l = (Long) al.get(2); System.out.println( "s = "+s ); System.out.println( "l =

"+l.intValue() ); } }

[email protected] http://www.ardentcollaborations.com

344

s = Stringl = 5

Page 345: Core Java Ppt

Miscellaneous Example2

LinkedList import java.util.*; public class LinkedListSample { public static void main( String [] args ) { LinkedList ll = new LinkedList(); ll.add("middle"); ll.add( 1, new Long(7)); ll.addFirst("First Element"); ll.addLast("Last element");adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

345

Page 346: Core Java Ppt

Miscellaneous Example2

LinkedList String first = (String)ll.getFirst(); String last = (String)ll.getLast(); System.out.println( "First:"+ first ); System.out.println( "Last :"+ last ); } }

[email protected] http://www.ardentcollaborations.com

346

First: First ElementLast: Last Element

Page 347: Core Java Ppt

Miscellaneous Example3

HashSet

import java.util.*; public class HashSetSample { public static void main( String [] args ) { HashSet hs = new HashSet(); hs.add("B"); hs.add("A"); hs.add("A"); hs.add( new Long(7) ); System.out.println( "hs:"+ hs ); } }adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

347

hs: [A, 7, B]

Page 348: Core Java Ppt

Miscellaneous Example4

TreeSet

import java.util.*; public class TreeSetSample { public static void main( String [] args ) { TreeSet ts = new TreeSet(); ts.add("C"); ts.add("B"); ts.add("A"); //ts.add( new Long(7) ); System.out.println( "ts:"+ ts ); } }

[email protected] http://www.ardentcollaborations.com

348

ts: [A, B, C]

Page 349: Core Java Ppt

Miscellaneous Example5

Iterator

import java.util.*; public class IteratorSample { public static void main( String [] args ) { TreeSet ts = new TreeSet(); ts.add(new Long(7)); ts.add(new Long(5)); ts.add(new Long(3)); Iterator i = ts.iterator();

[email protected] http://www.ardentcollaborations.com

349

Page 350: Core Java Ppt

Miscellaneous Example5

Iterator while ( i.hasNext() ) { System.out.println( "Item: "+i.next() ); } } }

[email protected] http://www.ardentcollaborations.com

350

Item: 3Item: 5Item: 7

Page 351: Core Java Ppt

Miscellaneous Example6

ListIterator import java.util.*; public class ListIteratorSample { public static void main( String [] args ){ LinkedList ll = new LinkedList(); ll.add(new Long(7)); ll.add(new Long(5)); ll.add(new Long(3)); ListIterator li = ll.listIterator(); while ( li.hasNext() ) {

[email protected] http://www.ardentcollaborations.com

351

Page 352: Core Java Ppt

Miscellaneous Example6

ListIterator System.out.print( li.next() ); if ( li.hasNext() ) System.out.print(", "); } System.out.println(""); while ( li.hasPrevious() ) { System.out.print( li.previous() ); if ( li.hasPrevious() ) System.out.print(", "); } } }

[email protected] http://www.ardentcollaborations.com

352

7 5 33 5 7

Page 353: Core Java Ppt

Miscellaneous Example7

HashMap import java.util.*; public class HashMapSample { public static void main( String [] args ) { HashMap hm = new HashMap(); hm.put("Key", new Long(2)); hm.put(new Long(5), "Value" ); Set s = hm.entrySet(); Iterator i = s.iterator();adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

353

Page 354: Core Java Ppt

Miscellaneous Example7

HashMap while ( i.hasNext() ) { Map.Entry me = (Map.Entry)i.next(); System.out.print("KEY:

"+me.getKey()); System.out.println(",VAL:

"+me.getValue()); } } }

[email protected] http://www.ardentcollaborations.com

354

KEY: Key, VAL: 2KEY: 5, VAL: Value

Page 355: Core Java Ppt

Miscellaneous Example8

TreeMap import java.util.*; public class TreeMapSample { public static void main( String [] args ) { TreeMap tm = new TreeMap(); tm.put("CKEY", "Just A String"); tm.put("BKEY", new Long(2)); tm.put("AKEY", new Long(1)); Set s = tm.entrySet();adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

355

Page 356: Core Java Ppt

Miscellaneous Example8

TreeMap Iterator i = s.iterator(); while ( i.hasNext() ) { Map.Entry m = (Map.Entry)i.next(); System.out.print("KEY: "+m.getKey()); System.out.println(",VAL:"+m.getValu

e()); } } }adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

356

KEY: AKEY, VALUE: 1KEY: BKEY, VALUE: 2KEY: CKEY, VALUE: Just a String

Page 357: Core Java Ppt

Miscellaneous Example9

Comparator

import java.util.*; class MyComparator implements

Comparator { public int compare( Object a, Object b ) { long la = ((Long)a).longValue(); long lb = ((Long)b).longValue(); long ra = la % 2; long rb = lb % 2;

[email protected] http://www.ardentcollaborations.com

357

Page 358: Core Java Ppt

Miscellaneous Example9

Comparator

if ( ( ra == 0 && rb == 1 ) || la < lb ) return -1; else if ( ( rb == 0 && ra == 1 ) || la >

lb ) return 1; return 1; } }

[email protected] http://www.ardentcollaborations.com

358

Page 359: Core Java Ppt

Miscellaneous Example9

Comparator

import java.util.*; public class UseComparator { public static void main( String [] args ) { TreeSet ts = new TreeSet( new

MyComparator() ); ts.add( new Long(1) ); ts.add( new Long(6) ); ts.add( new Long(5) );adrish.b@ardentcollaborations.

com http://www.ardentcollaborations.com

359

Page 360: Core Java Ppt

Miscellaneous Example9

Comparator

ts.add( new Long(10) ); Iterator i = ts.iterator(); while ( i.hasNext() ) { System.out.print(i.next()); if (i.hasNext()) System.out.print(", "); } } }

[email protected] http://www.ardentcollaborations.com

360

6, 10, 1, 5

Page 361: Core Java Ppt

Miscellaneous Example10

Vector import java.util.*;

class vector {

public static void main(String args[]) {

Vector vector = new Vector(5);

System.out.println("Capacity: " + vector.capacity());

vector.addElement(new Integer(0));

vector.addElement(new Integer(1));

vector.addElement(new Integer(2));

vector.addElement(new Integer(3));

vector.addElement(new Integer(4));

vector.addElement(new Integer(5));[email protected] http://www.ardentcollaborations.com

361

Page 362: Core Java Ppt

Miscellaneous Example10

Vector

vector.addElement(new Integer(6));

vector.addElement(new Double(3.14159));

vector.addElement(new Float(3.14159));

System.out.println("Capacity: " + vector.capacity());

System.out.println("Size: " + vector.size());

System.out.println("First item: " + (Integer) vector.firstElement());

System.out.println("Last item: " + (Float) vector.lastElement());

if(vector.contains(new Integer(3)))

System.out.println("Found a 3.");

}

}

[email protected] http://www.ardentcollaborations.com

362

Page 363: Core Java Ppt

java.util package(part-2)-Utility Classes

363

[email protected] http://www.ardentcollaborations.com

ByAdrish BhattacharyayArdent Collaborations

Page 364: Core Java Ppt

StringTokenizer

The processing of text often consists of parsing a formatted input string. Parsing is the division of text into a set of discrete parts, or tokens, which in a certain sequence can convey a semantic meaning. The StringTokenizer class provides the first step in this parsing process, often called the lexer (lexical analyzer). StringTokenizer implements the Enumeration interface.So you can enumerate the individual tokens contained in it using StringTokenizer.

[email protected] http://www.ardentcollaborations.com

364

Page 365: Core Java Ppt

StringTokenizer Constructors StringTokenizer(String str) StringTokenizer(String str, String

delimiters) StringTokenizer(String str, String

delimiters, boolean delimAsToken)

[email protected] http://www.ardentcollaborations.com

365

Page 366: Core Java Ppt

StringTokenizer-methods

Method Description int countTokens( ) Using the current set of delimiters, the

method determines the number of tokens left to be parsed and returns the result.

boolean hasMoreElements( ) Returns true if one or more tokens remain in the string and returns false if there are none.

boolean hasMoreTokens( ) Returns true if one or more tokens remain in the string and returns false if there are none.

Object nextElement( ) Returns the next token as an Object. String nextToken( ) Returns the next token as a String. String nextToken(String delimiters) Returns the next token as a String and

sets the delimiters string to that specified

by delimiters.

[email protected] http://www.ardentcollaborations.com

366

Page 367: Core Java Ppt

StringTokenizer

Program demostrating StringTokenizer methods

import java.util.StringTokenizer;

class STDemo {

static String in = "name=Adrish Bhattacharyay;" +

"address=Chandannagar;" +

"[email protected];" +

"Qualification=B.Tech";

public static void main(String args[]) {

StringTokenizer st = new StringTokenizer(in, "=;");

while(st.hasMoreTokens()) {

String key = st.nextToken();

String val = st.nextToken();

System.out.println(key + "\t" + val);

}

}}[email protected] http://www.ardentcollaborations.com

367

name Adrish Bhattacharyayaddress Chandannagaremail [email protected] B.Tech

Page 368: Core Java Ppt

BitSet

A BitSet class creates a special type of array that holds bit values. This array can increase in size as needed. This makes it similar to a vector of bits.

The BitSet constructors are shown here:

BitSet( )

BitSet(int size)

[email protected] http://www.ardentcollaborations.com

368

Page 369: Core Java Ppt

BitSet methods

Method Description void and(BitSet bitSet) ANDs the contents of the invoking BitSet

object with those specified by bitSet. The result

is placed into the invoking object. void andNot(BitSet bitSet) For each 1 bit in bitSet, the

corresponding bit in

the invoking BitSet is cleared. int cardinality( ) Returns the number of set bits

in the invoking

object. void clear( ) Zeros all bits. void clear(int index) Zeros the bit specified by index. void clear(int startIndex,int endIndex) Zeros the bits from startIndex to

(endIndex– 1)[email protected] http://www.ardentcollaborations.com

369

Page 370: Core Java Ppt

BitSet methods

Method Description Object clone( ) Duplicates the invoking BitSet object. boolean equals(Object bitSet) Returns true if the invoking bit set is

equivalent to the one passed in bitSet.Otherwise, the method returns false.

boolean get(int index) Returns the current state of the bit at the

specified index. BitSet get(int startIndex,int endIndex) Returns a BitSet that consists

of the bits from startIndex to endIndex–1. The invoking object is not changed.

boolean intersects(BitSet bitSet) Returns true if at least one pair of corresponding bits within the invoking object and bitSet are 1.

[email protected] http://www.ardentcollaborations.com

370

Page 371: Core Java Ppt

BitSet methods Method Description int length( ) Returns the number of bits required to hold

the contents of the invoking BitSet. This value

is determined by the location of the last 1 bit. void or(BitSet bitSet) ORs the contents of the invoking BitSet object

with that specified by bitSet. The result is placed into the invoking object.

int size( ) Returns the number of bits in the invoking

BitSet object. String toString( ) Returns the string equivalent of the invoking

BitSet object. void xor(BitSet bitSet) XORs the contents of the invoking BitSet

object with that specified by bitSet. The result

is placed into the invoking object.

[email protected] http://www.ardentcollaborations.com

371

Page 372: Core Java Ppt

BitSet Example

import java.util.BitSet; class BitSetDemo { public static void main(String args[]) { BitSet bits1 = new BitSet(16); BitSet bits2 = new BitSet(16); // set some bits for(int i=0; i<16; i++) { if((i%2) == 0) bits1.set(i); if((i%5) != 0) bits2.set(i); }

[email protected] http://www.ardentcollaborations.com

372

Page 373: Core Java Ppt

BitSet Example

System.out.println("Initial pattern in bits1: "); System.out.println(bits1); System.out.println("\nInitial pattern in bits2: "); System.out.println(bits2); // AND bits bits2.and(bits1); System.out.println("\nbits2 AND bits1: "); System.out.println(bits2); // OR bits bits2.or(bits1); System.out.println("\nbits2 OR bits1: ");

[email protected] http://www.ardentcollaborations.com

373

Page 374: Core Java Ppt

BitSet Example

System.out.println(bits2); // XOR bits bits2.xor(bits1); System.out.println("\nbits2 XOR bits1: "); System.out.println(bits2); } }

[email protected] http://www.ardentcollaborations.com

374

Initial pattern in bits1:{0, 2, 4, 6, 8, 10, 12, 14}Initial pattern in bits2:{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}bits2 AND bits1:{2, 4, 6, 8, 12, 14}bits2 OR bits1:{0, 2, 4, 6, 8, 10, 12, 14}bits2 XOR bits1:{}

Page 375: Core Java Ppt

Date

import java.util.Date; class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date using toString() System.out.println(date); // Display number of milliseconds since

midnight, January 1, 1970 GMT

[email protected] http://www.ardentcollaborations.com

375

Page 376: Core Java Ppt

Date

long msec = date.getTime(); System.out.println("Milliseconds since Jan. 1,

1970 GMT = " + msec); } }

[email protected] http://www.ardentcollaborations.com

376

Page 377: Core Java Ppt

Calender

import java.util.Calendar; class CalendarDemo { public static void main(String args[]) { String months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; Calendar calendar = Calendar.getInstance(); System.out.print("Date: "); System.out.print(months[calendar.get(Calendar.MONT

H)]); System.out.print(" " + calendar.get(Calendar.DATE) +

" "); System.out.println(calendar.get(Calendar.YEAR));

[email protected] http://www.ardentcollaborations.com

377

Page 378: Core Java Ppt

Calender System.out.print("Time: "); System.out.print(calendar.get(Calendar.HOUR) + ":"); System.out.print(calendar.get(Calendar.MINUTE) + ":"); System.out.println(calendar.get(Calendar.SECOND)); calendar.set(Calendar.HOUR, 10); calendar.set(Calendar.MINUTE, 29); calendar.set(Calendar.SECOND, 22); System.out.print("Updated time: "); System.out.print(calendar.get(Calendar.HOUR) + ":"); System.out.print(calendar.get(Calendar.MINUTE) + ":"); System.out.println(calendar.get(Calendar.SECOND)); } }

[email protected] http://www.ardentcollaborations.com

378

Page 379: Core Java Ppt

379

[email protected] http://www.ardentcollaborations.com

ByAdrish BhattacharyayArdent Collaborations

java.io package

Page 380: Core Java Ppt

Introduction

The Java Input/Output (I/O) is a part of java.io package. The classes in the package

are primarily abstract classes and stream-oriented that define methods and subclasses which allow bytes to be read from and written to files or other input and output sources. The InputStream and OutputStream  are central classes in the package which are used for reading from and writing to byte streams, respectively.

Page 381: Core Java Ppt

Class hierarchy in java.io package

Page 382: Core Java Ppt

InputStream

The InputStream class is used for reading the data such as a byte and array of bytes from an input source. An input source can be a file, a string, or memory that may contain the data. It is an abstract class that defines the programming interface for all input streams that are inherited from it. An input stream is automatically opened when you create it. You cans explicitly close a stream with the close( ) method, or let it be closed implicitly when the object is found as a garbage.

Page 383: Core Java Ppt

InputStream sub-classes

InputStream is inherited from the Object class. Each class of the InputStreams provided by the java.io package is intended for a different purpose.

Page 384: Core Java Ppt

OutputStream

The OutputStream class is a sibling to InputStream that is used for writing byte and array of bytes to an output source. Similar to input sources, an output source can be anything such as a file, a string, or memory containing the data. Like an input stream, an output stream is automatically opened when you create it. You can explicitly close an output stream with the close( ) method, or let it be closed implicitly when the object is garbage collected.

Page 385: Core Java Ppt

OutputStream sub-classes

OutputStream is also inherited from the Object class. Each class of the OutputStreams provided by the java.io package is intended for a different purpose.

Page 386: Core Java Ppt

How Files and Streams Work

Java uses streams to handle I/O operations through which the data is flowed from one location to another. For example, an InputStream can flow the data from a disk file to the  internal memory and an OutputStream can flow the data from the internal memory to a disk file. The disk-file may be a text file or a binary file. When we work with a text file,  we use a character stream where one character is treated as per byte on disk. When we work with a binary file,  we use a binary stream.

Page 387: Core Java Ppt

Byte Streams

If a program needs to read/write bytes (8-bit data), it could use one of the subclasses of the InputStream or OutputStream respectively.

Page 388: Core Java Ppt
Page 389: Core Java Ppt

import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class BytesCopy { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("xanadu.txt"); out = new FileOutputStream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) {

Page 390: Core Java Ppt

in.close(); } if (out != null) { out.close(); } } } }

Page 391: Core Java Ppt

Character Streams

The abstract classes for reading and writing streams of characters are Reader and Writer. Each supports methods similar to those of its byte stream counterpart InputStream and OutputStream, respectively.

Page 392: Core Java Ppt

Reader and Writer

Page 393: Core Java Ppt

Working with Reader classes

Java provides the standard I/O facilities for reading text from either the file or the keyboard on the command line. The Reader class is used for this purpose that is available in the java.io package. It acts as an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). the Reader class is further categorized into the subclasses. 

Page 394: Core Java Ppt

java.io.Reader

Page 395: Core Java Ppt

InputStreamReader

An InputStreamReader is a bridge from byte streams to character streams i.e. it reads bytes and decodes them into Unicode characters according to a particular platform. Thus, this class reads characters from a byte input stream. When you create an InputStreamReader, you specify an InputStream from which, the InputStreamReader reads the bytes.

The syntax of InputStreamReader is written as:InputStreamReader <variable_name> = new

InputStreamReader(System.in);

Page 396: Core Java Ppt

BufferedReader  

The BufferedReader class is the subclass of the Reader class. It reads character-input stream data from a memory area known as a buffer maintains state.  The buffer size may be specified, or the default size may be used that is large enough for text reading purposes. 

Page 397: Core Java Ppt

BufferedReader consructors

BufferedReader(Reader in):Creates a buffering character-input stream that uses a default-sized input buffer.

BufferedReader(Reader in, int sz): Creates a buffering character-input stream that uses an input buffer of the specified size.

Page 398: Core Java Ppt

BufferedReader class provides some standard methods to perform specific reading operations shown in the table. All methods throws an  IOException, if an I/O error occurs.

 Method Return Type

 Description

 read( )  int  Reads a single character 

 read(char[] cbuf, int off, int len)

 int Read characters into a portion of an array.

 readLine( )  String Read a line of text. A line is considered to be  terminated by ('\n').

  close( )  void   Closes the opened stream.

Page 399: Core Java Ppt

File I/O

The File class deals with the machine dependent files in a machine-independent manner i.e. it is easier to write platform-independent code that examines and manipulates files using the File class. This class is available in the java.io package.

Page 400: Core Java Ppt

What we can do?

Create a File Constructing a File Name pathRead the File Write to a File Getting the Size of a File Count lines of a particular file Renaming a File or Directory Copying a File to Another File Copying Multiple Files  Moving a File or Directory to Another Directory Deleting a File or Directory Change a File timestamp Create a Temp File Delete a Temp File    Getting an absolute path and Parents of a Filename

Page 401: Core Java Ppt

Create file

import java.io.*;

public class CreateFile1{    public static void main(String[] args) throws IOException {      File f;      f=new File("myfile.txt");      if(!f.exists())

{      f.createNewFile();      System.out.println("New file \"myfile.txt\" has been created                           to the current directory");      }    }}

Page 402: Core Java Ppt

Constructing a File Name path 

import java.io.*;

public class PathFile{    public static void main(String[] args) throws IOException {      File f;    f=new File("example" + File.separator + "myfile.txt");      f.createNewFile();      System.out.println("New file \"myfile.txt\" has been created                              to the specified location");      System.out.println("The absolute path of the file is: "                +f.getAbsolutePath());          }}

Page 403: Core Java Ppt

FileInputstream

This class is a subclass of Inputstream class that reads bytes from a specified file name . The read() method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. To read text data, this class is used with an InputStreamReader and BufferedReader class. This class throws FileNotFoundException, if the specified file is not exist.

Page 404: Core Java Ppt

import java.io.*;

public class ReadFile{    public static void main(String[] args) throws IOException{      File f;    f=new File("myfile.txt");

      if(!f.exists()&& f.length()<0)      System.out.println("The specified file is not exist");

      else{         FileInputStream finp=new FileInputStream(f);      byte b;    do{      b=(byte)finp.read();      System.out.print((char)b);    }      while(b!=-1);        finp.close();        }    }  }

Page 405: Core Java Ppt

FileOutputStream

This class is a subclass of OutputStream that writes data to a specified file name. The write() method of this class writes a byte or array of bytes to the file. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a PrintWriter, BufferedWriter and an OutputStreamWriter class.

Page 406: Core Java Ppt

FileWriterThe FileWriter is a class used for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. This constructor simply overwrite the contents in the file by the specified string but if you put the boolean value as true with the file name (argument of the constructor) then the constructor append the specified data to the file i.e. the pre-exist data in a file is not overwritten and the new data is appended after the pre-exist data.

BufferedWriter The BufferWriter class is used to write text to a

character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings

Page 407: Core Java Ppt

import java.io.*;class FileWrite {   public static void main(String args[])  {      try{    // Create file     FileWriter fstream = new FileWriter("out.txt",true);        BufferedWriter out = new BufferedWriter(fstream);    out.write("Hello Java");    //Close the output stream    out.close();    }

catch (Exception e) {      System.err.println("Error: " + e.getMessage());    }  }}