You are on page 1of 407

1

Core Java
By Adrish Bhattacharyay Ardent Collaborations

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

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

-JAVA EE(ENTERPRISE EDITION)-FORMERLY J2EE

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

COREJAVA

Step by step java program execution(before Java2)

COREJAVA
More detailed explanation

Java source

.java

javac Java bytecode java

.class

Programming API

Programming API

Programming API

JVM
Platform interface of Web Browse

JVM
Platform interface of Windows

JVM
Platform interface of Unix

COREJAVA
Processiong .class file in JVM

JVM running Applet or Application

.class file

machine code

JIT COMPILER

CORE JAVA-OOP CONCEPTS


Types of Programming -Structured Programming Approach -Object Oriented Programming Approach

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

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

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: Height Width Length

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 Behavior: Keeping something

RealLife Object: State-Variable Behavior-method

CORE JAVA-OOP CONCEPTS


Features of 100% OOP Languages:
1) 2) 3) 4) 5) 6)

Encapsulation / DataHiding Abstraction Inheritance Polymorphism Dynamic Binding Message Passing

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.

CORE JAVA-OOP CONCEPTS


ENCAPSULATION / DATAHIDINGABSTRACTION

CAPSULE
MEDICINE INSIDE THE CAP

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 dont know what is capsulated inside the capsule..

COREJAVA
Simple java program

class A { public static void main(String arr[])

{
System.out.println(Hello World); } }

COREJAVA
Simple java program

class A name of the class { public static void main(String arr[])

{
System.out.println(Hello World); } }

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.

COREJAVA
Simple java program

String array as argument


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

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.

COREJAVA
Compiling java programs d:\mydirectory>javac A.java d:\mydirectory> Running java Programs d:\mydirectory>java A Hello World d:\mydirectory>

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

CORE JAVA-OOP CONCEPTS DEFAULT CONSTUCTORS


public void display() default constructor. -Non/Un-Parameterized It initialize variables to { default value.and stores it Constructor System.out.println("height="+height); dynamically System.out.println("lenghth="+length); System.out.println("width="+width); } public static void main(String arr[]) { new keyword for is Encapsulation() Declaring the Object dynamic allocation of Encapsulation encap=new Encapsulation() the memory Constructor: member encap.init(); function having the same name as the encap.display(); class name,used to } create object. }
There is a concept of

Constructor is of two type: If we dont define any constructor -Parameterized Constructor

CONSTRUCTOR : -Member Function

CORE JAVA-OOP CONCEPTS


parameterized
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 areaMath.PI*a*a); } public static void main(String arr[]) { Area a=new Area(); Area a1=new Area(4); Area a2=new Area(4.0); }

-having same name with the Class -used at the time of Object Creation Exampleclass Area{

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

CORE JAVA-OOP CONCEPTS


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 address
JVM(REF,ADDRESS)

GARBAGE COLLECTION DELETE THE REFERENCE OBJECT WILL BE FREE THEN GC WILL DELETE THE OBJECT..

GC REF OBJ

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

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. protected void finalize() { //code }

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 ).

CORE JAVA-OOP CONCEPTS


INHERITANCE Inheritance is a process, through which we can create a new class from an existing class. Parent , Super, Base Class

Child , Sub , Derived Class In Java extends key word is used

CORE JAVA-OOP CONCEPTS


class 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(); } }

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

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..

CORE JAVACLOSER 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.

CORE JAVACLOSER LOOKS TO METHODS


class Overloading { static int add(int x,int y) { return x+y; } static float add(float x,float y) { return x+y; } static int add(int x,int y,int z) { return x+y+z; } public static void main(String arr[]) { int result; result=add(10,20,30); System.out.println("Addition is:"+result); result=add(100,50); System.out.println("Addition is:"+result); float result1; result1=add(10.25f,20.50f); System.out.println("Addition is:"+result1); } } class Overloading { int add(int x,int y) { return x+y; } float add(float x,float y) { return x+y; } int add(int x,int y,int z) { return x+y+z; } public static void main(String arr[]) { int result; float result1; Overloading ovrld=new Overloading(); result=overld.add(10,20,30); System.out.println("Addition is:"result); result=overld.add(100,50); System.out.println("Addition is:"result); result1=overld.add(10.25f,20.50f); System.out.println("Addition is:"result1); } }

CORE JAVACLOSER LOOKS TO METHODS


@ Ardent Collaborations by Adrish Bhattacharyay

CORE JAVACLOSER 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 areaMath.PI*a*a);

33

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

Area a2=new Area(4.0);


} }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

CORE JAVACLOSER LOOKS TO METHODS

Difference: Method Overloading and Constructor Overloading


Method Overloading Using one object we can call all the methods having same name Example: A a=new A(); a.add(12,14); a.add(11.5,16.8); a.add(10,15,20); Constructor Overloading We need different objects to call each constructors

Example: Area a=new Area(); Area a1=new Area(4); Area a2=new Area(4.0);

CORE JAVACLOSER 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

CORE JAVACLOSER 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 {
A

//code
} class B extends A {
B

//code
}

CORE JAVACLOSER 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 {
A

//code
} class B extends A {
B

//code
} class C extends B {
C

//code

CORE JAVACLOSER 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:

CORE JAVACLOSER 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.


B

CORE JAVACLOSER 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.


B Diamond ProblemBut supported by C++ To Overcome this problem we have the concept of Interface..

CORE JAVACLOSER 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 { C

CORE JAVACLOSER 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;

43

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(); } adrish.b@ardentcollaborations.com }

http://www.ardentcollaborations.com

