oops concepts java

61
qwertyuiopasdfghjklzxcvbnmqwertyui opasdfghjklzxcvbnmqwertyuiopasdfgh jklzxcvbnmqwertyuiopasdfghjklzxcvb nmqwertyuiopasdfghjklzxcvbnmqwer tyuiopasdfghjklzxcvbnmqwertyuiopas dfghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghj klzxcvbnmqwertyuiopasdfghjklzxcvbn mqwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasdf ghjklzxcvbnmqwertyuiopasdfghjklzxc vbnmqwertyuiopasdfghjklzxcvbnmrty uiopasdfghjklzxcvbnmqwertyuiopasdf ghjklzxcvbnmqwertyuiopasdfghjklzxc vbnmqwertyuiopasdfghjklzxcvbnmqw JAVA OOP‘S CONCEPTS 5/10/2011 NGPVN

Upload: anjinayulu-anji

Post on 28-Nov-2014

370 views

Category:

Documents


0 download

DESCRIPTION

every prgm in this book was excuted and verified

TRANSCRIPT

Page 1: Oops Concepts Java

qwertyuiopasdfghjklzxcvbnmqwertyui

opasdfghjklzxcvbnmqwertyuiopasdfgh

jklzxcvbnmqwertyuiopasdfghjklzxcvb

nmqwertyuiopasdfghjklzxcvbnmqwer

tyuiopasdfghjklzxcvbnmqwertyuiopas

dfghjklzxcvbnmqwertyuiopasdfghjklzx

cvbnmqwertyuiopasdfghjklzxcvbnmq

wertyuiopasdfghjklzxcvbnmqwertyuio

pasdfghjklzxcvbnmqwertyuiopasdfghj

klzxcvbnmqwertyuiopasdfghjklzxcvbn

mqwertyuiopasdfghjklzxcvbnmqwerty

uiopasdfghjklzxcvbnmqwertyuiopasdf

ghjklzxcvbnmqwertyuiopasdfghjklzxc

vbnmqwertyuiopasdfghjklzxcvbnmrty

uiopasdfghjklzxcvbnmqwertyuiopasdf

ghjklzxcvbnmqwertyuiopasdfghjklzxc

vbnmqwertyuiopasdfghjklzxcvbnmqw

JAVA

OOP‘S CONCEPTS

5/10/2011

NGPVN

Page 2: Oops Concepts Java

2

THIS SMALL BOOK CONTAINS MANY CONCEPTS OF JAVA AND THE

PROGRAMING PART IS VERIFIED BY MY SELF IN TH EDIT PLUS AND

COMMAND PROMPT AND THE OUTPUT ARE DISPLAYED IN THIS BOOK IT

SELF .

Page 3: Oops Concepts Java

3

Constructors: If a class has any method with the same name as its class then it is

constructor method for that class. Used to initialize the objects upon creation. In

the absence of constructor method we have to specifically add a method for object

initialization. If no constructor is defined for the class then a default constructor is

provided by Java run time environment (Without Parameters). Constructor method

has no return type not even void. Code written inside constructor method is

automatically executed for every object creation of that class.

Constructor Overloading: Implementing more than one constructor inside a

single class

/*Program to implement constructor overloading*/

class Box

{

double width,height,depth;

Box(double w,double h,double d)

{

width=w;

height=h;

depth=d;

}

Box(double e)

{

width=e;

height=e;

depth=e;

}

void volume()

{

System.out.println("Volume of the box is"+(width*height*depth));

}

}

class OverloadConstructor

{

public static void main(String args[])

{

Box b1=new Box(3.2,4.5,6.7);

Box b2=new Box(3.4);

Box b3=new Box(1.1);

Page 4: Oops Concepts Java

4

b1.volume();

b2.volume();

b3.volume();

}

}

Output:

Volume of the box is96.48

Volume of the box is39.303999999999995

Volume of the box is1.3310000000000004

Method Overloading: Two methods are said to be overloaded if they have same

name and different signatures .Signature of method means number of arguments to

method and their types. Two methods are said to have different signatures if they

differ in number of arguments they receive or their types. Example Signature

Signature

int sum (int a, int b) sum(int,int)

float sum (int a, float b) sum(int,float)

double sum(double a , double b) sum(double,double)

void draw(); draw()

Note : return type and name of arguments are not part of signatures

/* Program to implement method overloading*/

class Addition

{

void sum(int a,int b)

{

System.out.println("result is"+(a+b));

}

float sum(float a,float b)

{

return (a+b);

}

double sum(double a,double b)

{

return (a+b);

}

}

class OverloadMethod

{

public static void main(String args[])

{

Addition a1=new Addition();

Page 5: Oops Concepts Java

5

a1.sum(3,4);

float x=a1.sum(3.4f,4.5f);

System.out.println("sum of floating point numbers"+x);

double y=a1.sum(3.45,4.56);

System.out.println("sum of double numbers"+y);

}

}

Output:

result is7

sum of floating point numbers7.9

sum of double numbers8.01

“this” Keyword: if the class scope variable name method scope variable name are

same then to differentiate these 2 we use ‘this‘ keyword. It always refers current

class object.

/* Program to implement ‗this‘ keyword*/

class A

{

int a=20;

void display()

{

int a=55;

System.out.println("method scope value of a is"+a);

System.out.println("class scope value of a is"+this.a);

}

}

class thisDemo

{

public static void main(String x[])

{

A y=new A();

y.display();

}

}

Output:

method scope value of a is55

scope value of a is20

Inheritance: Deriving a new class from existing class is called inheritance. The

existing class is called super/parent/base class, new class is called

Page 6: Oops Concepts Java

6

sub/child/derived class. „extends‟ is the keyword used to inherit the properties of

super class to sub class.

/* Program to implement inheritance*/

class Base

{

int a=20;

int b=30;

void sum()

{

System.out.println("Sum is"+(a+b));

}

}

class Derived extends Base

{

int c=50;

void sum()

{

System.out.println("Sum is"+(a+b+c));

}

}

class InheritDemo

{

public static void main(String s[])

{

Base b1=new Base();

b1.sum();

Derived d=new Derived();

d.sum();

}

}

Output:

Sum is50

Sum is100

METHOD OVERRIDING: Sub class can override the methods defined by the

super class. Overridden Methods in the sub classes should have same name, same

signature, same return type and may have either the same or higher scope than

super class method. Java implements Run Time Polymorphism/ Dynamic Method

Dispatch by Method Overriding. [Late Binding] Call to Overridden Methods is

Resolved at Run Time. Call to a overridden method is not decided by the type of

Page 7: Oops Concepts Java

7

reference variable Rather by the type of the object where reference variable is

pointing. While Overriding a Method, the sub class should assign either same or

higher access level than super class method.

/* Program to implement METHOD OVERRIDING */

class A

{

void show()

{

System.out.println("Hello This is show() in A");

}// End of show() Method

} // End of class A

class B extends A

{

void show()

{

System.out.println("Hello This is show() in B");

}// End of show() Method

} // End of class B

class override

{

public static void main(String args[])

{ // super class reference variable // can point to sub class object

A a1 = new A();

a1.show();

a1 = new B();

a1.show();

}

}

Output:

Hello This is show() in A

Hello This is show() in B

Dynamic Method Dispatch: Super class reference variable can refer to a sub class

object. Super class variable if refers to sub class object can call only overridden

methods. Call to an overridden method is decided by the type of object referred to.

/* Program to implement Dynamic Method Dispatch */

class A

{

void show()

{

Page 8: Oops Concepts Java

8

System.out.println("Hello This is show() in A");

}

}

class B extends A

{

void show()

{

System.out.println("Hello This is show() in B");

}

}

class C extends A

{

void show()

{

System.out.println("Hello This is show() in C");

}

}

class D extends A

{

void show()

{

System.out.println("Hello This is show() in D");

}

}

class override2

{

public static void main(String args[])

{

A a1 = new A();

a1.show();

a1 = new B();

a1.show();

a1 = new C();

a1.show();

a1 = new D();

a1.show();

}

}

Output:

Hello This is show() in A

Page 9: Oops Concepts Java

9

Hello This is show() in B

Hello This is show() in C

Hello This is show() in D

“super” Keyword: it can access super class variable

