56
0 JAVA OOPS Contents: S.No Topic Page Method Overloading 1 Static Keyword 2 Constructors 5 Inheritance 7 Method Overriding 12 Polymorphism 13 FinalKeyword 14 Abstract Classes 17 Packages 19 Practice Material on Interfaces 20 Interfaces 21 Arrays 25 Strings 31 Programs on StringBuffer 35 Exception Handling 37 Inner Classes 46 Multithreading 49

Core Java SoftCopy

Embed Size (px)

Citation preview

Page 1: Core Java SoftCopy

0

JAVA OOPS

Contents:

S.No Topic Page Method Overloading 1 Static Keyword 2 Constructors 5 Inheritance 7 Method Overriding 12 Polymorphism 13 FinalKeyword 14 Abstract Classes 17 Packages 19 Practice Material on Interfaces 20 Interfaces 21 Arrays 25 Strings 31 Programs on StringBuffer 35 Exception Handling 37 Inner Classes 46 Multithreading 49

Page 2: Core Java SoftCopy

1

Java OOPS

Method Overloading

If you define two methods with the same method name (signature) in a C- language file, it is a compilation error. That is the following two methods lead to a compilation error in C. 1st Method: void display() { // code } 2nd Method: void display(int x) { //code } Observe that, both the above methods have the same method name but differs only in parameters (the first method does not contain any parameters and the second one contains one parameters). The same above methods, if written in a OOPs language like C++ or Java, it is not a compilation error. What is Method Overloading? Reusing the same method name, with different arguments and with the same or different return type is called Method Overloading. When overload methods are called, compiler differentiates the methods depending on their number, type and sequence of parameters. Return type will not be considered in differentiating the methods by the compiler. 1st Method: void display () { //code } 2nd Method: int display () { //code } Even though the return types are different in the above two methods, it is a compilation error. Where method Overloading is useful? The OOPs concept, method overloading avoids the usage of several method names that perform closely related jobs (functionality). That is to say method overloading eliminates the need for entirely different methods that do essentially the same thing. Overloading also makes it possible for methods to behave differently based on the arguments they receive. What is Method Signature? Method signature includes method name, number of arguments and type of arguments but does not include written type. That is methods with a different type of return value and having the same name will be considered as the same method by the compiler and if exists in the same class, it is an error. IN THIS PROGRAM: Practicing Overloaded Methods using Math.sqrt class File Name: OverloadDemo.java Public class OverloadDemo { Public void area(int x) { //first method System.out.println(“The area of the circle is “+Math.Pl *x*x); } public void area(String figure,int x) { //2nd method

Page 3: Core Java SoftCopy

2

if(figure.equals(“circle”)) System.out.println(The area of the is”+Math.Pl*x*x);

else if(figure.equals(“square”)) System.out.println(“The area of the circle is”+x*x); Else System.out.println(“Please pass either circle or square only as argument”);

} public int area(int l,int b) { //3rd method

return l*b; }