CORE JAVACLOSER 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: As soon as the UseStatic class is loaded, all of the static statements class UseStatic are run. First, a is set to 3, then the static block executes (printing a message), and finally, b is initialized to a * 4 or 12. Then main( ) is { called, which calls meth( ), passing 42 to x. The three println( ) static int a = 3; statements refer to the two static variables a and b, as well as to the static int b; local variable x. static void meth(int x) { Note It is illegal to refer to any instance variables inside of a static System.out.println("x = " + x); method. Here is the output of the program: System.out.println("a = " + a); System.out.println("b = " + b); Static block initialized. } x = 42 static //Static Block a=3 b = 12 { System.out.println("Static block initialized.");Outside of the class in which they are defined, static methods and variables can be used independently of any object. To do so, you need b = a * 4; only specify the name of their class followed by the dot operator. For } example, if you wish to call a static method from outside its class, you public static void main(String args[]) can do so using the following general form: {

CORE JAVACLOSER 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: Here, classname is the name of the class in which the static class UseStatic method is declared. As you can see, this format is similar to that { used to call non-static methods through object reference static int a = 3; variables. A static variable can be accessed in the same wayby static int b; use of the dot operator on the name of the class. This is how Java static void meth(int x) { implements a controlled version of global functions and global System.out.println("x = " + x); variables. 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[]) {

CORE JAVACLOSER 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: Here is an example. Inside main( ), the static method callme( ) class UseStatic and the static variable b are accessed outside of their class class StaticDemo { { static int a = 42; static int a = 3; static int b = 99; static int b; static void callme() { static void meth(int x) { System.out.println("a = " + a); System.out.println("x = " + x); } System.out.println("a = " + a); } System.out.println("b = " + b); class StaticByName { } public static void main(String args[]) { static //Static Block StaticDemo.callme(); { System.out.println("b = " + StaticDemo.b); System.out.println("Static block initialized."); } b = a * 4; } } public static void main(String args[]) { meth(42); } } Here is the output of this program: a = 42 b = 99

CORE JAVACLOSER 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: They can only call other static methods.

They must only access static data.

They cant refer to this or super in any way.

CORE JAVACLOSER 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 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); } } { Box mybox1=new Box(10,20,30); {

Output:

Volume is6000.0

CORE JAVACLOSER 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 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); } } { Box mybox1=new Box(10,20,30); {

Output:

Volume is6000.0

CORE JAVACLOSER LOOKS TO METHODS

this keyword: this keyword is used to refer to the current object. It is illegal in Java to declare two local variables with the this- is always a reference to object on which the method was invoked. same name inside the same or enclosing scopes . Example: When a local variable has the same name as an instance class Box{ variable, the local variable hides the instance variable. double width; Thats why width, height and depth were not used as the double height; names of the parameters to the Box() constructor inside the double depth; Box class. Box(double w,double h,double d) { This can used to solve this name-space collision that might this.width=w; occur between instance variables and local variables. this.height=h; We can use
this.depth=d; } double volume(){ return width*height*depth; } Box(double width,double height,double depth) { this.width=width; this.height=height; this.depth=depth }

}
class BoxDemo{ public static void main(String arr[]) Box mybox2=new Box(3,6,9); double vol; vol=mybox1.volume(); { Box mybox1=new Box(10,20,30);

Output:

System.out.println("Volume is"+vol);

Volume is6000.0

CORE JAVACLOSER 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.

CORE JAVACLOSER 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); } }

53

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

CORE JAVACLOSER LOOKS TO METHODS

Difference between Method Overloading and Method Overridiing:

Method overloading: Compile-time Polymorphism Early/Static Binding Within one class

Method Overriding: Runtime Polymorphism Late/Dynamic Binding Base class and Child class

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 }

Abstract Class and Interfaces

By Adrish Bhattacharyay Ardent Collaborations http://www.ardentcollaborations.com adrish.b@ardentcollaborations.com

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

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.

Abstract Class
Abstract Classes may contain abstract methods. They are capable to contain abstract methods.

Inheritance of the abstrsct classes is possible.

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..

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

Abstract Class
class C extends B

SIMPLE EXAMPLE:
abstract class A { abstract void show(); void display() { System.out.println(In class A); }

void show()
{ System.out.println(Definiton of show); } void show1() {

System.out.println(Definition of show1);
} }

} abstract class B extends A { abstract void show1(); void display1() { System.out.println(In class B); } class Ex { public static void main(String arr[]) { C c=new C(); c.display(); c.display1(); c.show(); c.show1();

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

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.

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.

Interfaces
Few fact about Interfaces No 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.

Interfaces
One Interface can inherit another Interface.

Simple Example on Interface


interface A{ void display(); class D {

}
interface B extends A{ void show(); } class C implements B{ void display(){ System.out.println(interface A); } void show(){ System.out.println(Interface B); } }

public static void main(String arr[])


{ C c=new C(); c.display(); c.show(); } }

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.

CORE JAVA CONCEPT OF PACKAGE

BY ADRISH BHATTACHARYAY ARDENT COLLABORATIONS www.ardentcollaborations.com adrish.b@ardentcollaborations.com

What is package?? Under Java package is used to contain different classes. package Types of packages:

System packages Ex: java.lang.* java.util.* java.io.* java.sql.* www.ardentcollaborations.com

User Defined Packages Created by user . We have to follow some steps . package Key word is used to create a package

adrish.b@ardentcollaborations.com

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

adrish.b@ardentcollaborations.com

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 adrish.b@ardentcollaborations.com

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

adrish.b@ardentcollaborations.com

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

adrish.b@ardentcollaborations.com

CORE JAVA-EXCEPTION HANDLING

By-Adrish Bhattacharyay Phone:+91-9433249290 Email-adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Exceptions
Exception is the short hand of the Exceptional Event phrase

Definition: Abnormal conditions that arises in a code sequence at run-time. We can say these are runtime errors.

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)

Exception Handling Fundamentals


Basically Exceptions occurs due to some runtime 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.

Exception Handling Fundamentals


When Exception occurs Object Creation(thrown)

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

Exception Handling Fundamentals


When 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

Java Key Words for - Exception Handling


try 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(); }

Exception Hierarchy

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

Multiple catch clauses


PSVM(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); } finally { int y=a[1]/a[ ]; System.out.println(y=+y); }

catch(ArrayIndexOutOfBoundException e) { e.printStackTrace(); }

Nested try
try { try {

}
catch(Exception e) { }

}
catch(Exception e) { }

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.

throw
Ex: class ThrowDemo { public void demoproc() { try { throw new NullPointerException(demo); } catch(NullPointerException e) {S.O.P(caught); e.printStackTrace(); throw e; }

throw
public static void main(String arr[]) { try { demoproc(); } catch(NullPointerException e) { S.O.P(ReCaught); e.printStackTrace(); } } }

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

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

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

Multithreaded Programming using Java Threads

ADRISH BHATTACHARYAY Ardent Collaborations email- adrish.b@ardentcollaborations.com www.ardentcollaborations.com


92

A single threaded program


93

class ABC { .
public void main(..) { .. }
begin

body end

}
www.ardentcollaborations.com

A Multithreaded Program
94

Main Thread

start

start

start

Thread A

Thread B

Thread C

Threads may switch or exchange data/results www.ardentcollaborations.com

Single and Multithreaded Processes


95

threads are light-weight processes within a process


Single-threaded Process Threads of Execution Multiplethreaded Process

Multiple instruction stream Single instruction stream Common Address Space


www.ardentcollaborations.com

96

Multithreaded Server: For Serving Multiple Clients Concurrently

Client 1 Process

Server Process
Server Threads

Internet

Client 2 Process

www.ardentcollaborations.com

97

Web/Internet Applications: Serving Many Users Simultaneously


PC client

Internet Server
Local Area Network

PD A
www.ardentcollaborations.com

98

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

Editing Thread

www.ardentcollaborations.com

What are Threads?


99

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.
www.ardentcollaborations.com

Java Threads
100

Java has built in thread support for Multithreading Synchronization Thread Scheduling Inter-Thread Communication:
currentThread yield sleep resume

start run stop

setPriority getPriority suspend

Java Garbage Collector is a low-priority thread.


www.ardentcollaborations.com

Threading Mechanisms...
101

Create a class that extends the Thread class Create a class that implements the Runnable interface

Thread

Runnable

Thread

MyThread

MyClass

(objects are threads) [a]

(objects with run() body) [b]

www.ardentcollaborations.com

1st method: Extending Thread class


102

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();
www.ardentcollaborations.com

An example
103

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

www.ardentcollaborations.com

2nd method: Threads by implementing Runnable interface


104

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

www.ardentcollaborations.com

An example
105

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

www.ardentcollaborations.com

Life Cycle of Thread


106

new
start()
I/O completed

ready
notify()
Time expired/ interrupted

suspend()

waiting
dispatch

sleeping
sleep()

blocked

wait()

suspend()

running
completion

Block on I/O

stop()

dead

www.ardentcollaborations.com

107

A Program with Three Java Threads

Write a program that creates 3 threads

www.ardentcollaborations.com

Three threads example


108

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

www.ardentcollaborations.com

109

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

www.ardentcollaborations.com

Run 1
110

[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

www.ardentcollaborations.com

Run2
111

[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

www.ardentcollaborations.com

Thread Priority
112

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

www.ardentcollaborations.com

Thread Priority Example


113

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

www.ardentcollaborations.com

Thread Priority Example


114

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

www.ardentcollaborations.com

Thread Priority Example


115

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

}
}

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Accessing Shared Resources


116

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()

www.ardentcollaborations.com

117

Online Bank: Serving Many Customers and Operations


PC client

Internet Bank Server


Local Area Network

Bank Database www.ardentcollaborations.com

PD A

Shared Resources
118

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() {

www.ardentcollaborations.com

119

the driver: 3rd Threads sharing the same object


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

120

Shared account object between 3 threads


class 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
www.ardentcollaborations.com

accoun t (shared object)

121

Monitor (shared object access): serializes operation on shared object


class 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. }

}
www.ardentcollaborations.com

Multithreaded Server
122

Multithreaded Server

Client Process

Server Process
Server Threads

Client Process

User Mode

Kernel Mode
Message Passing Facility

www.ardentcollaborations.com

CORE JAVA-String Handling --------by------123

Adrish Bhattacharyay @

ARDENT
COLLABORATIONS

http://www.ardentcollaborations.com adrish.b@ardentcollaborations.com

5/1/2012

String Handling
Introduction:
. As is the case in most other programming languages, in Java a string is a sequence of 124 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.
http://www.ardentcollaborations.com adrish.b@ardentcollaborations.com 5/1/2012

String Constructors
The String class supports several constructors. To create an empty String, you call the default constructor.
For example, String s=new String();
125

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 shttp://www.ardentcollaborations.com with the string abc.
adrish.b@ardentcollaborations.com

5/1/2012

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

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.


http://www.ardentcollaborations.com adrish.b@ardentcollaborations.com 5/1/2012

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

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: http://www.ardentcollaborations.com Java adrish.b@ardentcollaborations.com 5/1/2012

String Constructors
Though Javas 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)
128

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.
http://www.ardentcollaborations.com adrish.b@ardentcollaborations.com 5/1/2012