/* Program to implement ‗super‘ keyword*/

class Base

{

int a=20;

void display()

{

System.out.println("Super class a is :"+a);

}

}

class Derived extends Base

{

int a=40;

void display()

{

System.out.println("Sub class a is:"+a);

System.out.println("Super class a is :"+super.a);

}

}

class SuperDemo

{

public static void main(String[] args)

{

Base b=new Base();

b.display();

Derived d=new Derived ();

d.display();

}

}

Output:

Super class a is :20

Sub class a is:40

Super class a is :20

To acces superclass method

class Box

{

Page 10: Oops Concepts Java

10

double w,h,d;

Box(double a,double b,double c)

{

w=a; h=b; d=c;

}

void volume()

{

System.out.println("Volume of box is"+(w*h*d));

}

}

class Box1 extends Box

{

double xyz;

Box1(double a, double b ,double e,double f)

{

super(a,b,e);

xyz=f;

}

void display()

{

System.out.println("result is is"+(w*h*d*xyz));

}

}

class SuperDemo

{

public static void main(String s[])

{

Box b1=new Box(2.3,4.5,8.8);

b1.volume();

Box1 b2=new Box1(2.3,2.3,2.3,7.8);

b2.display();

}

}

Output:

Volume of box is91.08

result is is 94.90259999999996

Use of final keyword in java: final keyword in java can be used for following a-

class declaration, b-variable declaration, c-method declaration. final keyword for

class means class cannot be inherited.

Page 11: Oops Concepts Java

11

Final classes cannot have subclasses. final keyword used with variable declaration

makes it constant whose value cannot be changed. final keyword used with

method definition means method cannot be overridden by subclasses ( Makes

sense only when inheritance is used).

/* Program to implement ‗final‘ keyword*/

class ABC

{

//final int a;

final int a = 10;

int b;

double c;

//final static int d;

static int d;

ABC(int x,double c,int d)

{ b=x; this.c = c; this.d =d ;}

void show()

{

System.out.println("a="+a);

System.out.println("b="+b);

System.out.println("c="+c);

System.out.println("d="+d);

}

}

class ABCDemo

{

public static void main(String args[])

{

ABC a1 = new ABC(10,8,5);

ABC a2 = new ABC(-10,18,15);

ABC a3 = new ABC(67,80.56,50);

ABC a4 = new ABC(76,-6.45,95);

a1.show();

}

}

Output:

a=10

b=10

c=8.0

d=95

Page 12: Oops Concepts Java

12

class Pie

{

public static void main(String s[])

{

final double pi=3.1415;

pi=pi+3;

System.out.println("pi="+pi);

}

}

Final Object Reference: You can declare any object reference as final. Declaring

a Object reference as final does not mean that Object‘s state i.e attribute values

cannot be changed. We can change the values of attributes provided it is allowed.

Declaring a Object reference as final makes the reference itself as final and it

cannot point to any other object.

final circle c1 = new circle(20);

c1.radius = 30;//(ok)

circle c2 = new circle(30);

c1 = c2// (wrong)

c1 final object reference it cannot point to another Object

Use of static keyword in Java: There are Four different uses of static keyword in

java.1-static instance variables, 2-static methods,3-static classes, 4-static blocks.

Note :static field/methods of a class can be accessed/referenced even

withoutcreating the objects of that class [ Provided They are static].

Syntax : <classname> . <fieldname> OR <classname> .

<methodname>

static instance variables/fields: Any Field/Attribute/instance field of a class can

be declared as static. Declaring an instance field as static makes it class variable

that belongs to a whole class not an individual object. For a static fields of any

class, all the objects of that class share a common copy. Static field is just like a

global variable for a class that is allocated memory once and all objects of that

class share that common copy. Static field/instance variables are allocated space in

the heap area.

Static Methods: static methods can use only static data. Static methods can be

called/accessed /referenced even without creating the objects that class. Static

method cannot call non static methods.

Examples: Math.sqrt (all math functions)

Static method can declare local variables but from outside it can access only static

data(fields/methods)

Page 13: Oops Concepts Java

13

Syntax: <class name> . < method name(parameter list)>

/*program on static*/

class StaticDemo

{

static int x=44;

static int y=x+4;

static int z=x+5;

void display()

{

System.out.println("x="+x);

System.out.println("y="+y);

System.out.println("z="+z);

}

public static void main(String s[])

{

StaticDemo sd=new StaticDemo();

sd.display();

}

}

Output:

X=44

Y=48

Z=49

/*program on static*/

class Static

{

int a=20;

static int b=32;

public static void main(String s[])

{

System.out.println(b++);

System.out.println(b++);

Static sd1=new Static();

System.out.println(sd1.a++);

System.out.println(sd1.a++);

Static sd2=new Static();

System.out.println(sd2.a++);

System.out.println(sd2.a++);

Static sd3=new Static();

System.out.println(sd3.a++);

Page 14: Oops Concepts Java

14

System.out.println(sd3.a++);

System.out.println(b++);

}

}

Output:

32

20

21

20

21

20

21

34

Objects as Parameters To Methods : Objects are always passed by reference

w.r.t its instance field values i.e state of the object. ( State of object Can be

changed by using the same reference variable ) If you are changing the values of

instance fields by using same reference variable then changes will be eflected in

the calling program. [ That‘s what we mean by callByReference ]Objects are

always passed by value w.r.t. its reference. The Called Method cannot change the

passed parameter reference to some another object . The called method if tries to

change the reference of passed parameter then that change remains local only and

will not be reflected to calling method.

/*program on call by reference*/

class Test1

{

int a,b;

Test1(int i,int j)

{

a=i;

b=j;

}

void display(Test1 t)

{

t.a=t.a*5;

t.b=t.b/2;

System.out.println("A="+t.a);

System.out.println("B="+t.b);

}

}

Page 15: Oops Concepts Java

15

class Test

{

public static void main(String s[])

{

Test1 t1=new Test1(44,88);

System.out.println("before A and B values are"+t1.a+" "+t1.b);

t1.display(t1);

System.out.println("After A and B values are"+t1.a+" "+t1.b);

}

}

Output:

before A and B values are 44 88

A=220

B=44

After A and B values are220 44

/*program on call by value*/

class A

{

void show(int i,int j)

{

i=i*2;

j=j/2;

}

}

class Value

{

public static void main(String s[])

{

A a=new A();

int p=20,q=30;

System.out.println("before acessing P and Q values are"+p+" "+q);

a.show(p,q);

System.out.println("after acessing P and Q values are"+p+" "+q);

}

}

Output:

before acessing P and Q values are20 30

after acessing P and Q values are20 30

Page 16: Oops Concepts Java

16

Abstract Classes: When we define a class to be ―final‖, it cannot be extended. In

certain situation, we want to properties of classes to be always extended and used.

Such classes are called Abstract Classes. An Abstract class is a conceptual class.

An Abstract class cannot be instantiated – objects cannot be created. Abstract

classes provides a common root for a group of classes, nicely tied together in a

package.When a class contains one or more abstract methods, it should be declared

as abstract class. The abstract methods of an abstract class must be defined in its

subclass.We cannot declare abstract constructors or abstract static methods.

Abstract Classes Properties

A class with one or more abstract methods is automatically abstract and it

cannot be instantiated.

A class declared abstract, even with no abstract methods can not be

instantiated.

A subclass of an abstract class can be instantiated if it overrides all abstract

methods by implementation them.

A subclass that does not implement all of the superclass abstract methods is

itself abstract; and it cannot be instantiated.

/* program to demonstrate abstract classes and abstract methods*/

abstract class Figure{

int d1,d2;

abstract void area();

}

class Rectangle extends Figure{

Rectangle(int a,int b){

d1=a; d2=b;

}

void area(){

System.out.println("rectangle area : "+(d1*d2));

}

}

class Square extends Figure{

Square(int c){

d1=d2=c;

}

void area() {

System.out.println("Square area : "+(d1*d2));

}

}

class Triangle extends Figure{

Triangle(int e,int f){

Page 17: Oops Concepts Java

17

d1=e; d2=f;

}

void area() {

System.out.println("Triangle area : "+((d1*d2)/2));

}

}