public float area(int a,int b,int c) { //4th method double s=(a+b+c) / 2; return(float)(s*Math.sqrt((s-a)*(s-b)*(s-c));

} public double area(int a,int b,double c) { double s=(a+b+c) / 2; return s*Math.sqrt((s-a)*(s-b)*(s-c));

} public static void main(String args[]) { OverloadDemo od=new OveloadDemo();

Od.area(5); //invokes 1st method Od.area(“circle”,7) //invokes 2nd method Od.area(“squre”,4); //invokes 2nd method Od.area(“triangle”,10); //invokes 2nd method System.out.println(“The area of the rectangle is”+od.area(20,10));//3rd method System.out.println(“The area of the triangle is”+Math.cell(od.area(3,4,5)));//4th System.out.println(“The area of the triangle is”+Math.round(od.area(3,4,5,6,7)));//5th } }

Output: The area of the circle is 78.53981633974483 The area of the circle is 153.9380400258995 The area of the circle is 16 Please pass either circle or square only as argument The area of the rectangle is 200 The area of the triangle is 16.0 The area of the triangle is 14

In the above program area () method is overloaded. Math is a class defined in the in the package java.lang which is imported by default by the JVM (Java Virtual Machine). Math Class includes many static methods like round (), floor () etc., Student is advised to refer to Java documentation for more methods and for in depth knowledge of Math class.

Static Keyword

Static keyword functions differently with keywords, methods and classes. We will explore each one by one. Using Static Keyword with Variables: With instance variable, each new instance (object) of the class gets a new copy of the instance variables. Even though the instance variable is one, each instance enjoys its own copy of the variable and variable one instance cannot change the variable of the other reason being they occupy different memory locations. This is made clear to you in my class Employee program where emp1.basic and emp2.basic are different identities occupying different memory locations and emp1.basic can never

Page 4: Core Java SoftCopy

3

access emp2.basic and one cannot corrupt the other even the instance variable basic is one and same between emp1 and emp2 objects. There may be a situation where one instance variable may be shared by all instances of the class. That is every instance of the class must refer (share) to the same instance variable and changing the value of that variable changes it for all instance of the class. You define these variables as static. Static variable occupy only one memory location irrespective of the numbers of instances calling the variable. IN THIS PROGRAM: Using static keyword with an instance vairiable. File Name: StaticDemo.java Public class StaticDemo { Int x=10; Static int y=20; Public static void main(String args[]) { //System.out.println(“Value of x is”+x);this is an error as instance variable can‟t be called directly System.out.println(“Value of y is”+y); //can be called directly s it is static StaticDemo sd=new StaticDemo(); System.out.println(“\nCalling with an instance:”); System.out.println(“Value of x is ”+sd.x); System.out.println(“Value of x is”+sd.y); System.out.println(“\nThree ways of Calling a static variable:”); System.out.println(“Directly calling:”+y); System.out.println(“\nCalling with an instance:”+sd.y); System.out.println(“\nCalling with class name:”+StaticDemo.y); } } Output: Value of y is 20 Calling with an instance: Value of y is 10 Value of y is 20 Three ways of Calling a static variable Directly calling:20 Calling with an instance:20 Calling with class name:20 IN THIS PROGRAM: Another example using static keyword with variable File Name: StaticDemo1.java Public class StaticDemo1 { Static int x=10; Public static void main(String args[]) { System.out.println(“Value of x is”+x); //prints 10 StaticDemo1 sd1=new StaticDemo1(); StaticDemo1 sd2=new StaticDemo1(); StaticDemo1 sd3=new StaticDemo1(); System.out.println(sd1.x); //prints 10 X=20;

Page 5: Core Java SoftCopy

4

System.out.println(x); //prints 20 System.out.println(sd1.x); //prints 20 Sd2.x=30; System.out.println(sd2.x); //prints 30 System.out.println(sd3.x); //prints 30 } } In the above program, the change in the value of the static variable x, affects the entire program. A static variable can be re-assigned without the help of an instance also. Using static keyword with Methods: Generally, a method in a class should be called with an object (instance) only, like emp1.computeAndDisplay() in my earlier Employee program. If the keyword static is used within a method signature, the method can be called without the need of an instance. IN THIS PROGRAM: using static with method. File Name: StaticMethod.java Public class StaticMethod { Public void display() { System.out.println(“From display”); } public static void show() { System.out.println(“From show”); } public static void main(String args[]) { //display(); //error,should be called with an instance only as as it is not static show(); //no error,can be called directly as it static(1st way of calling) StaticMethod sm=new StaticMethod(); Sm.display(); //no error Sm.show(); //static method can be called with instance also(2nd way of calling) StaticMethod.show(); //can be called with classname also(3rd way calling) //observe how many ways a static method can be called----it is 3 ways } } output: From show From display From show From show Can a local variable be static? No, a local variable can never be static and if so, it is a compilation error. A static variable is also called a class variable as whole class can access the same variable. Always static implies to whole class. If local variable is static, the meaning and purpose of static is lost. Points to remember about static variables:

1. They have the same value for all objects of the class. 2. They are in a common memory location which all objects of that class can refer to. 3. They can be accessed without objects. 4. They can not be made persistent.

Page 6: Core Java SoftCopy

5

Points to remember about static Methods:

1. Static methods can be accessed without objects. 2. Static methods can use only static variables. 3. Static methods can be called from static methods only.

Constructors

What is a Constructor? A constructor looks like a method and is called implicitly by an object when it is created (by new keyword). Unlike methods, a constructor cannot be called directly. Instead, java calls constructors automatically. Constructors should be declared before any methods in a class. Java does three things when new is used to create an instance of a class:

Allocates memory for the object

Initializes that object‟s instance variables, either to initial values or to a default (0 for numbers, Null for objects, False for Booleans, or „\0‟ for characters).

Calls the constructor method of the class, which might be one of several methods. Constructors look a lot like regular method with two basic differences:

Constructor always have the same name as that of class

Constructor doesn‟t have a return type (even void). NOTE: Constructors are not methods. Nor are they members. Overloading the Constructors: IN THIS PROGRAM: To overload a Constructor. FILE NAME : Rectangle.java Public class Rectangle { Public Rectangle() { //1st constructor System.out.println(“From Default constructor”); } public Rectangle(int x) { //2nd constructor

System.out.println(“Area with one parameter:”+x*x); } public Rectangle(double x) { //3rd constructor

System.out.println(“Area with one parameter:”+x*x); } public Rectangle(int x,int y) { //4th constructor System.out.println(“Area with two parameters:”+x*y); } public Rectangle(int x,double y) { //5th constructor System.out.println(“Area with two parameters:”+x*y); } public Rectangle(double x,int y) { //6th constructor System.out.println(“Area with two parameters:”+x*y); } public static void main(String argd[]) { System.out.println(“Overloading the constructors……\n”);

Page 7: Core Java SoftCopy

6

Rectangle rect1=new Rectangle(); //1st constructor is called Rectangle rect2=new Rectangle(5); //2nd constructor is called Rectangle rect3=new Rectangle(4.5); //3rd constructor is called Rectangle rect4=new Rectangle(4,5); //4th constructor is called Rectangle rect5=new Rectangle(4,5.5); //5th constructor is called Rectangle rect6=new Rectangle(5.5,4); //6th constructor is called

System.out.println(“Overloading the constructor is over”); }

} Output: Overloading the constructors…… From the default constructor Area with one parameters :25 Area with one parameters :20.25 Area with two parameters :20 Area with two parameters :22.0 Area with two parameters :22.0 Overloading the constructor is over Default Constructor: Constructor without arguments (or no-arguments) is called default constructor. If a default constructor is not provided by the programmer, automatically one will be created by the JVM and supplied. For example, in your earlier program Employee.java you have created an object emp1 as follows: Employee emp1 = New employee (); Where you have not provided a constructor like Public employee(). In spite of it, your program worked nice as one is created by the system and implicitly included your program. To call one Constructor from another Constructor in the same class: As stated earlier, constructors cannot be called just like methods. Instead constructors are called automatically when objects (instances) are created. I can say the same in a different fashion: The birth place of object is a constructor. Java provides a special syntax for calling a constructor from another. Use this (arg1, arg2, arg3) in a any constructor and that particular constructor will be called which matches the parameters of this (). this () must be first statement in a constructor public class Cloth { public Cloth () { //1st constructor System.out.println(“from default constructor”); } public Cloth(String name) { //2nd constructor

this (); //this calls1st constructor System.out.println(“Hello Mr.” + name+”, do you want Cloth?”); } public Cloth (int meters) { //3rd constructor this (“Bhaskar”); //this calls 2nd constructor System.out.println(“Do you want”+Meters+”Meters Cloth?”); }

Page 8: Core Java SoftCopy

7

public static void main(String args []) { Cloth cloth1=new Cloth(); Cloth cloth2=new Cloth(“Jack”); Cloth cloth3=new Cloth(5); } } Output: From default constructor From default constructor Hello Mr. Ramakanth, do you want cloth? From default constructor Hello Mr. Bhaskar, do you want cloth? Do you want 5 meters cloth?

Inheritance Inheritance is one of the most crucial steps in object – oriented programming, and it has a direct effect on how you design and write your own java classes. What is Inheritance? Inheritance is a mechanism that enables one class to inherit all of the behavior (methods) and attributes (instance variables) of another class. A class that inherits from another class is a Subclass and the class that gives the inheritance is called Superclass. A class can have only superclass (as multiple inheritance is not supported by java), but each class can have an unlimited number of subclasses. Subclasses inherit all the attributes and behavior of the superclasses. What are the advantages of Inheritance? With inheritance code duplication is avoided by reusing the code(attributes and methods) of one class in another class. You can derive new classes from already existing classes. IN THIS PROGRAM: using superclass method in a subclass. File Name: Rectangle1.java Class Quadrilateral { Public void area(int a,int b) { System.out.println(“Area is”+l*b+”sq.mts.”); } } public class Rectangle1 extends Quadrilateral { public static void main(String args[]) { Quadrilateral q1=new Quadrilateral(); Q1.area(5,4); Rectangle rect1=new Rectangle1(); Rect1.area(3,5); } } Output: Area is is 20 sq.mts. Area is 15 sq.mts. In the above example, the method area () belongs to the class Quadrilateral (called super class) and this method is used by the class Rectangle(called subclass) as if it is its. The code (here it is

Page 9: Core Java SoftCopy

8

method) of one class is used in another class. That is wherever we want area (),we can utilize the method. This phenomenon is called inheritance and inheritance is the best example for code reusability at its maximum. The above source code consists of two classes---one with main() and the other without main().The class with main should be declared public(if not provided, by default it is assumed) and the file name must the class name with main() method. IN THIS PROGRAM: using method and instance variables of a super class in a subclasses.

File Name: MathsBook.java class Book { Int qty; Double price; Public void amount(int qty,double price) { this.qty=qty;

this.price =price; System.out.println(“The bill amount is Rs.”+qty*price); } } class EnglishBook extends Book { } class TeluguBook extends Book { } public class MathsBook extends Book { public static void main(String args[]) { Book b=new Book(); b.amount(5,250.75); EnglishBook eb=new EnglishBook(); eb.amount(4,150); TeluguBook tb=new TeluguBook(); tb.amount(10,50.50); MathsBook mb=new MathsBook(); mb.amount(15,75.25); } } Output: The bill amount is Rs.1253.75 The bill amount is Rs.600.0 The bill amount is Rs.505.0 The bill amount is Rs.1128.75 In the above program, super class Book includes two instance variables qty and price and one method amount 0 which are used freely by its subclasses EnglishBook,TeluguBook etc. Behavior of Constructors in Inheritance: When a default constructor of a subclass is executed, the default constructor of the subclass will call the default constructor of superclass. After getting executed the superclass constructor only, the subclass constructor is executed. IN THIS PROGRAM: Demo on subclass constructor calling superclass constructor.

Page 10: Core Java SoftCopy

9

File Name: ConstructorDemo.java class A { public A() { System.out.println(“From A constructor”); }} class B extends A { public B() { System.out.println(“From B constructor”); }} class C extends B{ publc C() { System.out.println(“From C constructor”); }} class ConstructorDemo { public static void main(String args[]) { System.out.println(“Instance of class A is created:”); Aa=newA(); System.out.println(“\nInstance of class B is created:”); Bb=new B(); System.out.println(“\nInstance of class C is created:”); Cc=new C(); } } Output: Instance of class A is created From A constructor Instance of class B is created From A constructor From B constructor Instance of class C is created From A constructor From B constructor From C constructor Using super keyword in Inheritance:

1. super with Instance variables:

Super is a Java keyword used to refer the instance variables (non-static) of the parent class that are hidden by the current class.

IN THIS PROGRAM: using super keyword. File Name: Son.java class Father {

Page 11: Core Java SoftCopy

10

int age = 60; public void display_age() { System.out.println(“Son‟s age;” + age); } } public class Son extends Father { int age = 25; public void show_age() { System.out.println(“Son‟s age;”+age); System.out.println(“Using super: Son‟s age:” +super.age); } public static void main(Sting args[]) { Father f= new Father(); Son s = new Son(); f.display_age(); s.show_age(); } } Output: Father‟s age: 60 Son‟s age: 25 Using super: Son‟s age: 60 In the above program, both superclass and subclass have the same instance variable age. The instance variable age of subclass hides the instance variable age of superclass. When a superclass variable is hidden, it can be called from the subclass by using super keyword.

2. Super with Methods: When the same method signature exists in both the superclass and subclass, the superclass method is hidden by the subclass method. That is an object of subclass can not access the superclass method. In this situation of data hiding, super keyword can be used to access the superclass method.

IN THIS PROGRAM: Using super keywords with methods. File Name: Grape.java Class Cherry { Public void color() { System.out.println(“The color of Cherry is red”); } } public class Grape extends Cherry { public void color() { System.out.println(“The color of Grape is Green”); Super.color(); } public static void main(Strings args[]) { Cherry cherry = new Cherry(); Grape grape = new Grape(); System.out,println(“Calling Cherry‟s color method:”); Cherry.color(); System.out.println(“\nCalling Grape‟s color method:”);

Page 12: Core Java SoftCopy

11

Grape.color(): } } Output: Calling Cherry‟s color method: The color of Cherry is Red Calling Grape‟s color method: The color of Grape is green The color of Cherry is red Using super() in Inheritance: Super() is used to call a superclass constructor from a subclass constructor. Super() must be the first statement, if used, in a subclass constructor. If not, it is a compilation error. IN THIS PROGRAM: Using super () to access superclass constructor. File Name:Officer.java Class Worker { int basic, da, hra ; public Worker(int a, int b) { basic = a ; da = b ; System.out.println(“Worker‟s basic + da is Rs.” + (basic + da)); } public Worker(int a, int b, int c) { basic = a; da=b; hra = c; System.out.println(“Worker‟s basic + da + hra is Rs.” +(basic+da+hra)); } } public class Officer extends worker { public Officer(int p, int q) { super(p,q); System.out.println(“Officer‟s basic+da is Rs.”+(basic+da)); } public Officer(int p,int q,int r) { super(p,q,r); System.out.println(“Officer‟s basic+da+hra is Rs.”+(basic+da+hra)); } public static void main(Sting args[]) { System.out.println(“Worker constructors in action”); Worker w1=new Worker(3000 , 1500); Worker w2= new Worker(4000 , 1800, 500); System.out.println(“\nOfficer constructors in action:”); Officer o1=new Officer(10000 , 5000); Officer o2=new Officer(15000 , 6000 , 2000); } } Output: Worker constructors in action: Workers basic + da is Rs.4500 Worker‟s basic + da + hra is Rs. 6300 Officers constructors in action Worker‟s basic+da is Rs.15000

Page 13: Core Java SoftCopy

12

Officer.s basic+da is Rs.15000 Worker‟s basic+da+hra is Rs.23000 Officer‟s basic+da+hra is Rs.23000

Method Overriding Method overriding involves inheritance. Method overriding occurs when a class declares a method that has the same type of signature as a method declared by one of its superclasses. Method overriding is a very important capability because it forms the basis for run-time polymorphism. The new method hides the method of the super class.

A super class reference variable can be used to refer to a subclass object. The actual version of an overridden method that is executed is determined at run-time, not at a compile time. Note: The dynamic method dispatch resolves calls to overridden methods at run-time. In the following program hello () method is used for overriding. The method is overridden in both the subclasses. IN THIS PROGRAM: Using method overriding. File Name: MethodOverridding.java class A { void hello() { System.out.println(“Hello from A”); } } class B extends A { void Hello() { System.out.println(“Hello from B”); } } class C extends B { void Hello() { System.out.println(“Hello from C”); } } public class Method Overridding1 { public static void main(String args[]) { C c = new C(); //A c = new C(); c hello(); } } Output: Hello from C A c = new C(); In this statement c is an object reference variable of type A, but assigned with an object of C. The statement can be also written as A c; c = new C(); or new C() hello(); A subclass object can be assigned to a superclass reference variable. Abstract methods cannot be private but can be protected. While overriding a protected abstract method, the overridden method can not be more restrictive (in access).

Page 14: Core Java SoftCopy

13

Always a member of a class (variable and method) can be inherited. Constructor is not member and can not be inherited (but can be accessed). Also Constructors cannot be native, abstract, final, synchronized or static.

Polimorphism Or Dynamic (Late) Binding Polymorphism is an OOPS concept and means that different objects respond distinctively to the same message. In Dynamic Binding, the interpreter resides which method is linked to the same object reference variable at run-time. IN THIS PROGRAM: Illustrating Polymorphism File Name : PolymorphismDemo.java class DesignRules public void design() { System.out.println(“Call me by name, I give you different designs at different places”); }} class House extence DesignRules { public void design() { System.out.println(“The House should consist of a kitchen and Bedroom”); }} class Factory extence DesignRules { public void design() { System.out.println(“The Factory should provide a fire alarm, siren and canteen”); }} class FunctionHall extence DesignRules() { public void design(){ System.out.println(“The functionhall shoul include kitchen, Dining hall, Weddinghall”); }} public class PolymorphicDemo{ public static void main (String args[]) { DesignRules dr ; //dr is a reference variable House house = new House (); Factory factory = new Factory(); Functionhall fn = new Functionhall(); dr = House; dr.design(); dr = Factory; dr.design(); dr = fn; dr.design(); System.out.println(“Iam from main, designs are over sir”); }} Output: The House should consist of a kitchen and Bedroom The Factory should provide a fire alarm, siren and canteen The functionhall shoul include kitchen, Dining hall, Weddinghall Iam from main, designs are over sir The Same output can be obtained by making class DesignRules as abstract and making its method abstract. In Inheritance, only one class should be public that contains the main method. Other should not be public and doing so is a compilation error.

Final Keyword

Page 15: Core Java SoftCopy

14

final keyword behaves differently with variables, methods and classes. We will see each. final with variables: final variables cannot be reassigned.final variables are like constant variables(const int x=20) of C-language. IN THIS PROGRAM: using final keyword with variables. File Name: FinalVariableDemo.java Public class FinalVariableDemo { Public static void main(String args[]) { int x=10; final int y=20; System.out.println(“Values before changing”); System.out.println(x); //prints 10 System.out.println(y); //print 20 x=100; //y=200 //compilation error.can‟t assign a value to a final variable System.out.println(x); } } final with methods: final keyword is invoked with methods and classes in inheritance. Final methods declared in a superclass can not be overridden in a subclass. A class declared as final can not be subclassed. This will be clear with the following two programs. IN THIS PROGRAM: final keyword with methods. File Name: FinalMethodDemo.java Class FinalMethod { Public void display() { System.out.println(“From display of super class”); } public final void show() { System.out.println(“From show of super class”); } } public class FinalMethodDemo extends FinalMethod { public void display() { System.out.println(“From display of subclass”); } /* public void show() { //error as final methods can not be subclassed System.out.println(“From show of subclass”); } */ public static void main(String args[]) { FinalMethodDemo fmd=new FinalMethodDemo(); Fmd.display(); Fmd.show();

Page 16: Core Java SoftCopy

15

} } Output: From display of subclass From show of subclass final with class final class FinalClass { } public class FinalClassDemo extends FinalClass { } The program does not compile and complains:can‟t subclass final classes. Can an instance variable be final? Yes,an instance can be final.But no instance of the class can change the value.Following is the proof. Public class FinalClassDemo { Final int x=10; //final instance variable Public static void main(String args[]) { FinalClassDemo fmd=new FinalClassDemo(); System.out.println(“fmd.x); //fmd.x=100;//can‟t assign a value to a final variable System.out.println(fmd.x); } } Study of Access Modifers: Class Modifiers: There are three possible modifiers that may precede the class keyword Keyword Meaning Abstract cannot be instantiated Final cannot be extended Public can be accessed by any other class.If this

keyword is missing,the access to the class is limited to the current package,known as default package.

Variable Modifiers: There are seven possible modifiers that precede the declarations of a variable.

Keyword Meaning final is a constant

private can be accessed by the code within the same class

protected can be accessed by the code in a subclass or the same

public can be access by any class package static is not an instance variable(called as class

variable)

Page 17: Core Java SoftCopy

16

Method Modifers: There are eighth possible modifiers that may precede the declaration of a variable.

Keyword Meaning

final cannot be overridden

abstract cannot be implemented in the same class

native The method is implemented in the machine code used by the host CPU, not using byte codes

private can be invoked by the code within the same class

protected can be invoked by the code of a sub class in the same package or any other package

public can be invoked by any class

static Cannot be accessed without an object (called as class method)

synchronized Acquired to lock when it begins execution

By default any variable is non-final, non-transient and non-volatile. The following example is an example demonstrating accessibilities of different methods

and variables. class A { Private int a=10; //this cannot be accessed from a subclass int b=20; //default access specifier protected int c=30; public int d=40; private void display() { //this cannot be accessed from a subclass System.out.println(“From display”); } void show() { System.out.println(“From show”); } protected void illustrate() { System.out.println(“From illustrate”); } public void expose() { System.out.println(“From expose”); } } public class B extends A public static void main(String args[]) { B b1=new B() //System.out.println(b1.a); //this is compilation error System.out.println(b1.b); System.out.println(b1.c); System.out.println(b1.d); //b1.display(); //this is compilation error b1.show(); b1.illistrate(); b1.expose(); }

Page 18: Core Java SoftCopy

17

} Access Specifiers at a Glance:

Private

Default

Protected

Public

Same Class Yes Yes Yes Yes

Same package subclass No Yes Yes Yes

Same package non subclass No Yes No Yes

Different package subclass No No Yes Yes

Different package non subclass No No No Yes

Access Specifiers between super class and subclass: When methods are overridden,the access specifier of the subclass overridden method cannot

be more restrictive than super class method.But it can be wider. class A { public void expose() { System.out.println(“From super expose”); } } public class B extends A { protected void expose() { //this will not compile as public is restricted to protected System.out.print(“From sub expose”); } public static void main(String args[]) { B b=b=new B();

b.expose(); }

}

Abstract Classes Abstract class specifies what functionality is to be provided and not how to provide. That is subclasses may use deferent implementation to achieve the same objective. Abstract classes cannot be final. That is to say abstract and final are mutually exclusive. IN THIS PROGRAM: Using abstract keyword. File Name:AbstractClassDemo.java abstract class Shape { //observe the syntax of an abstract class public abstract void display(); //observe the syntax of abstract method } class Circle extends Shape { public void display() { //display method is overridden,if not compilation error System.out.pritnln(“The circle have rounded corners”); } } class Rectangle extends Shape { public void display() { System.out.println(“The rectangle have right-angled corners”); //display() method is implemented with code

Page 19: Core Java SoftCopy

18

} } class Triangle extends Shape { public void display() { System.out.println(“The triangle do not hane two right-angled corners”); } } class AbstractClassDemo { public static void main(String args[]) { //public is assumed Circle cir=new Circle(); Rectangle rect=new Rectangle(); Triangle tri=new Triangle(); Cir.display(); rect.display(); tri.display(); /*The same output can be obtained through plymorphism also Shape sha; //creating a super class reference variable,here super class is an abstract class

sha=cir; sha.display(); sha=rect; sha.display(); sha=tri; sha.display(); */ } } Output: The circle have rounded corners The rectangle have right-angled corners The triangle do not have two right-angled corners The following is the best example to illustrate practically the purpose an abstract class and run-time polymorphism. IN THIS PROGRAM: Using abstract class and polymorphism. File Name: AbstractJetPlane.java abstract class JetPane { //abstract class abstract int numengines(); //abstract method } class DC10 extends JetPlane { int numEngines() { return 3; } } class DC10 extends JetPlane { int numEngines() { return 4; } } class AbstractJetPlane { public void amin(String args[]) { System.out.println(“No. of engines DC8 contains”+new DC8().numEngines());

Page 20: Core Java SoftCopy

19

System.out.println(“No. of engines DC10 contains”+new DC10().numEngines()); } } Output: No. of engines DC8 contains 3 No. of engines DC10 contains 4

P A C K A G E S A package is a group of classes and interfaces. You can assign the classes and interfaces in a source file to a particular package by using a package statement. The package statement must appear as the first statement in the source file. It is possible to organize package in a hierarchical manner. Java class libraries are organized into packages. Some of these are listed below: Package Description Java.applet allows you to build applets Java.awt provides an Abstract Window Toolkit (AWT)

with which user can construct Graphical User Interfaces.

Java.awt.event handles events from AWT components Java.io supports input and output Java.lang provides core java junctionality Java.net enables networking Java.util offers utility functionality ( like time, date, data structures etc) To create user defined packages Let C:\WINDOWS\RK>be your current directory. Now open an editor to your source file with the following command. C:\WINDOWS\RK>notepad Dog.java Write your source file as follows: package animal; public class Dog { int wt = 10: public void nature( ) { System.out.println( “Dog the most faithful servant” ) ; } public void weight( ) { System.out.println( “My pet weighs “ + wt +” kgs ”); } } Now compile the above source code as folloes: C:WINDOWS\RK> javac –d.Dog.java -d = Keeps the compiled java file(i.e Dog.class) in the package animal. . = stands for current directory. Now if you open RK directory,you can find animal directory and you cannot find Dog.class file.That is above command created a directory by name animal in the current directory RK.If you open the animal directory you can the see the Dog.class file.

Page 21: Core Java SoftCopy

20

Next my aim is to import this package animal in some other directory and call the Dog.class file. For example ,I go to my parent direrectory(windows) and from there I call.That is my current prompt is C:WINDOWS> It is necessary to set the classpath as follows: C:\WINDOWS>set classpath=C:\WINDOWS\RK;.; %CLASSPATH%; %CLASSPATH% = appends the earlier classpath . = Includes current directory At the prompt C:\WINDOWS opens a new source file as follows: C:\WINDOWS>notepad PackageDemo.java and write the code as follows: Import animal; //or import animal.Dog; Public class PackageDemo { Public static void main(String args[]) { Dog dog=new Dog(); Dog.nature(); dog.weighs(); } } Output: Dog the most faiyhful servant My pet dog weighs 10 kgs

Practice Material on Interfaces Before going into the discussion of interfaces, it is better to review once, the concepts of method overloading and overriding just you learnt in the previous class. Summary of Method Overloading:

The identity of a method is determined by the combination of its fully qualified class name and also the type, order and count of arguments in the arguments list.

Two are more methods in the same class (including perhaps the methods inherited from a superclass) with the same name but different argument lists are called overloaded.

Methods with overloaded names are effectively independent methods. Using the same name is really just a convenience to the programmer. Return type, access specifies and exception list may vary freely.

Overloaded methods may call one another simply by providing a normal method call with an appropriately formed argument list.

Summary of Method Overriding:

An overriding method (largely) replaces the method it overrides. (Overloaded methods supplement each other).

Each method in a parent class can be overridden at most once in any one subclass.(overloadedmethods can exist in any number, in the same class).

Page 22: Core Java SoftCopy

21

Overriding methods must have arguments lists of identical type and order, otherwise they are treated simply as overloaded methods. (overloaded methods must have different arguments lists).

The return type of a overriding method must be identical to that of the method it over rides. (the return type of an overladed method may be choosen freely).

Some more rules to be observer in method overriding:

An overriding method must not be less accessible that the method it overrides. (if the supercass method is public, the subclass method cannot be protected or private).

An overriding method must not throw any checked exceptions that are not declared for the overridden method.

Interfaces An interface defines a protocol behavior. A class that implements an interface adheres to the protocol defined by that interface. Interfaces like abstract classes provide templates of behavior that other classes are expected to implement. What is an interface? An interface is java keyword used to generically (in general) define constants and methods wherein the actual implementation for these methods is done by the subclass implementing the interface. Interfaces, unlike abstract classes, should contain all methods abstract. Abstract class may contain:

All abstract methods (like interfaces)

All non- abstract methods

A mixture of non – abstract methods.

Can an interface be extended? Yes, in fact interface expects it from you. An interface can be extended just like any other class but extends keyword should be replaced with another keyword implements. Does Java support multiple inheritance? In multiple inheritances, a subclass can have any number of superclasses. Strictly speaking, Java does not support multiple inheritance, even though it is basically an OOPs concept. For Example, a bat inherits the properties of birds (flying) and properties of mammals (giving offspring). In java, we can‟t write a program where a bat object inherits the properties of both bird object and mammal object. Isn‟t it (not supporting multiple inheritance) a negative point to java? Yes, you are right. Actually, it is a negative point to java. Java designers solved this problem through interfaces where it is possible to a class to implement more than one interface. That is to say that java supports multiple inheritance through interfaces. Creating and implementing interfaces: IN THIS PROGRAM: creating and using an interface. interface Bird { //writing interface class bird is wrong public abstract void wings(); //interface method contains nobody

Page 23: Core Java SoftCopy

22

public abstract void flying(); //interface method ends with semicolon } public class Bat implements Bird { //observe implements instead of extends] public void wings() { //providing implementation for first interface method System.out.println(“Bat has two wings”); } public void flying() { //providing implementation for second interface method System.out.println(“Bat flies at super speeds”); } public static void main(String args[]) { Bat bat = new Bat(); bat.wings(); bat.flying(); //we can also assign a subclass (Bat) object to a superclass interface (Bird) reference variable. System.out.println(“\nUsing interface reference variable:”); Bird bird; //creating interface reference variable bird = bat; //assigning subclass object to interface reference variable bird.wings(); //calling subclass methods with reference variable bird.flying(); //we can‟t create objects of an interface like an abstract class } } Output: Bat has two wings Bat files at super speeds Using interface reference variable: Bat has two wings Bat flies at super speeds If the interface contains more than one method, the subclass which implement the interface must override all the abstract methods of the interface else it is a compilation error. Implementing Multiple Interfaces: The following example shows the multiple inheritance of java regarding interfaces.The above program is modified a little and shown. IN THIS PROGRAM: Creating two interfaces and implementing in a sub class. interface Bird { //1st interface public abstract void wings(); public abstract void flying(); } interface Mammal { //2nd interface public abstract void offspring(); } public class Bat implements Bird,Mammal { //implementing both interfaces public void wings() { //implementing the method of 1st interface System.out.println(“Bat have two wings”); }

Page 24: Core Java SoftCopy

23

public void flying() { //implementing the method of 1st interface System.out.println(“Bat flies at super speed”); } public void offspring() { //implementing the method of 2nd interface System.out.println(“Bat gives offspring and does not lay eggs”); } public static vpid main(String args[]) { Bat bat=new Bat(); bat.wings(); bat.flying(); bat.offspring(); } } Output: Bat have two wings Bat flies super speed Bat gives offspring and does not lay eggs The sub class must be implement all the methods of all the interface it implementa. Extending Interfaces: One interface can extend another interface,but can‟t implement.The above example is slightly changed and presebted below. IN THIS PROGRAM: extending one interface to other. Interface Bird { //first interface public static final int wings = 2 //instance variable in interface public abstract void wings(); public abstract void flying(); } interface Mammal extends Bird { //second interface extending first public abstract void offspring(); } public class Bat implements Mammal { //implementing the second interface public void wings() { System.out.println(“Bat has”+wings+”wings”); } public void flying() { System.out.println(“Bat flies at super speeds”); } public void offspring() { System.out.println(“Bat gives offspring and does not lay eggs”); } Public static void main(String args[]) { Bat bat = new Bat(); bat.wings(); bat.flying(); bat.offspring(); }

Page 25: Core Java SoftCopy

24

} Output: Bat has 2 wings Bat flies at super speeds Bat gives offspring and does not lay eggs Some important points to remember about interfaces:

All methods in an interface must be declare public and abstract and even if omitted, the methods are public and abstract by default. Generally, programmers omit these access modifiers as a matter of style.

All variables in an interface are by default static and final.

All methods in an interface must be abstract.

A class can implement any number of interfaces with implements clause.

When an interface method is implemented, it must be declared as public in the subclass (the reason: in interface all methods are public by default and in implementation methods cannot be declared more restrictive in a subclass).

Interface reference variables can be assigned with objects of a subclasses, just like abstract classes.

Multiple Inheritance in Interfaces: One interface can extend any number of interfaces which is not possible in concrete classes. IN TNIS PROGRAM: extending two interfaces to an interface interface interface1 { public abstract void display(); } interface interface2 { public abstract void show(); } interface interface3 extends interface1, interface2 { public abstract void illustrate(); } public class MultiinterfaceDemo implements interface3 { public void display() { System.out.println(“From Display”);} public void show() { System.out.println(“From show”); } public void illustrate() { System.out.println(“From illustrate”); } public void main (String args[]) { MultiinterfaceDemo mid = new MultiinterfaceDemo(); mid.display(); mid.show(); mid.illustrate(); } } Output: From Display From show ]From illusrate Q.No.1 public class Numbers { public void sum(double x. double y) { System.out.println(x+””+y); } public static void main(String args[]) {

Page 26: Core Java SoftCopy

25

Numbers num = new Numbers(); Num.sum(4, 5); } } the output of the above program is a) 4 5 b) 4.0 5.0 c) does nt compile as matching method sum with int arguments is not found d) none Ans: b Explanation: When a matching method which can tally with the arguments is not found, compiler tries to implicitly promote the data types ( here, int is promoted to double). 4 and 5 are promoted to 4.0 and 5.0 and printed.

Arrays

Arrays are data structures that can store large amount of data of the same type grouped together and known by a common name. Each member is called an element of the array. Arrays are capable of strong primitive data types as well as objects. Like in C / C++, elements are stored in contiguous memory locations and indexed starting from 0. The elements of the array can be accessed by its index values. Once array is declared, its size cannot be altered dynamically. IN THIS PROGRAM: creating and displaying the elements. Public class ArrayDemo { Public static void main(String args[]) { int subject[] = new int[5]; //creating an array of type int of 5 elements System.out.println(“Default value of subject[2];”+subject[2]); //default 0 Subject[0] = 10; subject[1]=20; //start assigning the values toelements Subject[2] = 30; Subject[3] = 40; Subject[4] = 50;

System.out.println(“After assigning the value of subject[2]:”+subject[2]); //prints 30 int x=subject.length; //length gives the size of the array System.out.println(“Size of the subject array is:”+x); //prints 5 System.out.println(“\n Displaying the elements of subject array”); For(int I=0;I<subject.length;I++) System.out.println(“subject[“+i+”]=”+subject[I]); Int rates[]={100,200,300,400,500};

System.out.println(“\n Displaying the elements of rates array”); For(int i=o;i<rated.length;i++) System.out.println(“rwtes[“+I+”]=”+rates[i]); String names[]={“Sumanth”,”Bhaskar”,”Harish”}; System.out.println(“\n Displaying the elements of names array:”); For(int i=0;i<names.length;i++) System.out.println(“names[“+i+”=”+names[i]);

} } int subjects[]=new int[5] can be split into two statements: int subjects[]; subjects=new int[5]; The sqare brackets[] can be also placed as: int[]subjects=new int[5];

Page 27: Core Java SoftCopy

26

In the above example subject array is created first and the elements are assigned later.rates array and names array are initialized.When an array is initialized ,arrey size should not be give in the array statement.That is int rates[5]={100,200,300,400,500”;is wrong and leads to compilation error even though the size of the array,5 is correct. IN THIS PROGRAM: to pass command line arguments. public class CmmandLine1 { Public static void main(String args[]) { For(int i=0;i<args.length;i++) System.out.println(“args[i]); } } Compile the program as usual.While running give the command lile this: C:\Windows>java CommandLine1 sure rama kanth java lecturer The output will be sure,rama,kanth and lecturer in separate lines. IN THIS PROGRAM: to pass command line arguments and parsing to int values. Irrespective of whether you pass int or double or strings as command-line arguments, every thing will be converted into strings and passed into the program. If those values are to be used as to the values are to be converted to int from string form. public class ArrayPassingDemo { public static void main(String xyz[]) { for(int i=0;i<xyz.length;i++) System.out.println(“xyz[1]); int x=Integer.parseInt(xyz[1]); Int y=Integer.parseInt(xyz[2]); System.out.println(“The product is:”+x*y); } } In the previous programs, args is nothing but an identifier of a string array and it can be any valid identifier like xyz in the above program. Pass command-line arguments as: java ArrayParsingDemo 10 20 30 40 50.These integer values 10, 20 etc. are passed as strings and we cannot do any arithmetic operations on these values. A string value can be converted to an int type using parsing operation as in the above program. Array elements are passed by pass-by=value and arrays (because arrays are objects) are passes by pass –by-reference. The following to examples illustrates. IN THIS PROGRAM: to show array elements are passed by value. public class PassByValue { void calculate(int x) { x = 20; System.out.println(“From calculate method:”+x); //prints 20 } public static void main(Strings args[]) { PassByValue pbr = new PassByValue(); Int y[] = {10}; System.out.println(“Before passing the value:”+y[0]); //prints 10

Page 28: Core Java SoftCopy

27

Pbr.calculate(y[0]); System.out.println(“After passing the value:”+y[0]); //prints 10 } } IN THIS PROGRAM: to show arrays (not array elements) are passesd by reference public class PassByReference { void calculate(int x[]) { x[0] = 20; System.out.println(“From calculate method:”+x[0]); //prints 20 } public static void maijn(String args[]) { PassByReference pbr = new PassByReference(); Int y[] = {10}; System.out.println(“Before passing the value:”+y[0]); //prints 10 Pbr.calculate(y); //array itself is passed System.out.println(“After passing the value:”+y[0]); //prints 20 } } The change of value of an array element in the calculate method alters the value of the element in the main method. Objects are passed by reference in Java. We can create an array of objects also as in the following examples. IN THIS PROGRAM: creating an object array public class CreatingObjectArray { int x = 10, y = 27: public static void main(Strings args[]) { CreatingObjectArray[] obarray = new CreatingObjectArray[3]; obarray[0] = new CreatingObjectArray(); obarray[1] = new CreatingObjectArray(); obarray[2] = new CreatingObjectArray(); System.out.println(obarray[1]); System.out.println(obarray[1].x+obarray[1].y); Obarray[1].x = 100; System.out.println(obarray[1].x+obarray[1].y); } } Output: CreatingObjectArray @bf28676f 37 127 IN THIS PROGRAM: creating a two dimensional array. public class TwoDimensionalArray { public static void main(String args[]) { int que[] [] = { {10,20,30,40}, {100,200,300,400}, {1000,2000,3000,4000} }; System.out.println(que[1] [2]);

Page 29: Core Java SoftCopy

28

} } The output is 300 The above program can be coded also as: public class ArrayDemo { public static void main(Strings args[]) { int a1[] = {10,20,30,40}; int a2[] = {100,200,300,400}; int a3[] = {1000,2000,3000,4000}; int que[] [] = (a1, a2, a3}; System.out.println(que[1][2]); } } The output is 300. The following is the matrix from (3 rows x 4 columns) of the above example.

Matrix form of a two – dimensional array So far you have seen the similarities between the arrays of java and C/C++. Now we will explore the differences. How the java array differs from that of C or C++? As far as single dimensional array is concerned, there is no difference at all. In a two dimensional array, the size of the second of dimension can be varied for every row depending on the necessary. The needs can be as follows: Suppose, in the above example rows(first-dimension) represents students and the columns(second-dimension) represents subjects. Suppose, the second student do not appear for 2nd subject and third do not appear for 2nd and 3rd subjects the memory allocated to them is waste. In C/C++, there is no way not to allocate. But in java it is possible not to allocate as the following example explains: IN THIS PROGRAM: to have a varied second dimension in a two-dimensional array.

COLOMNS---------

0 1 2 3

10

20

30

40

100

200

300

400

1000

2000

3000

4000

R O W S

0 1 2

Page 30: Core Java SoftCopy

29

Public class ArrayDemo { Public static void main(String args[]) { int student[] [] = new int[3] []; //2nd dimension size is not mentioned student[0]=new int[4];

student[1]=new int[3]; student[2]=new int[1]; //start assigning element to yhe 2nd dimension student[0][0]=45; student[0][1]=55; //1st appeared all 4 subjects student[0][0]=65; student[0][3]=75; student[1][0]=46; student[1][1]=56; student[1][2]=66; //2nd students appears 3 subjects only student[2][0]=88; //3rd students appears only one subject System.out.println(“student[1][2]); //output 66 } } IN THIS PROGRAM:another example on a two dimensional array. class JavaTwoDimensionalArray { public static void main(String args[]) { int numarray[][]={{1,2},{10,20,30},{100,200.300,400}}; //to find the length of each row(1st

dimension) System.out.println(“The length is the numarray is”+numarray.length); System.out.println(“The length is the numarray[0] is”+numarray[0].length); System.out.println(“The length is the numarray [1]is”+numarray[1].length); System.out.println(“The length is the numarray [2]is”+numarray[2].length); //TO PRINT THE ELEMENTS OF EACH ROW for(int i=0;i<numarray.length;i++) { //numarray.length gives no.of rows for(int i=0;j<numarray[i].length;j++) //gives no.of elements in each column System.out.println(“numarray[i][j]); System.out.println(); } } } Output: The length of the numarray is 3 The length of the numarray[0] is 2 The length of the numarray[1] is 3 The length of the numarray [3]is 4 1 2 10 20 30 100 200 300 400 To copy one array into another:

Page 31: Core Java SoftCopy

30

Syntax: System.out.println(sourceArray,source position,destinationArray,destination position,no.of elements to be copied);

(method arraycopy is defined in System class of java.lang.package) IN THIS PROGRAM: copying an array into another array either completely or part. public class CopyingArray { Public static void main(String args[]) { //copying whole array:array1 into array2 int[] array1={1,2,3,4,5};

int[] array2=new int[5]; System.arraycopy(array1,0,array2,0,array1.length);

//here,0s represents he starting position of the element in each array and array1.length //indicates complete array is to be copied for(int i=0;i<array2.length;i++) //display the elements of array2 System.out.println(array2[I]+” “); //to copy part of an array2 System.out.println(); //to give an empty space int[] numarray1={10,20,30,40,50}; int[] numarray2={100,200,300,400,500,600,700};

System.out.println(numarray1,1,numarray2,2,3); For(int i=0;I<numarray2.length;i++) System.out.println(“numarray2[i]+” “); } } Output: 10 20 30 40 50 100 200 300 400 500 600 700

While creating array2,in the above example ,care must be should be taken to make he size of the array2 to be sufficient to accommodate all the elements of array1.

Assignment sum to students

Create a two-dimensional array of varying 2nd dimension representing rows as subjects and columns as marks.Print the marks of 2nd student and the marks of 2nd column.Also print the whole array in a matrix form? The following is the solution: In the following example each student subject-wise marks(row) and each subject Marks of whole class or all students(column) are obtained. class PlayingWithArrays { public static void main(String args[]) { int grades[][]={{1,2},{10,20,30},{100,200,300,400}}; //to obtain the marks of 2nd student(i.e 2nd row) System.out.print(“Marks of 2nd student:”);

Page 32: Core Java SoftCopy

31

for(int i=0;i<grades[1].length;i++) //2nd student array index is 1 System.out.print(grades[1][i]+” “); //to obtain the marks of subject 2(i.e 2nd column) System.out.print(“\n Marks of 2nd subject”); for(int i=0;i<grades.length;i++) System.out.print(grades[i][1]+” “); //to obtain the marks in matrix form System.out.println(“\n Marks in matrix form:”); for(int i=0;i<grades.length;i++) { for(int j;j<grades[i].length;j++) { System.out.print(grades[I][j]+””); }

System.out.println(); } } } Output: Marks of 2nd student:10 20 30 Marks of 2nd subject:2 20 200 Marks in matrix form: 1 2 10 20 30 100 200 300 400

Strings

PROGRAMS ON STRINGS In C/C++, string is an array of characters and in java string is an object (derived from string class) that can be assigned with a group of characters enclosed in double quotes. String class cannot be subclassed as it is declared final in the java.lang package. The class header of string class is

public final class String extends Object implements java.lang.serializable Unlike in C/C++, string manipulations are very easy in java. We will study some important methods of String class. IN THIS PROGRAM: comparing strings with equals and == Public class StringCompare { //equals() is Object class and is inherited by String Public void main(String args[]) { String s1=new String(“hello”); String s2=new String(“good bye”); String s3=new String(“Happy Birthday”); String s4=new String(“happy birthday”); System.out.println(“s1 =”+s1); if(s1 equals(“hello”)) //test for equality with equals System.out.println(“s1 equals \”hello\””); else System.out.println(“s1 does not equal\”hello\”);

Page 33: Core Java SoftCopy

32

if(s1==”hello”) //test for equality with == System.out.println(“s1 equals \”hello\””); else System.out.println(“s1 does not equal \”hello\””); if(s3.equalsIgnoreCase(s4)) //test for equality-ignore case System.out.println(“s3 equals s4”); else System.out.println(“s3 does not equal s4”); //test for equality with compareTo System.out.println(“s1.compareTo(s2) is”+s1.compareTo(s2)); System.out.println(“s2.compareTo(s1) is”+s2.compareTo(s1)); System.out.println(“s1.compareTo(s1) is”+s1.compareTo(s1)); } } Output: s1=hello s1 equals “hello” s1 does not equal “hello” s3 equals s4 s1.compareTo(s2) is 1 s2.compareTo(s1) is –1 s1.compareTo(s1) is 0 compareTo() compares two strings lexographically (character by character).If both the strings are same it returns 0 else it returns an integer which is the difference of ASCII code of the two dissimilar characters. IN THIS PROGRAM: checking a string with startsWith and endsWith Public class StringStartEnd { Public static void main(String args[]( { String s1=”started”); String s2=”starting”; System.out.println(“s1 starts with \”st\” “+s1.startsWith(“st”); System.out.println(“s1 starts with \”r\” from index 3”+s1.startsWith(“r”,3)); System.out.println(“s1 ends with \”ed\” “+s1.endsWith(“ed”); } } Output: S1 starts with”st”true S1 starts with \”r\” from index 3 true S1 ends with ed” In startsWith() search begins from start of the string and in endsWith() the search begins from ending of the string.In the statement s1.startWith(“r”,3),the search for r begins from the character at index 3 in the string. IN THIS PROGRAM: locating Characters and Sunstrings with indexOf and lastIndexOf.

Page 34: Core Java SoftCopy

33

Public class StringIndexMethods { Public static void main(String args[]) { String letters=”abcdefghijklmabcdefghijklm”; System.out.println(“TEST indexOf TO LOCATE A CHARACTER IN A STRING”); System.out.println(“c is located at index:”+letters.indexOf(„c‟));

System.out.println(“a is located at index:”+letters.indexOf(„a‟)); System.out.println(“$ is located at index:”+letters.indexOf(„s‟)+”\n”); System.out.println(“TEST lastIndexOf TO FIND AS CHARACTER IN ASTRING”); System.out.println(“Last c is located at index :”+letters.lastIndexOf(„c‟)); System.out.println(“Last a is located at index:”+letters.lastIndexOf(„a‟)); System.out.println(“Last $ is located at index:”+letters.lastIndexOf(„$‟)+”\n”); System.out.println(“Test indexOf TO LOCATE A SUBSTRING IN A STRING”); System.out.println(“\”def\” is located at index:”+letters.indexOf(“def”)); System.out.println(“\hello\” is located at index:”+letteres.indexOf(hello”+”|n”)):

System.out.println(“Test indexOf TO LOCATE A SUBSTRING IN A STRING”);

System.out.println(“last \”def\” is located at index:”+letters.lastIndexOf(“def”)); System.out.println(“Last \”hello\” is located at index:”+letters.lastIndexOf(“hello”)); } } Output: TEST indexOf TO LOCATE A CHARACTER IN A STRING c is located at index: 2 $ is located at index:-1 TEST lastIndexOf TO FIND AS CHARACTER IN A STRING Last c is located at index: 15 Last a is located at index: 15 Last $ located at index: -1 Test indexOf TO LOCATE A SUBSTRING IN A STRING “def” is located at index: 3 “hello” is located at index: -1 Test lastIndexOf TO LOCATE A SUBSTRING IN A STRING Last “def” is located at index: 16 Last “hello” is located at index: -1

IN THIS PROGRAM: extracting substrings from a string with substring. public class SubString { public static void main(String args[]) { String letters=”abcdefghijklmabcdefghijklm”; System.out.println(“Substring from index 20 to end is:”+letters.substring(20)); System.out.println(“Substring from index 0 upto 6 is:”+letters.substring(0,6)); System.out.println(“Substring of(1,6):”+letters.substring(1,6)); } } Output: Substring from index 20 to end is:hijklm Substring from index 0 to 6 is: abcdef //always substring reads 1 past,so make Substring of(1,6): bcdef //less 1 in the second integer parameter

Page 35: Core Java SoftCopy

34

IN THIS PROGRAM: concatenating strings using concat public class StringConcat { public static void main(String args[]) { String s1=new String (“Happy”); String s2=new String(“Birth Day”); System.out.println(“s1=”+s1);

System.out.println(“s2=”+s2); System.out.println(“Result of s1.concat(s2) is :”+s1.concat(s2)); System.out.println(“s1 after concatenation is:”+s1); //s1 is not changed System.out.println(“s1+s2 is:”+s1+s2); //after concat } } Output: s=Happy s2=Birth Day Result of s1.concat(s2) is : Happy Birth Day s1 after concatenation is: Happy s1+s2 is: HappyBirth Day

IN THIS PROGRAM: using the methods replace,toUpperCase,toLowerCase. Public class String { public static void main(String args[]) { String s1=new String(“hello”); String s2=new String(“GOOD BYE”); String s3=new String(“ spaces “); System.out.println(“Replace „l‟ with „L‟ in s1=”+s1.replace(„l‟,‟L‟)); System.out.println(“s1 after toUpperCase=”+s1.toUpperCase()); System.out.println(“s2 after toLowerCase=”+s2.toLowerCase()); System.out.println(“s3 after trim=”+s3.trim()); } } Output: Replace „l‟ „L‟ in s1=hello //replace does not change the original string.SOP(s1) prints hello S1 after toUpperCase=HELLO S2 after toLowerCase=good bye S3 after trim=spaces IN THIS PROGRAM: USING String.valueOf IN THIS PROGRAM: stringValueOf() converts to a string form any thing that is passed as parameter. Public class StringValueOf { public static void main(String args[]) { String s1=”Ramakanth”;

String s2=” spaces “; System.out.println(“Length of s1 is:”+s1.length()); System.out.println(s2.trim()); System.out.println(“4th character in s1 is:”+str.charAt(3)); }

Page 36: Core Java SoftCopy

35

} Output: Length of s1 is 9 Spaces 4th character in s1 is k

In the above program the number of characters present in the string is found with length()(which is a method) and is very different from that of length(which is a variable) which is used for find the sixe of the array.

Programs on StringBuffer Once if string is assigned a value ,it cannot be changed. It means if a string is reassigned a value, the original memory location is lost and new memory location is allotted. This phenomenon is called immutable and is an ovegead to the processor and a negative point for performance. To over come this lacuna, java designers introduced StringBuffers. StringBuffers are grow able dynamically. IN THIS PROGRAM: to find the length and capacity of a StringBuffer and using ensureCapasity. public class StringBuffer { public static void main(String args[]) { StringBuffer buf1=new StringBuffer(); StringBuffer buf2=new StringBuffer(10); StringBuffer buf3=new StringBuffer(“hello”); System.out.println(“TO CONVERT A StringBuffer TO String”); System.out.println(“buf3 toString=”+buf3.toString()+”\n”); System.out.println(“TO FIND THE LENGTH OF A StringBuffer”); System.out.println(“Length of buf1 is=”+buf1.length()); System.out.println(“Length of buf2 is=”+buf2.length()); System.out.println(“Length of buf3 is=”+buf3.length()); System.out.println(“TO FIND THE CAPACITY OF A StringBuffer”); System.out.println(“Capacity of buf1 is=”+buf1.capacity());

System.out.println(“Capacity of buf2 is=”+buf2.capacity()); System.out.println(“Capacity of buf3 is=”+buf3.capacity()); Buf1.ensureCapacity(50); System.out.println(“New Capacity of buf1 is=”+buf1.capacity());

System.out.println(“New length is of buf1 is=”+buf1.length()); } } Output: TO CINVERT A StringBuffer TO String Buf3 toString=hello //now hello is an String from and not StringBuffer form TO FIND THE LENGTH OF A StringBuffer Length of buf1 is=0 Lengrh of buf2 is=0 Length of buf3 is=5 TO FIND THE CAPACITY OF A StringBuffer Capacity of the buf1 ia=16 Capacity of the buf1 ia=10

Page 37: Core Java SoftCopy

36

Capacity of the buf1 ia=21 New capacity of buf1 is 50 New length of buf1 is 50 IN THIS PROGRAM: appending a StringBuffer with append public class StringBufferappend { public static void main(String args[]) { Object o=”hello”; //assign String to Object reference String s=”good bye”; boolean b=true; int i=7; double d=33.333; StringBuffer buf=new StringBuffer(); buf.append(o); buf.append(„ „); buf.append(s); buf.append(„ „); buf.append(b); buf.append(„ „); buf.append(l); buf.append(„ „); buf.append(d); System.out.println(buf); } } Output: Hello good bye true 7 33.333 Inserting a String in StringBuffer: class InsertString { public static void main(String args[]) { StringBuffer sb=new StringBuffer(“Rama Kanth”); System.out.println(sb); Sb.insert(4,”Bhaskar”); //char also can be inserted in the same way //for eg. Sb.insert(4,‟A‟); System.out.println(sb); } } Output: RamaBhaskar Rao Revering a StringBuffer: class Reverse { public static void main(String args[]) { StrngBuffer sb=new StringBuffer(“RAMA”); System.out.println(sb); //prints RAMA Sb.reverse(); System.out.println(sb); //prints AMAR } } To delete some characters of StringBuffer:

Page 38: Core Java SoftCopy

37

public class DeleteChars { public static void main(String args[]) { StringBuffer sb1=new StringBuffer(“rama”); sb1.delete(1,3); //like substring,reads one past,delets am prints ra System.out.println(sb1); sb1.append(“Krishna”); System.out.println(sb1); //prints rakrishna sb1.delete(0,sb1.length()); //delete complete string System.out.println(sba); //does not print anything } } One JCP Question: What is the output of the following code? StringBuffer sb=new StringBuffer(“RAMA”); sb.setLength(0); System.out.println(sb);//prints anything,but an empty line of that of println() statement SetLength() truncates or expanda the previous character string.If expanding,pads with nulls.

Exception Handling

Practice material on Exception Handling

What is an Exception? An exception is an abnormal condition that disrupts normal program flow(or execution). The exception signifies an illegal, invalid or unexpected situations like:

The file you try to open may not exist.

The class file you want to load may be missing or in the wrong format.

The other end of the network connection may be non-existent.

The network connection may be disrupted due to some mysterious reason.

An operand is not in the exceed the size of array and a divisor operatrion cannot be zero.

If these abnormal conditions are not prevented or at least handled properly,the program may be aborted(terminated). Observe the following program: public class ExceptionUnhandled { public static void main(String args[]) { int a=10;b=0;c; try { c=a/b; } catch(ArithmaticException e) { System.out.println(“I caught the exception:”+e); } System.out.println(“Okay”); } }

Page 39: Core Java SoftCopy

38

Output: I caught the exception:java.lang.ArithmaticException:/ by zero Okay Two new statements you can find in the above program. Due to these changes, an exception message and Okay are printed. The flaws(defects) in the code which can be detected at compilation-time are called Bugs and that of at run-time(execution-time) are called exceptions. In the above programs, the statement c=a/b, raises an exception called Arithmetic Exception (all exceptions have got names, which we will see later).As exception raised, the 1st program (class ExceptionUnhandled) displays the exception message and the program terminates without printing okay. In the second program, the exception is handled by two new keywords try and catch. As exception is handled, the exception message is displayed and okay is printed. The process of dealing exceptions, as in the above second program, is called Exception Handling. What is the mechanism of Exception Handling java adopt? The statements which you think may raise exceptions simply move them to try block. In the above program, such statement is c=a/b and is moved into a try block. The exception raised in the try block, should be handled at some point of the program and it is the catch block. The catch block is capable enough to handle the exception. In the catch block, exception name (in previous example, it is Arithmetic Exception and it is a class by itself. All exceptions are defined in java.lang.package) is written followed by some message you would like to point (apart system‟s)in case of exception occurs. The message is written in a println statement. Are try and catch methods? They look like methods but not.In java,you know,a method should have a return type(atleast void) and access specifier (atleast default).But try and catch do not have any of these. try and catch are blocks a(and not called methods)-try block and catch block and later you may get another called finally block.

Suppose in the second program,if b is not equal to zero,will he try-catch blocks raise an error though exception possibility is not there? If exception is not raised ,the JVM simply forgets the try-catch blocks and will be treated as a normal program.That is,the exception handling mechanism(providing try and catch blocks)invoked(implicitly by JVM)only when exception is raised and if not JVM simply forgets. Another program which raises an exception. Public class ExceptionDemo { Public static void main(String args[]) { int subject[]={35,45,55,65}; try { System.out.println(subject[5]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(“I caught the exception: “+e); } System.out.println(“Okay”);

Page 40: Core Java SoftCopy

39

} } Output: I caught the exception:java.lang.ArithmaticException:/ by zero Okay

In the above program, the exception is ArrayIndexOutOfBoundsException(in the previous example it is Arithematic exception) which is raised by the statement Subject [5]. There is no 5th element in the subject array and the element that do not exist is tried to display for some result. It is an exception in java which is handled by catch block successfully and the program execution continues and prints Okay. If it is in C/C++, a garbage value is printed. This is an example, where java is designed robust.

Observe the following by try block code: try { System.out.println(subject[5]); System.out.println(“This statement will not print”); } Two print statements are present in the above try block. When the first one raises an exception, control comes into the catch block as expected, but after executing the catch block, control does not go back into the try block to execute the second println statement. From catch block, the control proceeds to the next (below the catch block) and prints Okay (not shown in the above fraction of code. What is finally block? Suppose in place of second println statement, if an important statement is present which must be executed, then what about its fate. The second statement may be some times to free the system resources of files which if not freed, memory leak may occur. Move such of these important statements into a finally block. Finally block guarantees the execution for its statements whether exception is raised or not. The following program displays the semantics of a finally block: public class FinallyDemo { public static void main(String args[]) { int subject[] = {35,45,55,65}; try { System.out.println(subject[2]); System.out.println(“Not Okay”); } catch(ArrayIndexOutBoundsException e) { System.out.println(“I caughtthe exception:”+e); } finally { System.out.println(“Okay”); } } } Output: 55 Not Okay Okay In the above program three println statements (two from try block and one from finally) got executed as exception is not raised as subject [2] is within the array index range. Now change the

Page 41: Core Java SoftCopy

40

index to say 5---- an exception is raised. In this situation two print statements (one from catch and one from finally) are got executed. That is whether exception is raised (second case, subject[5]) or not (first case, subject[2]), finally is executed. Move any important statements, whose execution is to be guaranteed, to finally block. Other way to put it is, the finally block guarantees the execution of code which you place in it. Can a catch handle more than one exception ? No, not possible, if you desire to handle more than one exception, write more number of catch blocks and note that each catch block cannot handle more than one exception. A single try block can have any number of catch blocks. IN THIS PROGRAM: to use more than one catch block. class MultipleCatchDemo { public static void main(String args[]) { int a = 10, b = 0, c; int[]subject = {35,45,55,65}; try { System.out.println(c = a/b); System.out.println(subject[5]); }

catch(ArithmeticException e) { System.out.println(“I caught”+e getMessage()); } catch(ArrayIndexOutBoundException e) { e.printStackTrace(); } } //e.Message() and e.printStackTrace() are another way of getting exception information. } Before going into details still further, we will study about the hierarchy of exception. Object IOException Throwable InterruptedException ArithmeticException Exception ClassNotFoundException NegetiveArraySizeException Error RuntimeException IndexOutOfBoundException

ArrayIndexOutBoundsException StringIndexOutBoundsException

Hirearchy of Exception

Checked exceptions vs Unchecked exceptions:

Page 42: Core Java SoftCopy

41

Checked exceptions are exceptions that are not subclass of Runtime Exception class and must be checked(handled) by the programmer and if not, the code does not compile. Unchecked exceptions are the subclass of Runtime Exception which even when not handled by the program, the program compiles( but execution stops at some point). That is to say, the unchecked exceptions may be unchecked by the programmer (of course, the danger prevails, if he checks, program execution proceeds are not). Using throws keyword: Some times the author of a method wants to warn others against the possible dangers (or exceptions) that may occur if they use his method. See how an author( the language designer) wants the possible exception that may occur when a file is to be opened. public FileInputStream(String name) throws FileNotFoundException He wants the possibility of not existing the file which the user want to open. The author warns by placing the exception in the method(here, constructor) header itself with throws clause. Any one who wants to use the constructor has to handle the exception(using try – catch) or atleast throw the exception( we will see how to use throw keyword later). IN THIS PROGRAM: to use throw keyword. import java.io class ThrowsDemo { public static void display() { try { FileInputStream fis = new FileInputStream(“Employee.Java”); } catch(FileNotFoundException e) { System.out.println(“Some problem in file opening”+e.getMessage()); } System.out.println(“From display method, File successfully opened”); } public static void show() throws FileNotFoundException { FileInputStream fis = new FileInputStream(“ExceptionHandled.java”); System.out.println(“From show method, File successfully opened”); } public static void main(String args[]) throws FileNotFoundException { display(); show(); } } The FileNotFoundException is handled in two ways by the two methods ------ display() and show(). Display() writes try – catch and show() throws the exception. throws helps the show() method only to get compiled and if actually exception is raised (that is, if the file ExceptionHandled.java is not found) program execution does not proceed further. Because show() is called (which throws FileNotFoundException) by the main method, main method whould also throw the FileNotFoundException. For display() method it is not necessary to throw because display() handles the exception in try – catch blocks.

Page 43: Core Java SoftCopy

42

If FileNotFoundException is not caught by the display() method, the following compiler‟s message is displayed: Exception.java.io.FileNotFoundException, must be caught or must be declared in the throws clause of this method” A method can throw more than one exception if it wants by separating with commas, See the following servlet method which throws more than one exception. Public void services(ServletRequest req, ServletResponse res) throws ServletException, IOException User Defined Exceptions: Sometimes the exceptions defined in java language may not convey understandable meaning to a common user. For him, you can design an exception and you can explicitly throw it at an appropriate situation. IN THIS PROGRAM: creating and throwing an user defined exception. class NoMoney Exception extends Exception { NoMoneyException(String message) { Super(message); } } public class Bank { public static void main(String args[]) throws NoMoneyException { int balance = 500.withdraw_amount = 1000; if(withdraw_amount>balance) throw new NoMoneyException(“Sorry, not enough balance please”); } } The same exception message can also be used to show the balance to the user. Just replace the message with(“Sorry, not enough balance please. Your balance is Rs.”+balance); Exceptions between superclass and subclass (important for JCP exam) Rule: An overridden subclass method cannot throw more than a superclass method. It can throw the same or less number of exceptions. The following examples illustrate. import java.io.*; //this package is to be imported for all I/O operations class A { public void display()throw FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(“a.dat”); System.out.println(“From super”); fis close(); //close()method throws IOException } //FileInputStream(String filename)constructor throws FileNotFoundException } public class B extends A { public void display() throws FileNotFoundException { //display() is overridden FilleInputStream fis = new FileInputStream(“a.dat”); System.out.println(“From sub”); } public static void main(String args[]) throws FileNotFoundException { B b = new B(); b.display();

Page 44: Core Java SoftCopy

43

} } The above program works nice and gets you output as subclass overridden display() method throws less number of exceptions than the superclass display() method. In the next example the subclass method throws more number of exceptions than superclass method and for this reason the program does not compile. import java.io.*; class A { public void display()throw FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(“a.dat”); System.out.println(“From super”); } } public class B extends A { public void display() throws FileNotFoundException { //display() is overridden FilleInputStream fis = new FileInputStream(“a.dat”); System.out.println(“From sub”); fis close(); } public static void main(String abc[]) throws FileNotFoundException { B b = new B(); b.display(); } } In the above example, the superclass display() throws only one exception FileNotFoundException. The subclass overridden display() method throws FileNotFoundException and also IOException. As subclass method is throwing more exceptions than superclass method, the program never compiles and throws the error message “Their throws clauses are incompatible”. Access specifies between superclass and subclass (important for JCP exam): Rule: An overridden method cannot have more restrictive access specifier than that of superclasss one. We know, the order of wider accessibility between access specifier in descending order is: public, protected, default, private. Observe the following example. class A { public void display() { System.out.println(“From super”); } } public class B extends A { protected void display() { System.out.println(“From sub”); } public static void main(String args[]) { B b = new B(); b.display(); } } Observe the access specifiers of the overridden display() method. In the superclass it is public and in subclass it is protected. As the overridden method got a more narrow access specifier than the superclass, the program does not compile. The compiler complains “The access modifier is made more restrictive”.

Page 45: Core Java SoftCopy

44

A real application of User defined Exceptions: Suppose a guy goes to Ocean Park to ride a Roller coaster. Riding a Roller Coaster is dangerous for kids and as well as for aged people as it involves speedy somersaults (tilts). Now we will write a program ------ when the are is entered by the computer operator, he must get the appropriate message: import java.io.*; class AgeException extends Exception { public AgeException(String message) { super(message); } } public class RollerCoaster { static int age, lowerAgeLimit = 15, upperAgeLimit = 60; public static void main(String args[]) throws AgeException { try { System.out.print(“Enter Your Age”); DataInputStream dis = new DataInputStream(System.in); String str = dis.readline(); age = integer.parseint(str);

} catch(IOException e) {

e.printStackTrace(); } if(age<15) { System.out.println(“Please come after”+(lowerAgeLimit)+”years”);

Throw new AgeException(“Sorry, now you are too YOUNG to ride a RollerCoaster Dear”);

} else if(age>60) { System.out.println(“You would have come before”+(age-upperAgeLimit)+”Years”); Throw new AgeException(“Sorry,now you are too old to ride a RollerCoaster Sir”); } else System.out.println(“Enjoy the ride on a RollerCoaster”); } } Just run the above program with different ages as input and enjoy Roller Coaster riding. Do not bother right now about the Input/Output mechanism in the above program. IN THIS PROGRAM: to demonstrate a nested exception. public class NestedTry { public static void main(String args[]) { in subject[]={35,45,55,65}; try { System.out.println(subject[2]); System.out.println(“Not Okay”); try { System.out.println(subject[5]); } catch (ArithmeticException) { System.out.println(“Frominner try:”+e); }

Page 46: Core Java SoftCopy

45

} catch(ArrayIndexOutBoundsException e) { System.out.println(“From outer try:”+e); } } } Output: 55 Not Okay From outer try : java.lang.ArrayIndexOutBoundsException:5 The inner try block should have it‟s qwn catch block.In the program ,as inner catch is given to catch some other exception like arithmetic exception ,the outer catch will catch the exception as inner failed. IN THIS PROGRAM: to demonstrate the propagation of exception. public class ExceptionPropagation { public static void display() { try { show(); } catch(ArithmaicException e) { System.out.println(“I caught:”+e); } System.out.println(“I am Okay”); } public static void show() { int a=10,b=0,c; c=a/b; } public static void main(String args[]) { display(); } } Output: I caught:java.lang.ArithmaticException:/ by zero I am Okay In the above program,exception is thrown by the one method(show) and caught by another method(display),because display calls the show method.We can still propagate the exception.Remove try-catch in display() method for show() and write try-catch in main method for display().Still the program works.

Inner Classes Definition: An inner class(nested) is a class that is declared in another class. Inner classes are introduced in jdk1.1.Fundamentally,an inner class is the same as any other class,but is declared inside some other class as a member or inside a method. The complexity of inner classes to scope and access,particularly access to variables in enclosing(outer) class. public class OuterOne { //outer class (enclosing class)

Page 47: Core Java SoftCopy

46

int x=10; //variable belonging to outer class public class InnerOne { //inner class as a member of outer class int y=20; //variable belongs to inner class public void InnerMethod { //a method of inner class System.out.println(“x from inner method:”+x; System.out.println(“y from inner method:”+y); } } } public void outerMethod() { //a method of outer class System.out.pritln(“x from outer method:”+x); //the following two statements raises a compilation error due to the scope of y System.out.println(“y from outer method:”+y”); System.out.println(“y from outer method:”+io.y”); } public static void main(String args[]) { OuterOne oo=new OuterOne(); OuterOne.InnerOne io=new OuterOne().new InnerOne(); oo.outerMethod(); io.innerMethod(); } } Output: x from outer method: 10 x from inner method: 10 y from inner method : 20 In the above program,the inner class InnerOne is like a member method of class outerOne and can not act as independent class.The inner class works in the context of outer class.As with member access and method invocation,it is important that the this reference be valid when you try to use it.Inside a static method there is no this reference,which you must take special efforts in these conditions. An instance of Innerclass can only exist within an instance of Outer class In the above example,we can not instantiate InnerOne as usual like InnerOne io=new InnerOne() as inner class do not have existence by itself being a nested class.Now if you refer the directory you will find two compiled classes:OuterOne.class and InnerOnesOuterOne.class.Observe the sign for the Inner class. In the above example,the statement OuterOne.InnerOne io=new OuterOne().new.InnereOne(); Can be replaced with OuterOne.InnerOne=oo.new.InnerOne(); The above program is modified further a little: public class OuterOne { static OuterOne.InnerOne io; //an instance variable of type OuterOne.InnerOne int x=10; //and the scope of io is for all the outer class public class InnerOne { int y=20; public void innerMethod () { System.out.println(“x from inner method:”+x); System.out.println(“y from inner method:”+y);

Page 48: Core Java SoftCopy

47

} } public void outerMethod() { System.out.println(“x from outer method:”+x); //System.out.println(“y from outer method:”+y);//error undefined variable y System.out.println(“y from outer method:”+y); } public static void main(String args[]) { OuterOne oo=new OuterOne(); io=oo.new InnerOne(); oo.outerMethod(); io.innerMethod(); } } Output: x from outer method: 10 y from outer method: 20 x from inner method: 10 y from outer method: 20 The modification of the program is due to the following reasons:

1. to access inner class instance variable(y) from the outer method,we used inner class object(io).io is referenced first in the instance variable position of outer class and made static as it is accessed(created object) through the static main() class.If io is not referenced like this,undefined variable io is displayed by the compiler.

2. to call the inner method using outer method instance (oo),the statement should be oo.io.innerMethod() ass oo can not access the inner class method directly.

Declaring an inner class inside a Method of outer class: In the previous examples, the inner class InnerOne enjoys the status of a member. Now we will declare a method in side a method of outer class and see the scope of variable. public class MOuter { public void display(int x,final int y) { //non-final variable of outer class final int b=x-y; //final variable of outer class class MInner { //an inner class inside the method of outer class public void show() { //System.out.println (“x is”+x); //illegal as x is not final

System.out.println(“y is”+y); //legal as y is final //System.out.println (“a is”+a); //illegal as a is not final System.out.println(“b is”+b); //legal as b is final

} //closing of show method of inner class /* Minner mi=new Minner/();mi.show();must be declared after class closing brace and before method closing brace else displays Invalid method declaration:method name required */ } //Minner class closing brace Minner mi=new Minner(); mi.show(); } //display method of outer class closing brace public static void main(String args[]) { Mouter mo=new new Mouter();

Page 49: Core Java SoftCopy

48

Mo.display(40,50); } } Output: Y is 50 B is –10 In the above program, the inner class can access only final variables of the enclosing (outer) class. That is the reason why x and a are illegal (as they are not final) and y and b are legal (as they are final).In the directory, you will find two .class files: Mouter.class and Mouter$1$MInner.class.$1$ appears as Minner is a nested inside a method of outer class. Static Inner classes: An inner class can be static also as in he following example: public class First { static class Display { public static void print(String s) { System.out.println(s); } //print method } //display class public static void main(String args[]) { First.Display.print(“Hello RamaKanth”); } } Output: Hello RamaKanth In the above example,both inner class and method of inner class are declared as static.As they are static only we are able to call First.Display.print(“Hello RamaKanth”) from main() method. Methods of static inner class can not access instance variables of the enclosing class.This is similar to the ruled that apply to static methods in ordinary class. Anonymous Inner Class An anonymous inner class is an inner class that does not have a name.Because they do not have a name,they must be instantiated at the same point thet are difined.The best example is the way we use an adapter class in window closing as coded below: AddWindowListener(new WindowAdopter() { public void windowClosing(WindowEvent e) { system.exit(0); } } Some facts about Nested Classes:

1. Like other classes,nested classes can be declared abstract and final.The meaning of these two modifiers is the same as for ordinary classes.

2. The access modifiers-private,public,protected and package may be used to restrict the access to nested classes just as they do not to other class members.

3. An inner class can have any accessibility,including private.

Page 50: Core Java SoftCopy

49

4. Inner classes,unless static,have access to the variables of the enclosing class instance.Additionally,inner classes defined in method scope have read access to finsl variables of the enclosing method.

Multithreading

A thread is a single sequential (separate) flow of control within program. Sometimes, it is called an execution context or a light weight process. A thread itself is not a program. A thread cannot run on it‟s own. Rather, it runs within a program. A program can be divided into a each package of code-Each representing a thread having its own separate flow of control. That is, a thread can‟t exist by itself. It is a part of a program. Light weight process: A thread is considered a light weight process because it runs within the context of a program (within the program)and takes advantage of the resources allocated to that program. Heavy weight process: In the heavy weight process, the control changes in between threads belonging to different processes (i.e. two different programs.).(In light weight process, the control changes in between threads belonging to same (one) process) Execution context: A thread will have its own execution stack and program counter. The code running within the thread works only within that context. Package Support of Threads: java.lang.Thread: In the java language, threads are objects that derive from java.lang. Thread class. We can subclass the Thread class to get the functionality of the thread. Thread is a concrete class. java.lang.Runnable: Runnable is an interface which provides an abstract method run() for a thread. java.lang.Object: This is the root class for every class and defines the three methods for use of threads.The methods are wait(),notify() and notifyAll(). Java language has two keywords related to the threads: volatile and synchronized.Both of these keywords help ensure the integrity of data that is shared between two concurrently running threads. run() method: The run() method is available both in Thread class and Runnable interface.We can subclass a Thread class and override the run() method.We write the specific code,which we would like to do by the thread,in the run() method is the heart of any Thread.run() method is called implicitly by the start() method. In java, we can create threads in two ways.---one by sub classing the Thread class and one by implementing Runnable interface. A program by subclassing the Thread class We can create threads by extending Thread class to our class. In the following program, the class Using Thread extends the class Thread. By this, every object of class Using Thread becomes implicitly a thread(i.e. it can utilize all the methods of Thread class). Example: printing 10 numbers by using a thread. Thread class is extended. File Name: UsingThread.java

Page 51: Core Java SoftCopy

50

public class UsingThread extends Thread //Thread class is extended { public void run() //write the code specific to the thread in run() method { try { for(int I=1;I<11;I++) { System.out.println(“Hello”+I);//prints Hellow 10 times Thread.sleep(1000); //with a gap of 1000 milliseconds }//which makes a thread to sleep(not functoing)for the specific time catch(InterruptedException e) { e.printStackTrace(); } System.out.println(“Done”); //When run‟s job is over Done is printed } public static void main(String args[]) { { UsingThread ut=new UsingThread(); Ut.start(); //a thread startd it‟s functoing with start() method only } } The run() method of UsingThread class overrides the empty run() method of Thread class with a for loop that iterates 10 times.Between each iteration it sleeps for 1 second(1000 milliseconds).After the loop has finished it prints Done. About sleep() method Sleep() is a method of Thread class with the following signature: Public static void sleep(long milliseconds)throws InterruptedException Sleep () method is static and throws (claims) a checked exception InterrupedException. That is, when ever we use, sleep () method, we should take care of InterruptedException by providing try-catch block.sleep() method makes a running(active) thread not to run(inactive) for the specified milliseconds of time. When the sleep time expires, the thread becomes automatically active. The active thread executes the run() method code. When the thread comes out of the run() method, it dies(naturally, the work assigned to it is over. That is why, we write the code that is to be done by the thread in run () method.

UsingThread ut=new UsingThread(); ut.start(); In the above first statement,a thread by name ut is created(ut is actually an object of

UsingThread class,but becomes implicitly a thread as the class has extended Thread class).The thread ut is in born state and is inactive.The inactive thread cannot call run() method.The thread in born state occupies the memory resources but cannot take microprocessor time.

In the second statement,we call the start() method on the thread.start() method implicitly calls run() method.The thread in run state is active and utilizes microprocessor time.

Page 52: Core Java SoftCopy

51

A program by implementing Runnable interface The above program is rewritten by implementing Runnable interface (instead of extending Thread class). Everything is same but for the small difference of writing implements instead of extends. Another difference is that the run() method in Thread class is a concrete method and it is left to the subclass to override it or not(any how, we will override).The same run() method in Runnable interface is an abstract method. that is, the subclass that implements the Runnable interface must override the run() method. Example: printing 10 numbers by using Runnable interface File Name: UsingRunnable.java public class UsingRunnable implements Runnable { public void run() { try { for(int I=1;I<11;I++) { System.out.println(“Hello”+I); Thread.sleep(1000); } } catch(InterruptedException e) { e.printStackTrace(); } System.out.println(“Done”); } public static void main(String args[]) { UsingRunnable ur=new UsingRunnable(); Thread t=new Thread(ur);//this line is extra than the previous program t.start(); } } We cannot call ur.start () directly and if called raises a compilation error. This is because the object ur (or the class UsingRunnable( is no way connected to the start() method of Thread class. To overcome this,java designers provided a way of passing ur as an argument to the Thread constructor.t.start() implicitly calls the run() method of UsingRunnable class. Instance of UsingRunnable class is passed as a parameter to the Thread constructor. And instead of starting the object ur,object of Thread class is started. This is the difference between the above two programs. Using Multiple threads We can execute different threads concurrently (and is the purpose of a multithreaded program).The source code includes three programs-FirstThread, SecondThread and TwoRuns. FirstThread and SecondThread classes extend Thread class.The objects of these classes are created and their start() methods are called from Two runs class. Example: to execute two run methods and observe with different sleep periods. File Name: TwoRuns.java class FirstThread extends Thread {

Page 53: Core Java SoftCopy

52

public void run() { for(int i=1;i<5;i++) { System.out.println(“First Thread:”+i); try

{ Thread.sleep(1000); } catch(InterruptedException e) { e.printStackTrace(); } } } }

class SecondThread extends Thread { public void run() { for(int i=1;i<5;i++) { System.out.println(“Second Thread:”+i)

try { Thread.sleep(1000); } catch(InterruptedException e) { e.printStackTrace(); } } } } public class TwoRuns { public static void main(String args[]) { FirstThread ft=new FiestThread(); //create the objects of the classes SecondThread st=new SecondThread(); //each object is a thread implicitly ft.start(); //start the threads st.start(); //there is not shortcut to start both the threads at a time try { ft.join(); st.join(); } //join method throws IonterruptedException catch(InterruptedException e) { e.printStackTrace(); } } } Output: First Thread 1 Second Thread 1 First Thread 2 Second Thread 2 First Thread 3 Second Thread 3 First Thread 4

Page 54: Core Java SoftCopy

53

Second Thread 4 Note:Change the sleep timings of both the run methods,and observe the output‟s

frequency. After running the above program,keep try-catch of join() methods in comments,and see

the defference in output(order of execution).

Life Cycle of a Thread Just like applets and servlets, threads too got a life cycle between their birth (thread object creation) and death (thread object garbage collection).life cycle constitutes different stages a thread can undergo in its life(it‟s existence). If your class is already extending any class (e.g., Applet or Frame), the choice left to you is only implementing Runnable interface. Otherwise, you are left with any choice. At any time, a thread is said to be in one of the several thread states. A thread just created (but not started), is in born state. The thread remains in this state until the thread‟s start() method is called; this causes the thread to enter the ready state. A thread in ready state is eligible to utilize microprocessor time. A thread enter the dead state when it‟s run() method completes or when it‟s stop method is called. A dead thread cannot enter again the run state as it is garbage collected. When running thread‟s sleep method is called, that thread enters the sleeping state. A sleeping thread enters the ready state again when the sleep time expires. A sleeping thread cannot use microprocessor, even if microprocessor is idle. When on a running thread, if suspend () method is called, the thread enters suspended state. A suspended thread becomes ready with resume () method. A suspends thread cannot use processor time, even if it is available. When on a running thread, if wait() method is called, the thread enters a waiting state where it will be waiting in a queue of threads(used in synchronization).The thread comes into ready state when notify() is issued on the thread by another thread. A thread enters the dead state when its method completes or stop () method is called. The stop () method sends a Thread Death object to the thread. ThreadDeath is a subclass of class Error.

Thread class The Thread class is included in java.lang package, a package that is implicitly imported into every program. The super class of Thread is Object class. Thread class plays a vital role in java‟s multithreading. Just like any other java class, the thread class is rich with its methods having different functionality. Following is the class signature: public class Thread extends Object implements Runnable Constructors Description public Thread() creates a thread with default name public Thread(String name) creates a thread with name public Thread(ThreadGroup group,String name) creates a thread in a thread group with name Fields When to use public final static int MIN_PRIORITY=1 to associate a thread with minimum priotity public final static int NORM_PRIORITY=5 to associate a thread with normal priority

Page 55: Core Java SoftCopy

54

public final static int MAX_PRIORITY=10 to associate a thread with maximum priority Methods What that give

public static native Thread currentThread() returns the current thread being executed on the microprocessor

public static native void sleep(long mills) throws InterruptedException

keeps thread in blocked state

public final String getName() returns the name of the thread

public final void setName(String name) sets a name to a thread

public final native Boolean isAlive() returns true if a thread is alive else false if dead

public boolean isInterrupted() returns true if a thread is interrupted

public void run() by default run method is called

public final int getPriority() returns the priority of the thread

public final void setPriority(int priority) sets a priority to a thread

public synchronized native void start() starts a thread

public final void stop() stops a thread and when stopped garbage collected

public final void suspend() to suspend a thread

public final void resume() to resume a thread which is suspended

Thread Priority The order of execution of multiple threads ion a single CPU, depends on the scheduling. The java runtime supports a scheduling algorithm called fixed priority scheduling. The algorithm schedules the threads based on their priority relative to other Runnable threads. Every java thread has a priority in the range Thread.MIN_PRIORITY(of constant 1) and Thread.MAX_PRIORITY (of constant 10).By default, each thread is given a priority of Thread.NORM_PRIORITY (of constant 5).Each new thread inherits the priority of the thread that creates it. The job of the thread scheduler is to keep the highest-priority thread running all the time and for the threads of same priority, time slices are allocated in round-robin fashion. A thread‟s priority can be adjusted with setPriotity () method. In the following program, different priorities are set to two different threads and their output is studied. Naturally, the thread with higher priority will execute first. Example: to set different priorities to threads. File Name: PriorityDemo.java public class PriorityDemo extends thread { public void run() { for(int i=0;i<5;i++) //currentThread()returns an object of Thread(that is being run on the microprocessor time) String str=Thread.currentThread().getName(); System.out.println(str+”:”I); } } public static void main(String args[]) { PriorityDemo pd1=new PriorityDemo(); //creating thread objects PriorityDemo pd2=new PriorityDemo();

Page 56: Core Java SoftCopy

55

pd1.setName(“First Thread”);//giving names for the threads pd2.setName(“Second Thread”); pd1.setPriority(Thread.MIN_PRIORITY);//setting priority to the threads pd2.setPriority(Thread.MAX_PRIORITY); pd1.start();//starting the threads pd2.start(); //to read to the priorities of threads System.out.println(“Priority of pd1:”+pd1.getPriority()); System.out.println(“Priority of pd2:”+pd2.getPriority()); } } Output: Second Thread:0 //thread of priority 10(MAX_PRIORITY)executes first Second Thread:1 Second Thread:2 Second Thread:3 Second Thread:4 Priority of pd1:1 //next,thread of priority 5(NORM_PRIORITY),the default of main executes Priority of pd2:10 First Thread:0 //thread of priority 1(MIN_PRIORITY)executes last First Thread:1 First Thread:2 First Thread:3 First Thread:4