String Constructors
Example:
129

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 CDE
http://www.ardentcollaborations.com adrish.b@ardentcollaborations.com 5/1/2012

String Constructors
Constructing String from a StringBuffer by using constructor:
130

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)

http://www.ardentcollaborations.com adrish.b@ardentcollaborations.com

5/1/2012

String Length
The length of a string is the number of characters that it contains. To obtain this value,
call the length( ) method, shown here: int length( )
131

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

http://www.ardentcollaborations.com adrish.b@ardentcollaborations.com

5/1/2012

String Literals
The 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
132

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 http://www.ardentcollaborations.com directly on a adrish.b@ardentcollaborations.com 5/1/2012

String Concatenation
Java does not allow operators to be applied to String objects. The one exception to
133

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 http://www.ardentcollaborations.com have " +
adrish.b@ardentcollaborations.com
5/1/2012

String Concatenation with Other Data Types with other types of data. For example, consider You can concatenate strings
134

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
http://www.ardentcollaborations.com before.The compiler will convert adrish.b@ardentcollaborations.com

an operand to its string equivalent whenever 5/1/2012

135

String Concatenation with Other Data Types


String s = "four: " + 2 + 2;
System.out.println(s);

Be careful when you mix other types of operations with string concatenation expressions, however. You might get surprising results. Consider the following:

This fragment displays four: 22 rather than the four: 4 that you probably expected. Heres 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: adrish.b@ardentcollaborations.com
http://www.ardentcollaborations.com 5/1/2012

136

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 humanreadable

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.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com String toString( )

general form:

137

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 + "."; } } adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

138

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Character Extraction
139

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);
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Character Extraction
140

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 sourceEnd1. 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 adrish.b@ardentcollaborations.com large enough to hold the number of characters in the specified substring. http://www.ardentcollaborations.com

Character Extraction
141

UsinggetChars()

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

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

Character Extraction
142

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: adrish.b@ardentcollaborations.com
http://www.ardentcollaborations.com

char[ ] toCharArray( )

String Comparison
143

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. adrish.b@ardentcollaborations.com
http://www.ardentcollaborations.com

String Comparison
144

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 adrish.b@ardentcollaborations.com characters in the same order, and false otherwise.
http://www.ardentcollaborations.com

String Comparison
145

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)); } adrish.b@ardentcollaborations.com } http://www.ardentcollaborations.com

String Comparison
146

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

OUTPUT System.out.println(s1 + " equals " + s3 + " -> " + Hello equals Hello -> true s1.equals(s3)); Hello equals Good-bye System.out.println(s1 + " equals " + s4 + " -> " + -> false Hello equals HELLO -> false s1.equals(s4)); Hello equalsIgnoreCase HELLO -> true
s1.equalsIgnoreCase(s4)); } adrish.b@ardentcollaborations.com } http://www.ardentcollaborations.com

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

String Comparison
147

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 adrish.b@ardentcollaborations.com passed in http://www.ardentcollaborations.com numChars. In the second version, if ignoreCase is true, the case of the characters is

startsWith( ) and endsWith( )


148

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. adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

equals( ) Versus ==
149

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 two different String objects can contain the same adrish.b@ardentcollaborations.com characters, but references to these objects http://www.ardentcollaborations.com

equals( ) Versus ==
150

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com }

equals( ) Versus ==
151

equals( ) Versus ==

class EqualsNotEqualTo

{
public static void main(String args[]) {
OUTPUT String s1 = "Hello"; true Hello equals Hello -> Hello == = new false String s2 Hello ->String(s1);

System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com }

Searching Strings
152

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.


adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Searching Strings
153

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Searching Strings
154

System.out.println("lastIndexOf(the) = " +s.la stIndexOf("the")); Now is the time for all good men to come to = " +s.indexOf('t', 10)); & System.out.println("indexOf(t, 10) the aid of their country. indexOf(t) = 7 lastIndexOf() System.out.println("lastIndexOf(t, 60) = " +s.lastIndexOf('t', lastIndexOf(t) = 65 60)); indexOf(the) = 7 System.out.println("indexOf(the, 10) = " +s.indexOf("the", 10)); lastIndexOf(the) = 55 indexOf(t, System.out.println("lastIndexOf(the, 60) = " 10) = 11 lastIndexOf(t, 60) = 55 +s.lastIndexOf("the", 60)); indexOf(the, 10) = 44 } lastIndexOf(the, 60) = 55 } indexOf()

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Modifying a String
155

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 String methods, which will construct a new copy of the string with your modifications complete. substring adrish.b@ardentcollaborations.com concat http://www.ardentcollaborations.com

substring()
156

You can extract a substring using substring( ). It has two forms. String substring(int startIndex) String substring(int startIndex, int endIndex)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

substring()
157

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

substring()
158

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; This is a test. This is, too. } Thwas is a test. This is, too. Thwas was a test. This is, too. } while(i != a test. Thwas is, too. Thwas was -1);

} Thwas was a test. Thwas was, too. } adrish.b@ardentcollaborations.com


http://www.ardentcollaborations.com

concat( )
159

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"; adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

replace( )
160

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 s.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

trim()
161

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 states capital. It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered by the adrish.b@ardentcollaborations.com user.
http://www.ardentcollaborations.com

trim()
162

import java.io.*; class UseTrim { public static void main(String args[]) throws IOException {

Program showing trim().

// 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 {

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

trim()
163

str = br.readLine(); str = str.trim(); // remove whitespace

Program showing trim().

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

adrish.b@ardentcollaborations.com } http://www.ardentcollaborations.com

164

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 Javas 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[ ])
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

165

Changing the Case of Characters Within a String


String toLowerCase( )
String toUpperCase( )

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

166

Changing the Case of Characters Within a String


class ChangeCase { public static void main(String args[]) and { Original: This is a test. Uppercase: a test."; toLowerCase() String s = "This is THIS IS A TEST. Lowercase: 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 }
using toUpperCase()

String Buffer
167

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 adrish.b@ardentcollaborations.com manipulate StringBuffers behind the scenes by using http://www.ardentcollaborations.com the overloaded + operator.

String Buffer
168

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 adrish.b@ardentcollaborations.com room for a few extra characters, StringBuffer reduces the number http://www.ardentcollaborations.com of reallocations that take place.

String Buffer
169

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( )

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

String Buffer
170

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 = " + buffer = Hello sb.capacity()); length = 5 capacity = 21 } }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

String Buffer
171

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 buffer.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

String Buffer
172

setLength( )
To set the length of the buffer within a StringBuffer object, use setLength( ).
Its general form is shown here:

void setLength(int len)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

String Buffer
173

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)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

String Buffer
174

Program explanning charAt(),set CharAt(),set Length()

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);
buffer before after = System.out.println("buffer= Hello " + sb); charAt(1) before = e System.out.println("charAt(1) after = " + buffer after = Hi sb.charAt(1));charAt(1) after = i

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com }

String Buffer
175

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)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

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 sourceEnd1. 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.

String Buffer
176

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

String Buffer
177

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); } } a = 42!

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

String Buffer
178

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.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

String Buffer
179

insert( )

class insertDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("I Java!"); sb.insert(2, "like "); System.out.println(sb); } I like Java! }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

String Buffer
180

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.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

String Buffer
181

reverse()

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

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

String Buffer
182

delete( ) and deleteCharAt( ) Used to delete chararcters from StringBuffer. Forms:

StringBuffer delete(int startIndex, int endIndex) StringBuffer deleteCharAt(int loc)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

String Buffer
183

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); } }
After delete: This a test. After deleteCharAt: his a test.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

String Buffer
184

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 endIndex1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned.
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

String Buffer
185

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); } After replace: This was a test. }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

String Buffer
186

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 endIndex1. These methods work just like those defined adrish.b@ardentcollaborations.com for String that were described earlier.
http://www.ardentcollaborations.com

StringBuilder
187

StringBuilder is introduced from jdk5 StringBuilder is identical to StringBuffer except for one important diference : it is not synchronized,which means that it is not thread-safe. Adv: Faster Performance

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

188

Explore java.lang package


By Adrish Bhattacharyay Ardent Collaborations

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Introduction
189

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

java.lang.*(classes)
190

Boolean

InheritableThreadLocal

Runtime