class AbstractDemo{

public static void main(String[] args) {

Rectangle r=new Rectangle(20,30);

r.area();

Square s=new Square(25);

s.area();

Triangle t=new Triangle(40,20);

t.area();

}

}

Output:

rectangle area : 600

Square area : 625

Triangle area : 400

Interfaces:

Interface is a conceptual entity similar to a Abstract class.

Can contain only constants (final variables) and abstract method (no

implementation) - Different from Abstract classes.

Use when a number of classes share a common interface.

Each class should implement the interface.

Interfaces: An informal way of realising multiple inheritance:

An interface is basically a kind of class—it contains methods and

variables, but they have to be only abstract classes and final

fields/variables.

Therefore, it is the responsibility of the class that implements an interface

to supply the code for methods.

A class can implement any number of interfaces, but cannot extend more

than one class at a time.

Therefore, interfaces are considered as an informal way of realising

multiple inheritance in Java.

Page 18: Oops Concepts Java

18

Implementing Interfaces: Interfaces are used like super-classes who properties

are inherited by classes. This is achieved by creating a class that implements the

given interface as follows:

class ClassName implements InterfaceName [, InterfaceName2, …]{ //

Body of Class }

Extending Interfaces: Like classes, interfaces can also be extended. The new sub-

interface will inherit all the members of the superinterface in the manner similar to

classes. This is achieved by using the keyword extends as follows:

interface InterfaceName2 extends InterfaceName1 { // Body of

InterfaceName2 }

Inheritance and Interface Implementation:A general form of interface

implementation:

class ClassName extends SuperClass implements InterfaceName [,

InterfaceName2, …]{ // Body of Class }

This shows a class can extended another class while implementing one or more

interfaces. It appears like a multiple inheritance (if we consider interfaces as

special kind of classes with certain restrictions or special features).

INTERFACES IN JAVA: Java Does not support Multiple Inheritance directly.

Multiple inheritance can be achieved in java by the use of interfaces. We need

interfaces when we want functionality to be included but does not want to impose

implementation. Implementation issue is left to the individual classes

implementing the interfaces. Interfaces can have only abstract methods and final

fields. You can declare a variable to be of type interface. But you cannot create an

object belonging to type interface. Interface variable can point to objects of any

class implementing the interface. Another way of implementing Run Time

Polymorphism.

Similarities between Interfaces and classes:

• is compiled into byte code file

• can be either public,protected, private or package accessibility

• can not be public unless defined in the file having same name as interface

name

• serve as a type for declaring variables and parameters

Differences between Interfaces and classes:

• Declares only method headers and public constants

• Has no constructors

• Can be implemented by a class

• Can not extend a class

• Can extend several other interfaces

/*Program to illustrate interfaces*/

interface Arithmetic

Page 19: Oops Concepts Java

19

{

void add(int a,int b);

void sub(int a,int b);

void mul(int a,int b);

void div(int a,int b);

}

class A implements Arithmetic

{

public void add(int a,int b)

{

System.out.println("sum is"+(a+b));

}

public void sub(int a,int b)

{

System.out.println("diff is"+(a-b));

}

public void mul(int a,int b)

{

System.out.println("multiplication is"+(a*b));

}

public void div(int a,int b)

{

System.out.println("division is"+(a/b));

}

}

class InterfaceDemo

{

public static void main(String h[])

{

A a1=new A();

a1.add(4,5);

a1.sub(4,5);

a1.mul(4,5);

a1.div(6,3);

}

}

Output:

sum is9

diff is--1

multiplication is 20

Page 20: Oops Concepts Java

20

divison is2

interface Calculate

{

int compute(int x,int y);

void display(int a);

}

class Add implements Calculate

{

int res;

public int compute(int x,int y)

{

res=x+y;

return(res);

}

public void display(int a)

{

System.out.println("addition"+a);

}

}

class Multiply implements Calculate

{

int res;

public int compute(int x,int y)

{

res=x*y;

return(res);

}

public void display(int a)

{

System.out.println("multiplication"+a);

}

}

class InterfaceDemo

{

public static void main(String m[])

{

Add a1=new Add();

int x=a1.compute(3,4);

a1.display(x);

Page 21: Oops Concepts Java

21

Multiply m1=new Multiply();

int y=m1.compute(4,5);

m1.display(y);

}

}

Output:

Addition7

Multiplication20

Typecasting: Converting one data type to other data type. It is of 2 types a-

Implicit b-Explicit

Implicit: it is automatically if both data types are compatible and destination data

type is larger than source data type.

Explicit: if both data types are compatible and destination data type is not larger

than source data type.

We need to specify explicitly

/*program to implement typecasting*/

class ImpExp{

public static void main(String[] args){

int i=735;

float f;

byte b;

b=(byte)i;

f=i;

System.out.println(" Implicit Typecasting : "+i+"\n Explicit Typecasting : "+b);

}

}

Output:

Implicit Typecasting : 735

Explicit Typecasting : -33

Arrays in Java: Arrays in java are objects which belongs to class Array. Array

objects implements only static arrays. i.e once you create an array, its length is

fixed. User can not change the length after array creation. Java follows strict bound

checking for referencing array elements. If an attempt is made to reference the

elements outside the bounds then ―ArrayIndexOutOfBoundsException‖ will be

thrown at run time. Array elements can be referenced from 0 as LB to length-1 as

UB. Java also follows strict type checking for Array elements. If an attempt is

made to store the elements of another type then ―ArrayStoreException‖ will be

thrown at run time. Length is the attribute of each array which can be referenced

by <arrayreference> . <length>

Page 22: Oops Concepts Java

22

Syntax :

One-Dimensional Arrays : type[ ] arrayname = new type[size]; or

type arrayname[ ] = new type[size];

Examples :

1. int[ ] marks = new int[10]; //marks is an int array, length = 10 LB index =0 , UB

index = 9

2. float[ ] values = new float[20]; // values is an float array, length = 20 LB index

=0 , UB index =1 9

3. double cgpa[ ] = new double[5]; //cgpa is double array, length = 5 LB index =0

, UB index = 4

4. box[ ] b = new box[20]; //b is a box array, length = 20 LB index =0 , UB index =

19 (array of objects)

5. point points[ ] = new point[20]; // points is a point array, length = 20 LB index

=0 , UB index =19

Two-Dimensional Arrays : type[ ][ ] arrayname = new

type[row_size][col_size]; or

type arrayname[ ][ ] = new type[row_Size][col_Size];

row index varies from 0 to row_size – 1 column index varies from 0 to col_size –

1

Examples:

1. int[ ][ ] data = new int[3][3]; // data is 2-D int an array, row index 0 to 2 , col

index 0 to 2

2. float values[][] = new float[10][4];//values is 2-D float array, row index 0 to 9 ,

col index 0 to 3

3. int table[][] = {{ 0,0,0},{1,1,1}}; // 2 by 3 Array. Initializes first row to 0 &

second to 1

4. Variable Size Array:

int x[][] = new int[3][];

x[0] = new int[2];

x[1] = new int[4];

x[2] = new int[3];

/*Program to perform matrix addition multiplication?*/

class Matrix{

public static void main(String[] args) {

int a[][]={{1,2,3},{4,5,6},{7,8,9}};

int b[][]={{1,0,0},{0,1,0},{0,0,1}};

int c[][]=new int[3][3];

int d[][]=new int[3][3];

int i,j,k,s;

for(i=0;i<3;i++){

Page 23: Oops Concepts Java

23

for(j=0;j<3;j++){

s=0;

for (k=0;k<3 ;k++ ){

s=s+(a[i][k]*b[k][j]);

c[i][j]=s;

}

}

}

System.out.println("Matrix Multiplication is : ");

for(i=0;i<3;i++){

System.out.println();

for(j=0;j<3;j++){

System.out.print(c[i][j]+" ");

}

}System.out.println();

for(i=0;i<3;i++){

for(j=0;j<3;j++) {

d[i][j]=a[i][j]+b[i][j];

}

}

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

for(i=0;i<3;i++) {

System.out.println();

for(j=0;j<3;j++) {

System.out.print(d[i][j]+" ");

}

}System.out.println();

}

}

Output:

Matrix Multiplication is :

1 2 3

4 5 6

7 8 9

Matrix Addition is :

2 2 3

4 6 6

7 8 10

/*Program to copy array elements*/

Page 24: Oops Concepts Java

24

class ArrayCopy

{

public static void main(String[] args)

{

int a1[]={1,2,3,4,5};

int a2[]=new int[a1.length];

System.arraycopy(a1,2,a2,0,3);

System.out.println("Elements are ");

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

{

System.out.println(a2[i]);

}

}

}

Output:

Elements are

3

4

5

0

0

Packages are compiled as follows in command prompt

javac –d . class name.java

/* program to demonstrate access specifiers in packages*/

//Same class can acess all acess specifiers

package p1;

public class SameClass

{

int n=11;

private int n_private=22;

protected int n_protected=33;

public int n_public=44;

public void display()

{

System.out.println("Default access : "+n);

System.out.println("Private access : "+n_private);

System.out.println("Protected access : "+n_protected);

System.out.println("Public access : "+n_public);

}

Page 25: Oops Concepts Java

25

}

//Sub class in same package cannot acess private

package p1;

public class SubClass extends SameClass

{

public void display()

{

System.out.println("Default access : "+n);

//System.out.println("Private access : "+n_private);

System.out.println("Protected access : "+n_protected);

System.out.println("Public access : "+n_public);

}

}

//NonSub class in same package cannot acess private

package p1;

public class OtherClass

{

SameClass s=new SameClass();

public void display()

{

System.out.println("Default access : "+s.n);

//System.out.println("Private access : "+n_private);

System.out.println("Protected access : "+s.n_protected);

System.out.println("Public access : "+s.n_public);

}

}

//package p1 main class

import p1.SameClass;

import p1.SubClass;

import p1.OtherClass;

class MainClass1

{

public static void main(String[] args)

{

SameClass s1=new SameClass();

s1.display();

SubClass s2=new SubClass();

s2.display();

OtherClass s3=new OtherClass();

s3.display();

Page 26: Oops Concepts Java

26

}

}

Output:

Main class 1

Default access : 11

Private access : 22

Protected access : 33

Public access : 44

Default access : 11

Protected access : 33

Public access : 44

Default access : 11

Protected access : 33

Public access : 44

//Sub class in other package cannot acess private,default

package p2;

import p1.*;

public class SubOtherClass extends SameClass

{

public void display()

{

// System.out.println("Default access : "+n);

// System.out.println("Private access : "+n_private);

System.out.println("Protected access : "+n_protected);

System.out.println("Public access : "+n_public);

}

}

//Neithr Sub class in same package can acess public

package p2;

import p1.*;

public class NonSubClass

{

SameClass s=new SameClass();

public void display()

{

// System.out.println("Default access : "+n);

// System.out.println("Private access : "+n_private);

// System.out.println("Protected access : "+n_protected);

System.out.println("Public access : "+s.n_public);

Page 27: Oops Concepts Java

27

}

}

//package p2 main class

import p1.SameClass;

import p1.SubClass;

import p1.OtherClass;

import p2.SubOtherClass;

import p2.NonSubClass;

class MainClass2

{

public static void main(String[] args)

{

SubOtherClass s4=new SubOtherClass();

s4.display();

NonSubClass s5=new NonSubClass();

s5.display();

}

}

Output: Main class2

Protected access : 33

Public access : 44

Public access : 44

ACESSING PRIVATE DEFAULT PROTECTED PUBLIC

Same class

in same

package

yes yes yes Yes

Sub class in

same

package

No Yes Yes Yes

NonSub

class in same

package

No Yes Yes Yes

Sub class in

other

package

No no yes yes

Neithr Sub

class nor in

same

package

No No no yes

Page 28: Oops Concepts Java

28

EXCEPTIONS IN JAVA:

An exception is an abnormal condition that occurs run time. E.g divide by 0.

During execution of a method if any exceptional conditions occurs, Java run

time environment i.e java interpreter creates a suitable Exception object and

throws it.

Every Exception is basically an object belonging to Java‘s Exception class

Hierarchy.

Exceptions needs to be handled so that appropriate actions can be taken.

Programmer can also provide exception handling code. However if there is

no exception handling code present during runtime, then java interpreter

provides default exception handler.

Default Exception Handler Simply displays the name of the exception object

in string form and stops the execution of the program.

However , programmer can provide exception handling code and program‘s

execution can continue even after the occurrence of exception.

Every Exception type is basically an object belonging to class Exception

Throwable class is the root class of Exceptions.

Throwable class has two direct subclasses named Exception, Error

Types of Exceptions:

Unchecked Exceptions All Exceptions that extend the RuntimeException

or any one of its subclass are unchecked exceptions

• Unchecked Exceptions are unchecked by compiler.

• Whether you catch the exception or not compiler will pass the compilation

process.

• If Unchecked exception is caught then exception handling code will be

executed and program‘s execution continues.

• If Unchecked exception is not caught then java interpreter will provide the

default handler. But in this case execution of the program will be stopped by

displaying the name of the exceptions object.

Some Common Unchecked Exceptions

1. ArithmaticException (Divide By 0)

2. ArrayIndexOutOfBoundsException

3. ArrayStoreException

4. FileNotFoundException

5. NullPointerException

6. NumberFormatException

7. IllegalArumentsException

All Unchecked Exceptions directly or indirectly are sub classes of Run Time

Exception

Page 29: Oops Concepts Java

29

Checked Exceptions All Exceptions that extends the Exception or anyone its

subclass except Run Time Exception class are checked exceptions

• Checked Exceptions are checked by the Java compiler.

• There are two approaches that a user can follow to deal with checked

exceptions

Handling Checked Exceptions

• Inform the compiler that a method can throw an Exception.

• Catch the checked exception in try catch block

• If Checked exception is caught then exception handling code will be

executed and program‘s execution continues.

• If Checked exception is not caught then java interpreter will provide the

default handler. But in this case execution of the program will be stopped by

displaying the name of the exceptions object.

Some Common Checked Exceptions

1. IOException

2. ClassNotFoundExceptions

3. InterruptedException

4. NoSuchMethodException

Ways To Handle Checked Exceptions

Method 1: << Mention thru throws clause>>

1. throws clause is used with methods to indicate type of Exception a method

can throw

2. Specifically required for Checked Exceptions [ To Pass Compilation

process]. It can/may be used for unchecked exceptions also.

3. A method can throw as many exceptions.

Method 2 << Put the statements in try catch block and catch >>

Exception Handling Requires the Following four steps

1. Finding the problem (Identify the statements whose execution may result in

Exception. Put all those statements in a try{..} block)

2. Inform that an exception is thrown (Throw the Exception) << Note Down

throw vs throws>>

3. Receive the exception ( Catch the exception using catch{..} block)

4. Provide exception handling code in catch block.

Important Points :

1. try {} block may have one or multiple statements.

2. try{} block may throw a single type of Exception or multiple exceptions. But at

a time it can throw only single type of exception.

3. There can be multiple catch() { .. } blocks associated with single try{} block.

4. If try{} block can throw multiple exceptions then user should catch all

exceptions. (one catch block for each type of exception)

Page 30: Oops Concepts Java

30

Throwing Unchecked Exception

1. Create an InvalidBOXException which will be thrown by the constructor of the

BOX class whenever an attempt will be made to create an invalid BOX object.

(Any Dimension = 0 or < 0).

2. Create an InvalidTriangleException which will be thrown whenever an attempt

will be made to create an invalid Triangle object. (In Triangle sum of two sides

must be > third side).

Checked Exceptions

• Make your exception class extends Exception class or any one of its subclass

except RumtimeException.

• Checked Exceptions needs to either caught or informed by use of throws

clause

• Note down that throw clause is used to throw the exception where as throws

clause is used to inform that an exception is thrown by the method.

• Throw clause is used inside method body where as throws clause is used

with first line of the method.

• Throws clause can be used to inform both type of exceptions. But in case a

method is throwing a unchecked exception then it is not compulsory to

inform.

• In case a method is throwing a checked Exception, then it has either to

caught the exception or informs by using throws clause or it can do both.

Use of finally Clause

• finally statement can be used to handle an exception that is not caught by

previous statements.

• finally block may be added immediately after try block or after the last catch

block.

• finally block in general used to perform housekeeping operations such as

closing files or releasing system resources.

• Finally block when present is guaranteed to execute regardless of whether an

exception is thrown or not.

• If you want then finally block can be used to handle any exception generated

within a try block.

/* program to handle exceptions using try, catch and finally*/

class Except

{

public static void main(String[] args)

{

int a=64,b;

b=args.length;

try

Page 31: Oops Concepts Java

31

{

int c=a/b;

System.out.println("RESULT OF A/B IS :"+c);

}

catch (ArithmeticException e)

{

e.getMessage();

}

finally

{

System.out.println("exception case caught and solved");

}

}

}

Output:

exception case caught and solved

/* Program to create own exception*/

class OwnException extends Exception{

OwnException(String msg){

super(msg);

}

}

class MyException{

public static void main(String a[]){

int marks=Integer.parseInt(a[0]);

try{

if(marks<0||marks>100){

throw new OwnException("Marks should be in b/w 0 to 100");

}else

Page 32: Oops Concepts Java

32

System.out.println("entered marks are"+marks);

}catch(OwnException e){

System.out.println(e.getMessage());

}

}

}

/*Program to generate user defined exception*/

class UserException extends Exception

{

UserException(String msg)

{

super(msg);

}

}

class OwnException

{

public static void main(String x[])

{

int marks=Integer.parseInt(x[0]);

try

{

if(marks<0||marks>100)

{

throw new UserException("Marks should be in b/w 0 to 100");

}

else

System.out.println("marks :"+marks);

}catch(UserException e)

{

System.out.println(e.getMessage());

}

}

}

String Handling:

Page 33: Oops Concepts Java

33

class StringExs{

public static void main(String[] args) {

String s1="object";

System.out.println(s1); //object

byte[] b1=s1.getBytes();

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

System.out.print(b1[i] +" ");//111 98 106 101 99 116

}

System.out.println();

char ch[]={'N','G','P','V','N'};

String s2=new String(ch);

System.out.println(s2);//NGPVN

System.out.println(s2.charAt(2));//P

String s3=new String(ch,1,3);

System.out.println(s3);//GPV

byte b[]={10,45,67,34,68,66};

String s4=new String(b);

System.out.println(s4);//-C"DB

String s5=new String(b,2,4);

System.out.println(s5);//C"DB

System.out.println("NAGAPAVAN".length());//9

System.out.println("NAGAPAVAN".toLowerCase());//nagapavan

System.out.println(s1.length());//6

String s6="oriented";

String s7=s1+s6;

System.out.println(s7);//objectoriented

String s8="concept";

String s9=s7.concat(s8);

System.out.println(s9);//objectorientedconcept

String s10=20+52+"sum is"+72;

System.out.println(s10);//72sum is72

char[] ch1=new char[21];

s9.getChars(2,12,ch1,0);

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

System.out.print(ch1[i] +" ");//j e c t o r i e

n t

}

System.out.println();

char[] ch2=s1.toCharArray();

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

Page 34: Oops Concepts Java

34

System.out.print(ch2[i] +" ");//o b j e c t

}