System

Byte
Character

Integer
Long

RuntimePermission
SecurityManager

Thread
ThreadGroup

Class
ClassLoader Compiler Double Enum Float

Math
Number

Short

ThreadLocal

There are two classes defined by Character: StackTraceElement Throwable Character.Subset and Character.UnicodeBlock. Object StrictMath Void
Package Process ProcessBuilder String StringBuffer StringBuilder

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

java.lang.*(interfaces)
191

Appendable CharSequence Cloneable

Comparable Iterable Readable

Runnable

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


192

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 doubleValue( ) byte byteValue( ) double here: float floatValue( )
int intValue( ) long longValue( ) short shortValue( )

The values returned by these methods can be rounded.Number has six Double Float Byte Short Integer Long concrete subclasses that hold explicit values of each numeric type:
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


193

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 floatingpoint number.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


194

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.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


195

Number Double and Float: Both Float and Double define the following constants:
MAX_VALUE MIN_VALUE NaN POSITIVE_INFINITY Maximum positive value Minimum positive value Not a number Positive infinity

NEGATIVE_INFINITY
TYPE SIZE MAX_EXPONENT MIN_EXPONENT MIN_NORMAL
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Negative infinity
The Class object for float or double The bit width of the wrapped value(from J2SE5) Maximum exponent(from JSE6) Minimum exponent(from JSE6) Minimum positive normal value(from JSE6)

Primitive Type Wrapper


196

Number Double and Float: Methods defined by Float


Method byte byteValue( ) static int compare(float num1,float num2) Description Returns the value of the invoking object as a byte. Compares the values of num1 and num2. Returns 0 if the values are equal. Returns a negative value if num1 is less than num2. Returns a positive value if num1 is greater than num2. Compares the numerical value of the invoking object with that of f. 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. (Added by Java 2)

int compareTo(Float f)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


197

Number Double and Float: Methods defined by Float


Method int compareTo(Object obj) Description Operates identically to compareTo(Float) if obj is of class Float. Otherwise, throws a ClassCastException. Returns the value of the invoking object as a double.

double doubleValue( )

boolean equals(Object FloatObj)

Returns true if the invoking Float object is equivalent to FloatObj. Otherwise, it returns false
Returns the IEEE-compatible,single-precision bit pattern that corresponds to the num.

static int floatToIntBits(float num)

static int floatToRawIntBits(float num)

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


198

Number Double and Float: Methods defined by Float


Method Description

float floatValue( )
int hashCode( ) static float intBitsToFloat(int num)

Returns the value of the invoking object as a float.


Returns the hash code for the invoking object. Returns float equivalent of the IEEE-compatible, single-precision bit pattern specified by num. Returns the value of the invoking object as an int. Returns true if the invoking object contains an infinite value. Otherwise, it returns false. Returns true if num specifies an infinite value. Otherwise, it returns false.

int intValue( ) boolean isInfinite( ) static boolean isInfinite(float num)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


199

Number Double and Float: Methods defined by Float


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

static boolean isNaN(float num)

long longValue( )
static float parseFloat(String str)throws NumberFormatException

Returns the value of the invoking object as a long.


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

short shortValue( )
static String toHexString(float num)

Returns the value of the invoking object as a short.


Returns a string containing the value of num in hexadecimal format.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


200

Number Double and Float: Methods defined by Float


Method Description

String toString( ) static String toString(float num)

Returns the string equivalent of the invoking object. Returns the string equivalent of the value specified by num.

static Float valueOf(String str)throws NumberFormatException


static Float valueOf(float num)

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


201

Number Double and Float: Methods defined by Double


Method byte byteValue( ) static int compare(double num1, double num2) Description Returns the value of the invoking object as a byte. Compares the values of num1 and num2. Returns 0 if the values are equal. Returns a negative value if num1 is less than num2. Returns a positive value if num1 is greater than num2. Compares the numerical value of the invoking object with that of f. 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. (Added by Java 2)

int compareTo(Double f)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


202

Number Double and Float: Methods defined by Double


Method int compareTo(Object obj) Description Operates identically to compareTo(Float) if obj is of class Float. Otherwise, throws a ClassCastException. Returns the value of the invoking object as a double.

double doubleValue( )

boolean equals(Object DoubleObj)

Returns true if the invoking Double object is equivalent to DoubleObj. Otherwise, it returns false
Returns the IEEE-compatible,single-precision bit pattern that corresponds to the num.

static long doubleToLongBits(float num)

static long doubleToRawLongBits(float num)

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


203

Number Double and Float: Methods defined by Double


Method Description

float floatValue( )
int hashCode( ) static double longBitsToDouble (int num)

Returns the value of the invoking object as a float.


Returns the hash code for the invoking object. Returns double equivalent of the IEEE-compatible, single-precision bit pattern specified by num. Returns the value of the invoking object as an int. Returns true if the invoking object contains an infinite value. Otherwise, it returns false. Returns true if num specifies an infinite value. Otherwise, it returns false.

int intValue( ) boolean isInfinite( ) static boolean isInfinite(double num)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


204

Number Double and Float: Methods defined by Double


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

static boolean isNaN(double num)

long longValue( )
static double parseDouble (String str)throws NumberFormatException

Returns the value of the invoking object as a long.


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

short shortValue( )
static String toHexString(double num)

Returns the value of the invoking object as a short.


Returns a string containing the value of num in hexadecimal format.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


205

Number Double and Float: Methods defined by Double


Method Description

String toString( ) static String toString(double num)

Returns the string equivalent of the invoking object. Returns the string equivalent of the value specified by num.

static Double valueOf(String str)throws NumberFormatException


static Double valueOf(double num)

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Example
206

Demonstrati ng ifInfinite() and isNan():

Float and Double provide the methods isInfinite( ) and isNaN( ), which help when manipulating two special double and float values. These methods test for two unique values 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.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Example
207

Demonstrati ng 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()); } }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Example
208

Demonstrati ng 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()); Infinity: true, false } NaN: false, true }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


209

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)
adrish.b@ardentcollaborations.com Long(String str) throws NumberFormatException http://www.ardentcollaborations.com

Primitive Type Wrapper


210

Number Byte, Short, Integer, and Long: CONSTANTS:

MIN_VALUE MAX_VALUE TYPE

Minimum value Maximum value The Class object for byte, short, int, or long

SIZE

The bit width of the wrapped value.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


211

Number Byte , Short, Integer, and Long:METHODS


Method
byte byteValue( ) int compareTo(Byte b)

Description
Returns the value of the invoking object as a byte. 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. Operates identically to compareTo(Byte) if obj is of class Byte. Otherwise, throws a ClassCastException.

int compareTo(Object obj)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


212

Number Byte , Short, Integer, and Long:METHODS


Method
static Byte decode(String str) throws NumberFormatException

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

double doubleValue( )
boolean equals(Object ByteObj) float floatValue( ) int hashCode( )

Returns the value of the invoking object as a double.


Returns true if the invoking Byte object is equivalent to ByteObj. Otherwise, it returns false. Returns the value of the invokingobject as a float. Returns the hash code for the invoking object.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


213

Number Byte , Short, Integer, and Long:METHODS


Method
int intValue( ) long longValue()

Description
Returns the value of the invoking object as an int. Returns the value of the invoking object as a long.

static byte parseByte(String str) throws NumberFormatException


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

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


214

Number Byte , Short, Integer, and Long:METHODS


Method
short shortValue( ) String toString( ) static String toString(byte num) static Byte valueOf(String str) throws NumberFormatException

Description
Returns the value of the invoking object as a short. Returns a string that contains the decimal equivalent of the invoking object Returns a string that contains the decimal equivalent of num. 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 contains the value specified by the string in str using the specified radix.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


215

Number Byte , Short, Integer, and Long:METHODS


Method
byte byteValue( ) int compareTo(Short s)

Description
Returns the value of the invoking object as a short. 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. Operates identically to compareTo(Short) if obj is of class Short. Otherwise, throws a ClassCastException.

int compareTo(Object obj)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


216

Number Byte , Short, Integer, and Long:METHODS


Method
static Short decode(String str) throws NumberFormatException

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

double doubleValue( )
boolean equals(Object ShortObj) float floatValue( ) int hashCode( )

Returns the value of the invoking object as a double.


Returns true if the invoking Short object is equivalent to ByteObj. Otherwise, it returns false. Returns the value of the invokingobject as a float. Returns the hash code for the invoking object.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