System.out.println();

System.out.println(s1.equals(s2));//false

System.out.println(s1.equalsIgnoreCase(s2));//false

String s11="Now its the time for all good men to aid for their country";

System.out.println(s11);//Now its the time for all good men to aid for their country

String s12=s11.toUpperCase();

System.out.println(s12);//NOW ITS THE TIME FOR ALL GOOD MEN TO AID

FOR THEIR COUNTRY

String s13="Indian team will start preparation for the matches";

System.out.println(s13);//Indian team will start preparation for the matches

String s14=s13.toUpperCase();

System.out.println(s14);//INDIAN TEAM WILL START PREPARATION FOR

THE MATCHES

String s15=s14.toLowerCase();

System.out.println(s15);//indian team will start preparation for the matches

System.out.println(s11.substring(20));// all good men to aid for their country

System.out.println(s11.substring(20,40));// all good men to ai

System.out.println("NAGAPAVAN".substring(4));//PAVAN

System.out.println(s1.replace('j','t'));//obtect

System.out.println(s11.regionMatches(4,s12,6,10));//false

System.out.println(s11.regionMatches(14,s13,17,17));//false

System.out.println(s12.regionMatches(4,s14,6,10));//false

System.out.println(s11.regionMatches(true,4,s12,6,10));//false

System.out.println(s9.startsWith("obj"));//true

System.out.println(s9.endsWith("cept"));//true

String s16="NGPVN";

String s17="NGPVN";

String s18=s16;

if(s16==s17){

System.out.println("NAGAPAVAN");//NAGAPAVAN

}else{

System.out.println("NGPVN");

}

if(s16.equals(s17)) {

System.out.println("NAGAPAVAN");//NAGAPAVAN

}else{

System.out.println("NGPVN");

}

Page 35: Oops Concepts Java

35

if(s16==s18){

System.out.println("NAGAPAVAN");//NAGAPAVAN

}else{

System.out.println("NGPVN");

}

if(s16.equals(s18)){

System.out.println("NAGAPAVAN");//NAGAPAVAN

}else{

System.out.println("NGPVN");

}

System.out.println(s16.compareTo(s17));//0

System.out.println(s17.compareTo(s16));//0

System.out.println(s11.indexOf('t'));//5

System.out.println(s11.lastIndexOf('t'));//56

System.out.println(s11.indexOf("to"));//35

System.out.println(s11.lastIndexOf("to"));//35

System.out.println(s11.indexOf("to",35));//35

System.out.println(s11.lastIndexOf("to",35));//35

}

}

String Buffers:

class StringBuff {

public static void main(String[] args) {

StringBuffer sb1=new StringBuffer();

System.out.println(sb1.length());//0

System.out.println(sb1.capacity());//16

sb1.ensureCapacity(10);

System.out.println(sb1.capacity());//16

StringBuffer sb=new StringBuffer("object");

sb.append("oriented");

System.out.println(sb);//objectoriented

System.out.println(sb.length());//14

System.out.println(sb.capacity());//22

sb.ensureCapacity(10);

System.out.println(sb.capacity());//22

sb.insert(6," ");

System.out.println(sb);//object oriented

System.out.println(sb.length());//16

sb.setCharAt(10,'a');

System.out.println(sb);//object oraented

Page 36: Oops Concepts Java

36

System.out.println(sb.reverse());//detnearo tcejbo

System.out.println(sb.reverse());//object oraented

sb.deleteCharAt(10);

System.out.println(sb);//object orented

sb.delete(6,13);

System.out.println(sb);//objected

}

}

String Tokenizer

import java.util.*;

class StringToken {

public static void main(String[] args) {

StringTokenizer st=new StringTokenizer("hi how are you?");

System.out.println(st.hasMoreTokens());//true

System.out.println(st.countTokens());//4

while(st.hasMoreTokens()){

System.out.print(st.nextToken());//hihowareyou?

}

System.out.println();

StringTokenizer st1=new StringTokenizer("hi,how,are:you?",",:,");

System.out.println(st1.hasMoreTokens());//true

System.out.println(st1.countTokens());//4

while(st1.hasMoreTokens()){

System.out.print(st1.nextToken());//hihowareyou?

}

System.out.println();

StringTokenizer st2=new StringTokenizer("hi,how,are:you?",",:,",true);

System.out.println(st2.hasMoreTokens());//true

System.out.println(st2.countTokens());//7

while(st2.hasMoreTokens()){

System.out.print(st2.nextToken());//hi,how,are:you?

}

}

}

Collections in Java:

• Group of Objects treated as a single Object.

• Take group of students and maintain it as a LinkedList. <<Linked List is a

Collection>>

• Java provides supports for manipulating collections in the form of

Page 37: Oops Concepts Java

37

1. Collection Interfaces

2. Collection Classes

• Collection interfaces provide basic functionalities whereas collection classes

provides their concrete implementation

Collection Interfaces

There are Five Collection Interfaces

1. Collection

• Enables You to work with collections. << Top of Collection Hierarchy>>

2. List

• Extends Collection to handle list of elements [objects]

• Allows duplicate elements in the list

• Uses indexing technique starting with 0 to access elements

3. Set

• Extends Collection to handle set of elements [objects], which must contain

unique elements

4. SortedSet

• Extends Set to handle sorted elements in a set

Collections also uses following interfaces:

1. Comparator , 2. Iterator 3. ListIterator 4. RandomAccess

Collection Classes

• Collection classes are standard classes that implement collection interfaces

• Some Collection Classes are abstract and some classes are concrete and can

be used as it is.

• Important Collection Classes:

1. AbstractCollection

2. AbstractList

3. AbstractSequentialList

4. LinkedList

5. ArrayList

6. AbstractSet

7. HasSet

8. LinkedHashSet

9. TreeSet

Important Method in Collection Interfaces

1. boolean add(Object obj) / boolean addAll(Collection c)

• Adds in to collection either a single Object or all elements from another

collection. [ Addition only in the end ]

2. void clear() // clears all elements from the Collection

3. boolean contains(Object obj)

• Returns true if obj is there in the collection otherwise false

Page 38: Oops Concepts Java

38

4. boolean containsAll(Collection c)

• Returns true if invoking collection contains all elements of c

5. boolean equals(Object obj)

• Returns true if invoking collection and obj are equal or not

6. boolean isEmpty()

• Returns true if invoking collection is Empty otherwise false

7. int size() // returns size of collection

8. boolean remove(Object obj) / boolean removeAll(Collection c)

9. Iterator iterator()

• Returns an iterator for a collection for traversing purpose

Important Method in List Interfaces

1. boolean add(int index, Object obj) / boolean addAll(int index, Collection c)

• Adds in to collection either a single Object or all elements from another

collection at a mentioned index.

2. Object get(int index)

• Return object at given index. Index >=0 and < size();

3. int indexOf(Object obj)

• Returns index of obj in the invoking collection otherwise -1

4. int lastIndexOf(Object obj)

• Returns index of obj in the invoking collection from last

otherwise -1 will be returned if obj not found

5. ListIterator listIterator()

• Returns a list iterator for a given collection

• ListIterator allows both way traversal . Iterator allows only forward traversal

6. Object remove(int index)

• Removes elements from invoking collection at index. iIndex >=0 and <

size();

7. Object set(int index,Object obj)

• Sets the obj as elements for location specified by index. Index >=0 and <

size();

ArrayList class

• Supports Dynamic Arrays that can grow as needed.

• Variable length array of object references

• ArrayList can increase or decrease in size.

• Earlier versions of java supports dynamic arrays by a legacy class Vector.

public class ArrayList<E>

extends AbstractList<E>

implements List<E>, RandomAccess, Cloneable, Serializable

<E> Type of the Objects/Elements stored

Types of ArraysList

Page 39: Oops Concepts Java

39

1. Unparametrized ArrayLists

• Supported in earlier versions of Java (1.3 and earlier)

• Can store/handle objects of any type.

2. Parametrized ArrayLists

• Supported in later versions after 1.4 onwards

• Can handle objects of only mentioned type

Note :

If you are using unparametrized arraylists and are using latest java compiler the use

the following to compile:

javac -Xlint <sourcefile>

ArrayList Constructors

1. ArrayList()

• Empty ArrayList() size() =0

• Examples :

ArrayList arr = new ArrayList(); // Unparametrized Type

ArrayList<BOX> boxes = new ArrayList();//parametrized Type

ArrayList<Student> students = new ArrayList<Student>();//

parametrized Type

2. ArrayList(Collection c)

• Creates an ArrayList which is initialized with elements from other collection

3. ArrayList(int capacity)

• Creates an arraylist with initial capacity.

• Examples

ArrayList arr = new ArrayList(10);

ArrayList<BOX> boxes = new ArrayList(10);

ArrayList<Student> students = new ArrayList(20);

ArrayList<Student> students1 = new ArrayList<Student>(20);

Iterator Interface

• Allows the traversal of collections only in forward direction

• All Collections use iterator interface and provides method for attaching

iterator for any collection. Iterator iterator();

Methods :

• boolean hasNext()=(Returns true/false if there exists next element or not)

• E next() / Object next()=(Returns the next element. Used in conjunction with

hasNext())

• void remove()=(Removes the element from location pointed to by iterator )

ListIterator Interface

Page 40: Oops Concepts Java

40

• Extends Iterator interface, Allows both way traversal ListIterator

listIterator();

Methods :

• boolean hasNext() / boolean hasPrevious()=Returns true/false if there exists

next/previous element or not

• E next() / Object next() || E previous() / Object previous()=Returns the

next/previous element Used in conjunction with hasNext()/hasPrevious

• void remove() / void add(E obj)=Removes/adds the eListIterator

Interfacelement from/to location pointed to by iterator

• int nextIndex() /int previousIndex()= Returns the index of previous/next

element index

LinkedList class: Extends Abstract Sequential List, implements List and Queue

interfaces Arranges the elements of a collection as Linked List where each element

knows about the location of successor elements. Generic Declaration: class

LinkedList<E> <E> Type of objects that it will hold.

Constructors :

LinkedList() ; // Creates an Empty Linked :ist

LinkedList(Collection <? Extends E> c)Creates a linked list that is

initialized with the elements of collection c.

Important Methods

• void addFirst(E obj) / void addLast(E obj)=Adds element E to first and last

of this linked list

• E getFirst() / E getLast()=Gets the First/Last Element from the list

• E removeFirst() / E removeLast()=Removes and returns the first/last element

from the list

/*Program to illustrate Collections */

import java.util.*;

public class CollectionsTest{

public static void main(String[] args) {

List l = new ArrayList();

Map m = new TreeMap();

Set s = new TreeSet();

l.add(new Integer(1));

l.add(new Integer(4));

l.add(new Integer(3));

l.add(new Integer(2));

l.add(new Integer(3));

m.put(new Integer(1), "A");

m.put(new Integer(4), "B");

m.put(new Integer(3), "C");

Page 41: Oops Concepts Java

41

m.put(new Integer(2), "D");

m.put(new Integer(3), "E");

s.add(new Integer(1));

s.add(new Integer(4));

s.add(new Integer(3));

s.add(new Integer(2));

s.add(new Integer(3));

System.out.println("List");

Iterator i = l.iterator();

while (i.hasNext())

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

System.out.println("Map using keys");

i = m.keySet().iterator();

while (i.hasNext())

System.out.println(m.get(i.next()));

System.out.println("Map using entries");

i = m.entrySet().iterator();

while (i.hasNext())

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

System.out.println();

System.out.println("Set");

i = s.iterator();

while (i.hasNext())

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

}

}

Output:

List

1

4

3

2

3

Map using keys

A

D

E

B

Map using entries

1=A

Page 42: Oops Concepts Java

42

2=D

3=E

4=B

Set

1

2

3

4

Programs

Reading inputs in java from key board

1st

using buffered reader

import java.io.*;

class ReadDemo1{

public static void main(String[] args)throws IOException {

InputStreamReader isr =new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

System.out.println("Enter 1st Number");

int a=Integer.parseInt(br.readLine());

System.out.println("Enter 2nd Number");

int b=Integer.parseInt(br.readLine());

int c=a+b;

System.out.println("Result is"+c);

}

}

Output:

2

nd using JOptionPane

import javax.swing.*;

class ReadDemo2{

public static void main(String[] args){

int a, b,c;

String s1,s2;

s1=JOptionPane.showInputDialog("enter first number");

s2=JOptionPane.showInputDialog("enter second number");

Page 43: Oops Concepts Java

43

a=Integer.parseInt(s1);

b=Integer.parseInt(s2);

c=a+b;

JOptionPane.showMessageDialog(null,"result is"+c);

}

}

Output:

3

rd using scanner

import java.util.*;

class ReadDemo3{

public static void main(String[] args) {

Scanner s1=new Scanner(System.in);

System.out.println("Enter 1st number");

int a=Integer.parseInt(s1.nextLine());

System.out.println("Enter 2nd number");

int b=Integer.parseInt(s1.nextLine());

int c=a+b;

System.out.println("result is"+c);

}

}

Output:

Program to find prime numbers

class Prime{

public static void main(String s[]){

int n=Integer.parseInt(s[0]);

int r, c;

for(int i=1;i<=n;i++){

Page 44: Oops Concepts Java

44

c=0;

for(int j=1;j<=i;j++){

if(i%j==0){

c++;

}

}if(c==2)

System.out.print(i);

}

}

}