217

Number Byte , Short, Integer, and Long:METHODS


Method
int intValue( ) long longValue()

Description
Returns the value of the invoking object as an int. Returns the value of the invoking object as a long.

static short parseShort (String str) throws NumberFormatException


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

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


218

Number Byte , Short, Integer, and Long:METHODS


Method
short shortValue( ) String toString( ) static String toString(short num) static Short valueOf(String str) throws NumberFormatException static Short valueOf(String str,int radix) throws NumberFormatException

Description
Returns the value of the invoking object as a short. Returns a string that contains the decimal equivalent of the invoking object Returns a string that contains the decimal equivalent of num. Returns a Short object that contains the value specified by the string in str. Returns a Short object that contains the value specified by the string in str using the specified radix.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


219

Number Byte , Short, Integer, and Long:METHODS


Method
byte byteValue( ) int compareTo(Integer i)

Description
Returns the value of the invoking object as a short. 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 class Integer. Otherwise, throws a ClassCastException.


Returns the number of set bits in num.

static int bitCount(int num)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


220

Number Byte , Short, Integer, and Long:METHODS


Method Method
static Integer decode(String str) static Integer decode(String str) throws NumberFormatException throws NumberFormatException double doubleValue( ) ) double doubleValue( boolean equals(Object IntegerObj) float floatValue( )

Description Description
Returns a Integer object that contains thethe value Returns a Integer object that contains value specified by the string in str. string in str. specified by the Returns the value of the invoking object as asdouble. Returns the value of the invoking object a a double. Returns true if the invoking Short object is equivalent to Returns true if the invoking Short object is equivalent to IntegerObj. Otherwise, it returns false.

boolean equals(Object IntegerObj) float floatValue( )


int hashCode( )

IntegerObj. Otherwise, it returns false.

Returns the value of the invokingobject as a float.

Returns the value of the invokingobject as a float.


Returns the hash code for the invoking object.

int hashCode( )
static int lowestOneBit(int num)

Returns the hash code for the invoking object.


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.

static int lowestOneBit(int num)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


221

Number Byte , Short, Integer, and Long:METHODS


Method
int intValue( ) static Integer getInteger(String propertyName)
static Integer getInteger(String propertyName, int default)

Description
Returns the value of the invoking object as an int. Returns the value associated with the environmental property specified by propertyName. A null is returned on failure.
Returns the value associated with the environmental property specified by propertyName. The value of default is returned on failure.

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

Returns the value of the invoking object as a long. Returns the integer equivalent of the number contained in the string specified by str using radix 10. Returns the integer equivalent of the number contained in the string specified by str using the specified radix

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


222

Number Byte , Short, Integer, and Long:METHODS


Method
short shortValue( ) String toString( ) static String toString(short num) static Integer valueOf(String str) throws NumberFormatException

Description
Returns the value of the invoking object as a short. Returns a string that contains the decimal equivalent of the invoking object Returns a string that contains the decimal equivalent of num. 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.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


223

Number Byte , Short, Integer, and Long: METHODS


Method
byte byteValue( ) int compareTo(Long l)

Description
Returns the value of the invoking object as a short. 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 class Long. Otherwise, throws a ClassCastException.


Returns the number of set bits in num.

static int bitCount(int num)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


224

Number Byte , Short, Integer, and Long: METHODS


Method Method
static Long decode(String str) str) static Integer decode(String throws NumberFormatException throws NumberFormatException double doubleValue( ) ) double doubleValue( boolean equals(Object LongObj) float floatValue( )

Description Description
Returns a Long object that contains the value specified by Returns a Integer object that contains the value the string in str. string in str. specified by the Returns the value of the invoking object as asdouble. Returns the value of the invoking object a a double. Returns true if the invoking Short object is equivalent to Returns true if the invoking Short object is equivalent to LongObj. Otherwise, it returns false.

boolean equals(Object IntegerObj) float floatValue( )


int hashCode( )

IntegerObj. Otherwise, it returns false.

Returns the value of the invokingobject as a float.

Returns the value of the invokingobject as a float.


Returns the hash code for the invoking object.

int hashCode( )
static long lowestOneBit(long num)

Returns the hash code for the invoking object.


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.

static int lowestOneBit(int num)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


225

Number Byte , Short, Integer, and Long: METHODS


Method
int intValue( ) static Long getLong (String propertyName)
static Long getLong (String propertyName, int default)

Description
Returns the value of the invoking object as an int. Returns the value associated with the environmental property specified by propertyName. A null is returned on failure.
Returns the value associated with the environmental property specified by propertyName. The value of default is returned on failure.

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

Returns the value of the invoking object as a long. Returns the long equivalent of the number contained in the string specified by str using radix 10. Returns the long equivalent of the number contained in the string specified by str using the specified radix

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


226

Number Byte , Short, Integer, and Long: METHODS


Method
short shortValue( ) String toString( ) static String toString(short num) static Integer valueOf(String str) throws NumberFormatException

Description
Returns the value of the invoking object as a short. Returns a string that contains the decimal equivalent of the invoking object Returns a string that contains the decimal equivalent of num. 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.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


227

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.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Example of parseInt()
228

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.");

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Example of parseInt()
229

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

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); }
adrish.b@ardentcollaborations.com } http://www.ardentcollaborations.com

Primitive Type Wrapper


230

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, respectively.
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

231

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)); 19648 in binary: } }
100110011000000 19648 in octal: 46300 19648 in hexadecimal: 4cc0 OUTPUT

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


232

Character Character 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( )

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


233

Character COSTANTS
MAX_RADIX MIN_RADIX MAX_VALUE MIN_VALUE TYPE The largest radix The smallest radix The largest character value The smallest character value The Class object for char

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


234

Character:Methods
METHOD
static boolean isDefined(char ch) static boolean isDigit(char ch) static boolean isIdentifierIgnorable(char ch) static boolean isISOControl(char ch) static boolean isJavaIdentifierPart(char ch)

DESCRIPTION
Returns true if ch is defined by Unicode. Otherwise, it returns false. Returns true if ch is a digit.Otherwise, it returns false. Returns true if ch should be ignored in an identifier.Otherwise, it returns false. Returns true if ch is an ISO control character. Otherwise, it returns false. Returns true if ch is allowed as part of a Java identifier (other than the first character). Otherwise, it returns false.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


235

Character:Methods
METHOD
static boolean isJavaIdentifierStart(char ch)

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

static boolean isLetter(char ch)


static boolean isLetterOrDigit(char ch) static boolean isLowerCase(char ch) static boolean isMirrored(char ch)

Returns true if ch is a letter.Otherwise, it returns false.


Returns true if ch is a letter or a digit. Otherwise, it returns false. Returns true if ch is a lowercase letter. Otherwise, it returns false. 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.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


236

Character:Methods
METHOD
static boolean isSpaceChar(char ch) static boolean isTitleCase(char ch) static boolean isUnicodeIdentifierPart(char ch)

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

static boolean isUnicodeIdentifierStart(char ch)

static boolean isUpperCase(char ch)


adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Returns true if ch is an uppercase letter. Otherwise, it returns false.

Primitive Type Wrapper


237

Character:Methods
METHOD
static boolean isWhitespace(char ch) static char toLowerCase(char ch) static char toTitleCase(char ch) static char toUpperCase(char ch)

DESCRIPTION
Returns true if ch is whitespace. Otherwise, it returns false. Returns lowercase equivalent of ch. Returns titlecase equivalent of ch. Returns uppercase equivalent of ch.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


238

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)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


239

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

240

Demonstrate several Is... methods.


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

Demonstrate several Is... methods.

char a[] = {'a', 'b', '5', '?', 'A', ' '};


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

a is a letter. System.out.println(a[i] + " is a digit."); a is lowercase. b is a letter. if(Character.isLetter(a[i])) b is lowercase. System.out.println(a[i] + " is a letter."); 5 is a digit. if(Character.isWhitespace(a[i])) A is a letter. A System.out.println(a[i] + " is whitespace.");is uppercase. is whitespace. if(Character.isUpperCase(a[i]))
if(Character.isDigit(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

Primitive Type Wrapper


241

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 false.
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


242

Boolean -Methods
Method
boolean booleanValue( ) boolean equals(Object boolObj)

Description
Returns boolean equivalent. Returns true if the invoking object is equivalent to boolObj. Otherwise, it returns false. Returns true if the system property specified by propertyName is true. Otherwise, it returns False.

static boolean getBoolean(String propertyName)

int hashCode( ) static boolean parseBoolean(String str)

Returns the hash code for the invoking object. Returns true if str contains the string true.Case is not significant. Otherwise ,returns false.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Primitive Type Wrapper


243

Boolean -Methods
Method
String toString( )

Description
Returns the string equivalent of the invoking object.

static String toString(boolean boolVal) static Boolean valueOf(boolean boolVal) static Boolean valueOf(String boolString)

Returns the string equivalent of boolVal. Returns the Boolean equivalent of boolVal. Returns true if boolString contains the string true (in uppercase or lowercase). Otherwise, it returns false.

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.
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Process -class
244

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Process -class
245

Method void destroy( ) int exitValue( ) InputStream getErrorStream( )

Description Terminates the process. Returns an exit code obtained from a subprocess. Returns an input stream that reads input from the process err output stream. Returns an input stream that reads input from the process out output stream. Returns an output stream that writes output to the process in input stream. Returns the exit code returned by the process. This method does not return until the process on which it is called terminates.

InputStream getInputStream( )

OutputStream getOutputStream( ) int waitFor( ) throws InterruptedException

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Runtime -class
246

The Runtime class encapsulates the runtime 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

Runtime -class
247 Method void addShutdownHook(Thread thrd) Description Registers thrd as a thread to be run when the Java virtual machine terminates.

Process exec(String progName) throws IOException

Executes the program specified by progName as a separate process. An object of type Process is returned that describes the new process.

Process exec(String progName, String environment[ ]) throws IOException

Executes the program specified by progName as a separate process with the environment specified by environment. An object of type Process is returned that describes the new process.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Runtime -class
248 Method Description

Process exec(String comLineArray[ ]) throws IOException

Executes the command line specified by the strings in comLineArray as a separate process. An object of type Process is returned that describes the new process.

Process exec(String comLineArray[ ], String environment[ ]) throws IOException

Executes the command line specified by the strings in comLineArray as a separate process with the environment specified by environment. An object of type Process is returned that describes the new process.

void exit(int exitCode)

Halts execution and returns the value of exitCode to the parent process. By convention, 0 indicates normal termination. All other values indicate some form of error.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Runtime -class
249

Method

Description

long freeMemory( )

Returns the approximate number of bytes of free memory available to the Java run-time system.
Initiates garbage collection. Returns the current Runtime object. Immediately terminates the Java virtual machine. No termination threads or finalizers are run. The value of code is returned to the invoking process. Loads the dynamic library whose file is specified by libraryFileName, which must specify its complete path.

void gc( ) static Runtime getRuntime( ) void halt(int code)

void load(String libraryFileName)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Runtime -class
250

Method void loadLibrary(String libraryName)

Description Loads the dynamic library whose name is associated with libraryName.

boolean removeShutdownHook(Thread thrd)

Removes thrd from the list of threads to run when the Java virtual machine terminates. It returns true if successful that is, if the thread was removed.
Initiates calls to the finalize( ) methods of unused but not yet recycled objects. Returns the total number of bytes of memory available to the program.

void runFinalization( )

long totalMemory( )

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Runtime -class
251

Method void traceInstructions(boolean traceOn)

Description Turns on or off instruction tracing, depending upon the value of traceOn. If traceOn is true, the trace is displayed. If it is false, tracing is turned off.

void traceMethodCalls(boolean traceOn)

Turns on or off method call tracing, depending upon the value of traceOn. If traceOn is true, the trace is displayed. If it is false, tracing is turned off.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Memory Management
252

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 memory.
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Memory Management
253

Showing memory operations using Runtime class..using totalMemory (),freeMemor y() 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);

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Memory Management
254

Showing memory operations using Runtime class..using totalMemory (),freeMemor y() and gc()

for(int i=0; i<1000; i++) someints[i] = new Integer(i); // allocate integers Total memory is: 1048568 mem2 = r.freeMemory(); memory: 751392 Initial free System.out.println("Free memory garbage collection:mem2); Free memory after after allocation: + 841424 Free memory used by allocation: + (mem1-mem2)); System.out.println("Memory after allocation: 824000 Memory used by allocation: 17424 for(int i=0; i<1000; i++) someints[i] = null; discarded Integers: Free memory after collecting r.gc(); 842640 mem2 = r.freeMemory(); System.out.println("Free memory after collecting" +" discarded Integers: "+ mem2); } }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Executing Other Programs


255

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( adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com ) is inherently environment-dependent.

Executing Other Programs


256

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."); } } }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Executing Other Programs


257

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.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Executing Other Programs


258

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()); } }
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

System
259

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.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

System
260

Method
static void arraycopy(Object source,int sourceStart,Object target,int targetStart,int size)

Description
Copies an array. The array to be copied is passed in source, and the index at which point the copy will begin within source is passed in sourceStart. The array that will receive the copy is passed in target, and the index at which point the copy will begin within target is passed in targetStart. size is the number of elements that are copied. Returns the current time in terms of milliseconds since midnight, January 1, 1970. Halts execution and returns the value of exitCode to the parent process (usually the operating system). By convention, 0 indicates normal termination. All other values indicate some form of error.

static long currentTimeMillis( ) static void exit(int exitCode)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

currentTimeMillis( )
261

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++) ;
Timing a for loop from 0 to 1,000,000 end = System.currentTimeMillis(); // get ending time Elapsed time: 10

System.out.println("Elapsed time: " + (end-start)); } }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

arraycopy( )
262

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)); } } adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

a = ABCDEFGHIJ b = MMMMMMMMMM a = ABCDEFGHIJ b = ABCDEFGHIJ a = AABCDEFGHI b = BCDEFGHIJJ

Class-class
263

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.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Class-class
264

Impotant methods forName() getClass() boolean isInterface( ) String getName( )

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Class-class
265

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Class-class
266

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

267

java.util package(part-1) Collection


By Adrish Bhattacharyay Ardent Collaborations

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Collection Framework
268

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 adrish.b@ardentcollaborations.com

of the most common abstractions, without burdening the programmer with too

http://www.ardentcollaborations.com

Overview
269

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com 19-269

Overview (contd)
270

Collection, Iterator Lists, ListIterator

Sets

List ArrayList LinkedList

Set TreeSet HashSet Map TreeMap HashMap

Maps

Stack Queue, PriorityQueue

All these interfaces and classes are part of the java.util package. Names of interfaces are in italics.
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com 19-270

interface

Collection

Overvie w

interface

interface

List

Set

ArrayList

LinkedList

TreeSet

HashSet

interface

Queue
interface

Map Stack PriorityQueue TreeMap


Collection Set TreeSet HashSet List ArrayList LinkedList

HashMap

interface

Iterator
interface

Comparable
interface TreeSet TreeMap PriorityQueue

ListIterator

interface

Comparator

271

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Overview (contd)
272

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).

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Collection, Iterator
273

interface Iterator

interface Collection

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 collections iterator method); the traversal sequence depends on the adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com collection. 19-273

Collection<E> Methods
274

interface Iterator

interface Collection

boolean isEmpty () int size () boolean contains (Object obj) boolean add (E obj) boolean remove (E obj) Iterator<E> iterator () // ... other methods

Supplies an iterator for this collection

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com 19-274

Iterator<E> Methods
275

interface Iterator

interface Collection

boolean hasNext () E next () void remove ()

Whats next is determined by a particular collection

Removes the last visited element

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com 19-275

Iterator For Each Loop


276

Collection<String> words = new ArrayList<String>(); ... for (String word : words) { < ... process word > } Iterator<String> iter = words.iterator(); while (iter.hasNext ()) { String word = iter.next (); < ... process word > }

A for each loop is a syntactic shortcut that replaces an iterator


adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Format of Code
277

Collection collection = ...; Iterator iterator = collection.iterator(); while (iterator.hasNext()) { Object element = iterator.next(); if (removalCheck(element)) { iterator.remove(); } }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Lists, ListIterator
278

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)

Lists (contd)
279

interface Iterator

interface Collection

interface ListIterator

interface List

interface Set

ArrayList

LinkedList

etc.

List<E> Methods
280

interface Iterator

interface Collection

// 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)

interface ListIterator

interface List