Output:

java Prime 11

2 3 5 7 11

Given no is palindrome r not

class Palindrome {

public static void main(String s[]) {

int n= Integer.parseInt(s[0]);

int d=n,r,sum=0;

while(n>0){

r=n%10;

sum=(sum*10)+r;

n=n/10;

}

if(sum==d){

System.out.println("Given No is Palindrome!");

}else

System.out.println("Given No is not Palindrome!");

}

}

Output:

java Palindrome 15351

Given No is Palindrome!

Given no is Armstrong r not

class Armstrong {

public static void main(String s[]) {

int n= Integer.parseInt(s[0]);

int d=n,r,sum=0;

while(n>0){

r=n%10;

sum=sum+(r*r*r);

Page 45: Oops Concepts Java

45

n=n/10;

}

if(sum==d) {

System.out.println("Given No is armstong!");

}else

System.out.println("Given No is not armstong!");

}

}

Output:

java Armstrong 153

Given No is armstong!

/* program to check whether the given String is palindrome or not without

using reverse method*/

class Palindrome{

public static void main(String[] args) {

char ch[]={'m','a','d','a','m'};

String s=new String(ch) ;

int i=0,j=0,flag=0;

j=s.length()-1;

while(i<j){

if(ch[i]==ch[j]){

flag=1;

}else{

flag=0;

break;

}i++; j--;

}if(flag==1){

System.out.println("Given String is Palindrome!");

}else{

System.out.println("Given String is Not Palindrome!");

}

}

}

Output:

Given String is Palindrome!

/* program to check whether the given String is palindrome or not */

class Palindrome{

public static void main(String[] args) {

String s="LIRIL";

StringBuffer sb=new StringBuffer(s);

Page 46: Oops Concepts Java

46

sb.reverse();

String s1=sb.toString();

if(s.equals(s1)){

System.out.println("Given String is Palindrome!");

}else{

System.out.println("Given String is Not Palindrome!");

}

}

}

Output:

Given String is Palindrome!

/*program to arrange strings in alphabetical order*/

class AlphaArange{

public static void main(String[] args) {

String s[]={"abc","abe","abd","aaa","aaaa"};

System.out.println("Before Sorting:");

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

System.out.println(s[i]+"");

}

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

for (int j=i+1;j<s.length ;j++ ){

if (s[i].compareTo(s[j])>0){

String temp=s[i];

s[i]=s[j];

s[j]=temp;

}

}

}

System.out.println("After Sorting:");

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

System.out.println(s[i]+"");

}

}

}

Output:

Before Sorting:

abc

abe

abd

aaa

Page 47: Oops Concepts Java

47

aaaa

After Sorting:

aaa

aaaa

abc

abd

abe

/*program to read characters from keyboard until typing the letter q for

quitting*/

import java.io.*;

class ReadChar{

public static void main(String[] args) throws IOException{

InputStreamReader isr =new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

System.out.println("Type q for quit");

int c;

while((c=br.read())!='q'){

System.out.print((char)c);

}

}

}

Output:

Type q for quit

NAGAPAVAN NGPVN Q HI asd q

NAGAPAVAN NGPVN Q HI asd

/*program to read strings from keyboard until typing the stop for quitting*/

import java.io.*;

class ReadString{

public static void main(String[] args) throws IOException{

String s;

InputStreamReader isr =new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

System.out.println("Type stop for quit");

while(!(s=br.readLine()).equals("stop")){

System.out.print(s);

}

}

}

Output:

Type stop for quit

Page 48: Oops Concepts Java

48

NAGAPAVAN

NAGAPAVAN NGPVN

NGPVN NAGA

NAGA pavan

pavan

stop

/*Write a java program to read a text file and count the number of words and

lines in that file*/

import java.io.*;

import java.util.*;

class Count{

public static void main(String[] args)throws IOException {

File f=new File("abc.txt");

Scanner s=new Scanner(f);

int wc=0;

int lc=0;

while(s.hasNextLine()){

lc++;

Scanner s1=new Scanner(s.nextLine());

while(s1.hasNext()) {

s1.next();

wc++;

}

}System.out.println("number of words "+wc);

System.out.println("number of lines "+lc);

}

}

Output:

number of words 7

number of lines 3

/*Program to read a file called “num.txt” and calculate the sum of first 5

numbers*/

import java.io.*;

Page 49: Oops Concepts Java

49

import java.util.*;

public class DoubleValues {

public static void main(String[] args)throws FileNotFoundException {

Scanner input = new Scanner(new File("numbers.txt"));

double sum = 0.0;

for (int i = 1; i <= 5; i++){

double next = input.nextDouble();

System.out.println("number = " + next);

sum += next;

}

System.out.println("Sum = " + sum);

}

}

Output:

number = 25.25

number = 55.23

number = 36.36

number = 45.36

number = 36.25

Sum = 198.45

/* program to read a file named “emp.txt” and calculate the number of

working hours of a particular employee*/

import java.io.*;

import java.util.*;