Returns a ListIterator that starts iterations at index i

19

ListIterator<E> Methods

interface Iterator

interface Collection

interface ListIterator

interface List

// The three Iterator<E> methods, plus: int nextIndex () boolean hasPrevious () Can traverse the E previous () list backward int previousIndex () void add (E obj) Can add elements to the list (inserts void set (E obj) after the last visited element) Can change elements (changes the last visited element)

Demo Code
282

List list = ...; ListIterator iterator = list.listIterator(list.size()); while (iterator.hasPrevious()) { Object element = iterator.previous(); // Process element }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

ArrayList
19

interface Iterator

interface List

interface ListIterator

ArrayList

LinkedList

Represents a list as a dynamic array (array that is resized when full) Provides random access to the elements
a0 a1 a2 ... an-1

Implements all the methods of List<E>

java.util.ArrayList<E>
284

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)
capacity size
"Cat" "Hat" "Bat"

...

ArrayList Generics
285

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

ArrayList<E> Constructors
286

Java docs use the letter E as the type parameter for elements in generic collections

ArrayList<E> ( )

Creates an empty ArrayList<E> of default capacity (ten)

ArrayList<E> (int capacity)

Creates an empty ArrayList<E> of the specified capacity

287

ArrayList<E> Methods (a Subset)


int size()

boolean isEmpty ()
boolean add (E obj) void add (int i, E obj)
returns true
inserts obj as the i-th value; i must be from 0 to size() i must be from 0 to size() -1

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

ArrayList Example
288

ArrayList<String> names = new ArrayList<String>( ); names.add("Ben"); names.add("Cat"); names.add(0, "Amy"); System.out.println(names);


Output

[Amy, Ben, Cat]

ArrayLists toString method returns a string of all the elements, separated by commas, within [ ].

ArrayList<E> Details
289

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 when i < 0 or i size() (or i > size() in add (i, obj) )

LinkedList
290

interface Iterator

interface List

interface ListIterator

ArrayList

LinkedList

Represents a list as a doubly-linked list with a header node


header

a0

a1

a2

...

an-1

Implements all the methods of List<E>

291

LinkedList (contd)

interface Iterator

interface List

interface ListIterator

ArrayList

LinkedList

Additional methods specific to LinkedList:


void addFirst (E obj) void addLast (E obj) E getFirst () E getLast () E removeFirst () E removeLast ()

Singly-Linked List
292

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)
head value 0 value 1 value 2

value ...

value n-1

Singly-Linked List (contd)


293

public class ListNode { private Object value; private ListNode next;

Represents a node of a singly-linked list A reference to the next node

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

Singly-Linked List Example 1


294

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); } x head value 0 value 1 value 2

value ...

value n-1

Singly-Linked List Example 2


295

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

node
head
A B C D

null

null

Singly-Linked List Traversal


296

public void printList (ListNode head) { for (ListNode node = head; node != null; node = node.getNext ()) System.out.println (node.getValue ()); }

Singly-Linked List with a Tail


297

Keeps a reference to the last node Suitable for implementing a queue

head

tail

value 0

value 1

value 2
value n-1

value ...

Doubly-Linked List
298

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
head
a0 a1 a2 ... an-1

tail

Doubly-Linked Circular List


299

next in the last node points to the first node previous in the first node points to the last node
head
a0
a1 a2

...

an-1

300

Doubly-Linked Circular List with a Header Node

Thats how java.util.LinkedList is implemented


private ListNode2 header;

a field in the DoublyLinkedList class

a0

a1

a2

...

an-1

ArrayList
301

vs. LinkedList

Implements a list as an array

Implements a list as a doubly-linked list with a header node

+ Provides random access to the elements

- No random access to the elements needs to traverse the list to get to the i-th element + Inserting and removing elements is done by rearranging the links no shifting + Nodes are allocated and released as necessary

Inserting and removing elements requires shifting of subsequent elements

- Needs to be resized when runs out of space

ArrayList vs. LinkedList (contd)


302

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) { ... }

Works well for an ArrayList O(n) inefficient for a LinkedList O(n2)

Work well for both an ArrayList and a LinkedList O(n)

List Example
303

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

List Example
304

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

adrish.b@ardentcollaborations.com } http://www.ardentcollaborations.com

Vector
305

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. constructors Vector<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

Vector -Example
306

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

Vector
307

java.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 capacity names.ensureCapacity(150); // Set minimum capacity to 150 int freeCount = names.capacity() names.size();//counting free space String name = names.get(4);//retrieving from vector

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Stacks
308

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

Stack<E> Methods
309

Stack

boolean isEmpty () E push (E obj) E pop () E peek ()

Returns obj; use as void Returns the top element without removing it from the stack

Queues
310

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)

Queues (contd)
311

interface Queue

LinkedList

Queue<E> Methods
312

interface Queue

LinkedList

boolean isEmpty () boolean add (E obj) E remove () E peek ()

Returns the first element without removing it from the queue

Queues (contd)
313

Queue<Message> q = new LinkedList<Message> ();

Methods have been added to LinkedList to implement the Queue interface: add == addLast remove == removeFirst peek == getFirst All of the above work in O(1) time

Priority Queues
314

In a priority queue, items are processed NOT in order of arrival, but in order of priority. java.util:
Queue

interface PriorityQueue (implements Queue)

Priority Queues (contd)


315

interface Queue

PriorityQueue

The same methods as in Queue: isEmpty, add, remove, peek.

316

PriorityQueue<E> Class

interface Queue

PriorityQueue

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

Stack
317

Queue
push remove add

pop

LIFO (Last-In-First-Out) access method

FIFO (First-In-First-Out) access method

Stacks and queues are used for temporary storage, but in different situations

Stacks are Used for


318

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

319

Stack: Array Implementation


myElements[5] myElements[4] myElements[3] myElements[2] myElements[1] myElements[0] Stack pointer value3 value2 value1 value0 sp

public void push (Object x) { myElements [sp] = x; sp++; } public Object pop ( ) { sp--; return myElements [sp]; }

ArrayList Implementation
320

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

LinkedList Implementation
321

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

Properties of Stacks
322

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).

java.util.Stack class
323

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!

Stack Example: Matching Brackets


324

public boolean bracketsMatch (String str) import java.util.Stack; { Stack<Integer> stk = new Stack<Integer> (); for (int pos = 0; pos < str.length(); pos++) { if (str.charAt (pos) == ' [ ' ) ) stk.push (pos); Autoboxing else if (str.charAt (pos) == ' ] ' )) (Save pos of ' [ ) { if (stk.isEmpty ()) return false; Autounboxing int pos0 = stk.pop (); System.out.println (pos0 + " - " + pos); } } return stk.isEmpty (); }

Stack Example:Traversing a Tree


325

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 ()); Save for future node = node.getLeft (); processing } else if (node.getRight () != null ) node = node.getRight (); else if (! stk.isEmpty ()) node = stk.pop (); if no children, else take the next node = null; node from the } stack

Queues are used for:


326

Processing events or messages in order of their arrival System tasks


Queueing

print jobs Entering keystrokes Processing mouse clicks

Queue: Ring-Buffer Implementation


327

Before: front 1 1 2 3 5 8 13 rear

After: (removed 1, 1; inserted 21, 34, 55) rear 55 front 2 3 5 8 13 21 34

Properties of Queues
328

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).

The java.util.Queue Interface


329

boolean isEmpty () boolean add (E obj) E remove () E peek ()

A generic interface, part of the Java Collections Framework Implemented by java.util.LinkedList

Queue Example
330

public Queue<String> findMatches (Scanner input, String target) { Queue<String> q = new LinkedList<String>(); while (input.hasNextLine ()) Returns a queue of { all the lines that String line = input.nextLine (); contain target if (line.indexOf (target) >= 0 ) q.add (line); } public void process (Queue<String> q) return q; { } while (! q.isEmpty ()) { Processes the String s = q.remove (); contents of q ... // process s (leaves the } queue empty) }

Sets
331

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

Sets (contd)
332

interface Iterator

interface Collection

interface Set

Methods of Set<E> are the same as methods of Collection<E>


TreeSet HashSet

Sets semantics are different from Collection (no duplicates), but Set does not add any new methods.

TreeSet<E>
333

interface Set

TreeSet

HashSet

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

HashSet<E>
334

interface Set

TreeSet

HashSet

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

Example1
335

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

adrish.b@ardentcollaborations.com } http://www.ardentcollaborations.com

Example 2<with Generics>


336

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;
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Example 2<with Generics>


337

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(); NOTICE : Unlike Set, List permits while(it.hasNext()){ } } }
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

duplicates.

System.out.println(it.next());

Maps
338

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

Maps (contd)
339

java.util:
Map

interface TreeMap HashMap

interface Map

TreeMap

HashMap

Map<K, V> Methods


340

interface Map

TreeMap

HashMap

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

TreeMap<K,V>
341

interface Map

TreeMap

HashSet

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

HashMap<K,V>
342

interface Map

TreeMap

HashMap

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

Miscellaneous Example1
343

ArrayList

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

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

Miscellaneous Example1
344

ArrayList

Long l = (Long) al.get(2); System.out.println( "s = "+s ); System.out.println( "l = "+l.intValue() ); } }


s = String l=5

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Miscellaneous Example2
345

LinkedList

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

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

Miscellaneous Example2
346

LinkedList

String first = (String)ll.getFirst(); String last = (String)ll.getLast(); System.out.println( "First:"+ first ); System.out.println( "Last :"+ last ); } }
First: First Element Last: Last Element

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Miscellaneous Example3
347

import java.util.*; public class HashSetSample { public static void main( String [] args ) {

HashSet

HashSet hs = new HashSet();


hs.add("B"); hs.add("A"); hs.add("A");
hs: [A, 7, B]

hs.add( new Long(7) );


System.out.println( "hs:"+ hs ); }

adrish.b@ardentcollaborations.com } http://www.ardentcollaborations.com

Miscellaneous Example4
348

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: [A, B, C]

TreeSet

//ts.add( new Long(7) );


System.out.println( "ts:"+ ts ); }

adrish.b@ardentcollaborations.com } http://www.ardentcollaborations.com

Miscellaneous Example5
349

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Miscellaneous Example5
350

Iterator

while ( i.hasNext() ) { System.out.println( "Item: "+i.next() ); } } }


Item: 3 Item: 5 Item: 7

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Miscellaneous Example6
351

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() ) {

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Miscellaneous Example6
352

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(", "); } } }
753 357

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Miscellaneous Example7
353

HashMap

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

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

Miscellaneous Example7
354

HashMap

while ( i.hasNext() ) { Map.Entry me = (Map.Entry)i.next(); System.out.print("KEY: "+me.getKey()); System.out.println(",VAL: "+me.getValue()); } } KEY: Key, VAL: 2 }
KEY: 5, VAL: Value

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Miscellaneous Example8
355

TreeMap

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

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

Miscellaneous Example8
356

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.getValue()); KEY: AKEY, VALUE: 1 } KEY: BKEY, VALUE: 2 } KEY: CKEY, VALUE: Just a String }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Miscellaneous Example9
357

Comparator

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

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;

Miscellaneous Example9
358

Comparator

if ( ( ra == 0 && rb == 1 ) || la < lb ) return -1; else if ( ( rb == 0 && ra == 1 ) || la > lb ) return 1; return 1; } }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Miscellaneous Example9
359

Comparator

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

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

Miscellaneous Example9
360

Comparator

ts.add( new Long(10) ); Iterator i = ts.iterator(); while ( i.hasNext() ) { System.out.print(i.next()); if (i.hasNext()) System.out.print(", "); } 6, 10, 1, 5 } }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Miscellaneous Example10
361

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));
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Miscellaneous Example10
362

vector.addElement(new Integer(6));
Vector

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."); }
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

363

java.util package(part-2)-Utility Classes


By Adrish Bhattacharyay Ardent Collaborations

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

StringTokenizer
364

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.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

StringTokenizer Constructors
365

StringTokenizer(String str) StringTokenizer(String str, String delimiters) StringTokenizer(String str, String delimiters, boolean delimAsToken)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

StringTokenizer-methods
366

Method int countTokens( ) delimiters, the tokens returns the result.

Description Using the current set of method determines the number of left to be parsed and Returns true if one or remain in the string and there are none. Returns true if one or remain in the string and there are none.

boolean hasMoreElements( ) more tokens returns false if boolean hasMoreTokens( ) more tokens returns false if

Object nextElement( )
String nextToken( ) String nextToken(String delimiters) and specified

Returns the next token as an Object.


Returns the next token as a String. Returns the next token as a String sets the delimiters string to that

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

StringTokenizer
367

Program demostrating StringTokeniz er methods

import java.util.StringTokenizer; class STDemo { static String in = "name=Adrish Bhattacharyay;" + "address=Chandannagar;" + "email=adrish.b@ardentcollaborations.com;" + "Qualification=B.Tech";

public static void main(String args[]) {


StringTokenizer st = new StringTokenizer(in, "=;"); while(st.hasMoreTokens()) {

name Adrish Bhattacharyay address Chandannagar String key = st.nextToken(); email String val = st.nextToken(); adrish.b@ardentcollaborations.com System.out.println(key + "\t" + val); Qualification B.Tech
} }}
adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

BitSet
368

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)

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

BitSet methods
369

Method void and(BitSet bitSet) result

Description ANDs the contents of the invoking BitSet object with those specified by bitSet. The is placed into the invoking object.

void andNot(BitSet bitSet) corresponding bit in int cardinality( ) in the invoking

For each 1 bit in bitSet, the the invoking BitSet is cleared.

Returns the number of set bits

object.

void clear( ) void clear(int index)

Zeros all bits. Zeros the bit specified by index. endIndex) Zeros the bits from startIndex to 1).

void clear(int startIndex,int adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com (endIndex

BitSet methods
370

Method Object clone( ) object. boolean equals(Object bitSet) equivalent bitSet.Otherwise, the

Description Duplicates the invoking BitSet Returns true if the invoking bit set is to the one passed in method returns false.

boolean get(int index)

Returns the current state of the bit at the


specified index. Returns a BitSet that consists of from startIndex to endIndex object is not changed.

BitSet get(int startIndex,int endIndex) the bits 1. The invoking boolean intersects(BitSet bitSet) invoking object

Returns true if at least one pair of corresponding bits within the and bitSet are 1.

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

BitSet methods
371

Method int length( ) value

Description Returns the number of bits required to hold

the contents of the invoking BitSet. This


is determined by the location of the last 1 bit.

void or(BitSet bitSet) object

ORs the contents of the invoking BitSet with that specified by bitSet. The result is placed into the invoking object.

int size( ) String toString( ) void xor(BitSet bitSet)


adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Returns the number of bits in the invoking BitSet object. Returns the string equivalent of the invoking BitSet object. XORs the contents of the invoking BitSet object with that specified by bitSet. The result

BitSet Example
372

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

BitSet Example
373

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: ");

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

BitSet Example
374

System.out.println(bits2);

// XOR bits
bits2.xor(bits1); System.out.println("\nbits2 XOR bits1: "); System.out.println(bits2); } }
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: {}

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Date
375

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

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Date
376

long msec = date.getTime();

System.out.println("Milliseconds since Jan. 1, 1970 GMT = " + msec);


} }

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

Calender
377

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.MO NTH)]);

System.out.print(" " + calendar.get(Calendar.DATE) adrish.b@ardentcollaborations.com + " ");

http://www.ardentcollaborations.com

System.out.println(calendar.get(Calendar.YEAR));

Calender
378

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

adrish.b@ardentcollaborations.com } http://www.ardentcollaborations.com

java.io package
379
By Adrish Bhattacharyay Ardent Collaborations

adrish.b@ardentcollaborations.com http://www.ardentcollaborations.com

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.

Class hierarchy in java.io package

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.

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.

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.

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.

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.

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.

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) {

in.close(); } if (out != null) { out.close(); }

}
} }

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.

Reader and Writer

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.

java.io.Reader

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

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.

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.

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 read( ) read(char[] cbuf, int off, int len) readLine( )

Return Type int int

Description Reads a single character Read characters into a portion of an array. Read a line of text. A line is considered to be terminated by ('\n').

String

close( )

void

Closes the opened stream.

File I/O

The File class deals with the machine dependent files in a machine-independent manner i.e. it is easier to write platformindependent code that examines and manipulates files using the File class. This class is available in the java.io package.

What we can do?


Create a File Constructing a File Name path Read 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

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

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

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.

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

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.

FileWriter The 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 preexist 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 characteroutput stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings

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