class EmployeeFile{

public static void main(String[] args)throws Exception{

Scanner c=new Scanner(System.in);

System.out.println("enter name");

String searchname=c.nextLine();

boolean found=false;

File f=new File("emp.txt");

Scanner input=new Scanner(f);

while(input.hasNextLine()) {

String line=input.nextLine();

Page 50: Oops Concepts Java

50

Scanner linescan=new Scanner(line);

int id=linescan.nextInt();

String name=linescan.next();

if(name.equalsIgnoreCase(searchname)) {

processLine(linescan,id,name);

found=true;

}

}if(!found)

System.out.println(searchname+"not found");

}public static void processLine(Scanner linescan,int id,String searchname) {

double s=0.0;

int c=0;

while(linescan.hasNextDouble()) {

s=s+linescan.nextDouble();

c++;

}

double avg=s/c;

System.out.println(searchname+"(ID#"+id+")worked

hours"+s+"("+avg+"hours/day)");

}

}

/* Program to draw rectangle, polygon, circle, oval, line, string, arc*/

import java.applet.*;

import java.awt.*;

/*<applet code="Fig.class" width=200 height=200></applet>*/

public class Fig extends Applet{

public void paint(Graphics g){

int x[]={1,2,3,4,5,6,7};

int y[]={8,9,10,11,12,13,14};

g.drawString("RaMsHyAm",5,10);

g.drawRect(30,30,35,30);

g.drawRoundRect(25,25,45,50,6,6);

g.setColor(Color.red);

g.fillRect(100,80,50,20);

g.fillRoundRect(100,20,25,20,3,3);

g.drawOval(100,100,20,30);

g.fillOval(140,140,20,30);

g.drawArc(18,18,10,15,100,100);

g.drawPolygon(x,y,x.length);

g.fillPolygon(x,y,y.length);

Page 51: Oops Concepts Java

51

}

}

Output:

/* Program to generate Mouseevents keyevents and Windowevents*/

import java.awt.*;

import java.awt.event.*;

public class EventsDemo extends Frame implements MouseListener,

MouseMotionListener, KeyListener, WindowListener {

String msg="";

EventsDemo(){

addMouseListener(this);

addMouseMotionListener(this);

addKeyListener(this);

addWindowListener(this);

setSize(400,400);

setVisible(true);

}

public void mouseEntered(MouseEvent m) {

msg="Mouse Entered";

setBackground(Color.red);

repaint();

}

public void mouseExited(MouseEvent m) {

Page 52: Oops Concepts Java

52

msg="Mouse Exited";

setBackground(Color.blue);

repaint();

}

public void mousePressed(MouseEvent m) {

msg="Mouse Pressed";

setBackground(Color.green);

repaint();

}

public void mouseReleased(MouseEvent m) {

msg="Mouse Released";

setBackground(Color.yellow);

repaint();

}

public void mouseMoved(MouseEvent m) {

msg="Mouse Moved";

setBackground(Color.orange);

repaint();

}

public void mouseDragged(MouseEvent m) {

msg="Mouse Dragged";

setBackground(Color.pink);

repaint();

}

public void mouseClicked(MouseEvent m) {

msg="Mouse Clicked";

setBackground(Color.cyan);

repaint();

}

public void keyPressed(KeyEvent k) {

msg="key Pressed";

setBackground(Color.red);

repaint();

}

public void keyReleased(KeyEvent k) {

msg="key released";

setBackground(Color.blue);

repaint();

}

public void keyTyped(KeyEvent k) {

Page 53: Oops Concepts Java

53

msg="Key Typed";

setBackground(Color.green);

repaint();

}

public void windowOpened(WindowEvent e ){

msg="windowOpened";

setBackground(Color.green);

repaint();

}

public void windowClosing(WindowEvent e) {

System.exit(0);

}

public void windowClosed(WindowEvent e) {

msg="windowClosed";

setBackground(Color.black);

repaint();

}

public void windowIconified(WindowEvent e) {

msg="windowIconified";

setBackground(Color.blue);

repaint();

}

public void windowDeiconified(WindowEvent e) {

msg="windowDeiconified";

setBackground(Color.yellow);

repaint();

}

public void windowActivated(WindowEvent e) {

msg="windowActivated";

setBackground(Color.red);

repaint();

}

public void windowDeactivated(WindowEvent e) {

msg="windowDeactivated";

setBackground(Color.cyan);

repaint();

}

public void paint(Graphics g) {

g.drawString(msg,100,120);

}

Page 54: Oops Concepts Java

54

public static void main(String x[]){

EventsDemo m=new EventsDemo();

}

}

/*Program to illustrate the synchronized keyword?*/

class SharedAccount {

private double balance;

public SharedAccount(double initialAmount) {

balance=initialAmount;

}

public synchronized void completeTransaction(double amount){

double temp=balance+amount;

if(amount<0){

System.out.println("withdrawing:"+Math.abs(amount));

}else

System.out.println("depositing:"+amount);

try{

Thread.sleep(1000);

}

catch(InterruptedException e){

System.out.println("transaction interrupted");

}

balance=temp;

System.out.println("current balance:"+balance);

}

}

class SharedAccountClient implements Runnable{

SharedAccount sa;

double transaction;

public SharedAccountClient(SharedAccount sa){

this.sa=sa;

}public void SetTransaction(double transaction){

this.transaction=transaction;

}public void run(){

sa.completeTransaction(transaction);

}

}

class SharedAccountDriver{

public static void main(String x[]){

SharedAccount sa=new SharedAccount(400);

Page 55: Oops Concepts Java

55

SharedAccountClient c1=new SharedAccountClient(sa);

SharedAccountClient c2=new SharedAccountClient(sa);

double x1=1000;

double x2=-400;

c1.SetTransaction(x1);

c2.SetTransaction(x2);

Thread t1=new Thread(c1);

Thread t2=new Thread(c2);

t1.start();

t2.start();

}

}

Output:

depositing:1000.0

current balance:1400.0

withdrawing:400.0

current balance:1000.0

/*Write a java program to demonstrate synchronized keyword in threads*/

class Callme{

void call(String msg) {

System.out.print(" [ "+msg);

try {

Thread.sleep(1500);

}catch (InterruptedException e) {

System.out.println("Interrupted");

}System.out.println(" ] ");

}

}

class Caller implements Runnable{

String msg;

Thread t;

Callme target;

public Caller(Callme targ,String s) {

target=targ;

msg=s;

t=new Thread(this);

t.start();

}public void run() {

synchronized(target) {

target.call(msg);

Page 56: Oops Concepts Java

56

}

}

}

class Synchronised {

public static void main(String[] args) {

Callme target=new Callme();

Caller ob1=new Caller(target,"Hello");

Caller ob2=new Caller(target,"Sychronized");

Caller ob3=new Caller(target,"World");

try {

ob1.t.join();

ob2.t.join();

ob3.t.join();

}catch (InterruptedException e) {

System.out.println("Interrupted");

}

}

}

Output:

[ Hello ]

[ Sychronized ]

[ World ]

/*Write a java program that creates a thread using Runnable interface*/

class NewThread implements Runnable{

Thread t;

NewThread() {

t=new Thread(this,"DemoThread");

System.out.println("ChildThread :"+t);

t.start();

}public void run(){

try{

for (int i=5;i>0 ;i-- ){

System.out.println("ChildThread :"+i);

Thread.sleep(500);

}

}catch (InterruptedException e){

System.out.println("ChildThread Interrupted");

}System.out.println("ChildThread Exited");

}

}

Page 57: Oops Concepts Java

57

class ThreadDemo{

public static void main(String[] args) {

new NewThread();

try{

for (int i=5;i>0 ;i-- ){

System.out.println("MainThread :"+i);

Thread.sleep(1500);

}

}catch (InterruptedException e){

System.out.println("MainThread Interrupted");

}System.out.println("MainThread Exited");

}

}

Output:

ChildThread :Thread[DemoThread,5,main]

MainThread :5

ChildThread :5

ChildThread :4

ChildThread :3

MainThread :4

ChildThread :2

ChildThread :1

ChildThread Exited

MainThread :3

MainThread :2

MainThread :1

MainThread Exited

/*Program to create threads by implementing Runnable interface?*/

class ThreadDemo2 implements Runnable{

Thread t=new Thread();

public void run() {

for(int i=1;i<=10;i++) {

System.out.println(i+" "+t.getName());

try{

Thread.sleep(2000);

}catch(InterruptedException e) {

e.printStackTrace();

}

}

}

Page 58: Oops Concepts Java

58

}

class MyThread{

public static void main(String x[]) {

ThreadDemo2 t1=new ThreadDemo2();

ThreadDemo2 t2=new ThreadDemo2();

Thread a=new Thread(t1);

Thread b=new Thread(t2);

a.start();

b.start();

}

}

Output:

1 Thread-0

1 Thread-1

2 Thread-0

2 Thread-1

3 Thread-0

3 Thread-1

4 Thread-0

4 Thread-1

5 Thread-0

5 Thread-1

6 Thread-0

6 Thread-1

7 Thread-0

7 Thread-1

8 Thread-0

8 Thread-1

9 Thread-0

9 Thread-1

10 Thread-0

10 Thread-1

/* Program to generate Border layout*/

import java.applet.*;

import java.awt.*;

import java.util.*;

/*<applet code="Form1" width=200 height=200></applet>*/

public class Form1 extends Applet{

public void init() {

setLayout(new BorderLayout());

Page 59: Oops Concepts Java

59

4add(new Button("EAST"),BorderLayout.EAST);

add(new Button("WEST"),BorderLayout.WEST);

add(new Button("NORTH"),BorderLayout.NORTH);

add(new Button("SOUTH"),BorderLayout.SOUTH);

add(new Button("CENTER"),BorderLayout.CENTER);

}

}

Output:

/* Program to generate grid layout*/

import java.applet.*;

import java.awt.*;

/*<applet code="Form2" width=200 height=200></applet>*/

public class Form2 extends Applet{

static final int n=4;

public void init() {

setLayout(new GridLayout(n , n));

setFont(new Font("SansSerif",Font.ITALIC,24));

for (int i=0; i<n;i++ ){

for (int j=0; j<n;j++ ){

int k=i*n+j;

if (k>0)

add(new Button(" " + k));

}

}

}

Page 60: Oops Concepts Java

60

}

Output:

/* Program to implement Frames*/

import java.awt.*;

import java.awt.event.*;

public class FrameDemo extends Frame{

FrameDemo() {

setLayout(new GridLayout(3, 2));

setSize(100,100);

setVisible(true);

add(new Label("Number1"));add(new TextField(5));

add(new Label("Number2"));add(new TextField(5));

add(new Button("Add"));add(new Button("Sub"));

}

public static void main(String v[]) {

FrameDemo fd=new FrameDemo();

}

}

Output:

Page 61: Oops Concepts Java

61

/* Program to Demonstrate write() */

class Write{

public static void main(String[] args) {

int b;

b='A';

System.out.write(b);

System.out.write('\n');

}

}

Output:

A

/* Program to Demonstrate print writer */

import java.io.*;

public class PWD{

public static void main(String[] args) {

PrintWriter pw=new PrintWriter(System.out,true);

int i=-7; double d=4.5e-7;

pw.println("Nagapavan"+"\t"+i+"\t"+d);

}

}

Output:

Nagapavan -7 4.5E-7