0% found this document useful (0 votes)
230 views126 pages

Oops Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 126

Java

*java is high level,object oriented programming


language.Developed by James Gosling in 1991 and released
by sunMicrosystems in 1995.
OOP (natural way to program) Paradigm:
object-oriented programming is about creating objects
that contain both data and methods. oop is a concept to
develop a program using classes and objects.
>eliminates problems in procedural oriented programming.
>object communicate with methods. Programs are divided into
objects (real world entity).
>Data is hidden and cannot be accessed by external functions.
>new data and methods can be added easily. follows bottom-
up approach.
*java is platform independent. portable,simple,High
performance,Distributed(access files by calling the
methods),Multithreaded.
*code Reusuability.Contains Automatic Garbage
Collector(strong memory-Exception handling).
*Data is Secured because of Access Specifiers
(private,public,protected).
*java checks the code during compilation and run time.
*Default access specifier is public in java and private in c++.
*Default package loaded is import Java.Lang.
*advantages are : reusability, modularity, flexibility,
maintanibility, data and information hiding.
Differences b/w c++ and java:

C++ java
1)C++ is platform-dependent. 1)java is platform
Independent.
2)used for system programming. 2)used for application
programming.
3)supports multiple inheritance. 3)doesn't support multiple
Inheritance.It can achieve
by interfaces.
4)supports operator overloading, 4) doesn't support operator
method overloading. Overloading.
5)Uses compiler only. 5)uses compiler and
interpreter.
6)Supports both call by value and 6)supports call by value
reference . only.
7)code is not portable. 7)code is portable.
8)Supports pointers, structures and 8)supports threads and
Unions. interfaces.
9)it requires explicit memory 9)it includes automatic garbage
Management collection.
10)it uses only compiler. 10)it uses both compiler and
interpreter
Class:It is a blueprint or prototype from which objects are created.it defines a
class that models the state and behaviour of real world object.

Eg :

class Democlass{

public static void main(String args[]){

System.out.println("class Demo");

Output:

S:\note java>javac Democlass.java

S:\note java>java Democlass

class Demo

Object:An object is an entity that has states and behaviors.


An object is an instance of class.
Method(Functions):
It is a block of code which only runs when it is called.we can pass
parameters into it.It is used to perform certain actions.
>it must be declared within a class.we can also create your own
methods to perform certain actions.
Ex:
public class methodexample{
static void mymethod(){
System.out.println("my own message");
}
public static void main(String args[]){
mymethod();
}
}
Output:
S:\note java>javac methodexample.java

S:\note java>java methodexample


my own message

Principles of oo language:
1.inheritance

2.abstraction

3.encapsulation

4.polymorphism

Inheritance(parent-child relationship):
It is a mechanism in which one object acquires all the
properties and behaviours of a parent object. It represents  IS-
A relationship. For method overriding and code

reusability we use inheritance in java)

o Sub Class/Child Class: Subclass is a class which inherits


the other class. It is also called a derived class, extended
class, or child class.
o Super Class/Parent Class: Superclass is the class from
where a subclass inherits the features. It is also called a
base class or a parent class.

EX:

class Employee{

float salary=40000;

class Programmer extends Employee{

int bonus=10000;

public static void main(String args[]){

Programmer p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);

System.out.println("Bonus of Programmer is:"+p.bonus);

OUTPUT:

S:\note java>javac Programmer.java

S:\note java>java Programmer


Programmer salary is:40000.0

Bonus of Programmer is:10000

Single inheritance:When a class inherits another class, it


is known as a single inheritance

Ex:

class Animal{

void eat(){

System.out.println("eating");

class Dog extends Animal{

void bark(){

System.out.println("barking");

class TestInheritance{

public static void main(String args[]){

Dog d=new Dog();

d.bark();

d.eat();

Output:
S:\note java>javac TestInheritance.java

S:\note java>java TestInheritance

barking

eating

Multiple Inheritance: where a class can inherit properties of


more than one parent class.

EX:

class Animal{

void eat(){

System.out.println("eating");

class Dog extends Animal{

void bark(){

System.out.println("barking");

class BabyDog extends Dog{

void weep(){

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

class MultipleInheritance{

public static void main(String args[]){


BabyDog d=new BabyDog();

d.weep();

d.bark();

d.eat();

Output:

S:\note java>javac MultipleInheritance.java

S:\note java>java MultipleInheritance

weeping

barking

eating

Hierarchial Inheritance:
When two or more classes inherits a single class, it is
known as hierarchical inheritance.

Ex:

class Animal{
void eat(){
System.out.println("eating");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking");
}
}
class Cat extends Animal{
void meow(){
System.out.println("meowing");
}
}
class TestInheritance{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
}
}
OUTPUT:
S:\note java>javac TestInheritance.java
S:\note java>java TestInheritance
meowing
eating

Abstraction:
 It is a process of hiding the implementation details and showing only
functionality to the user.

Ways to achieve abstraction:

1.Abstract class.

2.interface

>Abstract class:
It is a type of class in Java that is declared by the abstract keyword.
It can have both abstract methods and concrete methods.inside Abstract
class.no default cases for methods.no default cases for
variables.possible to define constructors,static blocks and nonstatic
blocks,static and nonstatic methods,static and nonstatic variables.object
creation not possible.it cannot be instantiated.
Example:

abstract class Bike{

abstract void run();

class Honda4 extends Bike{


void run(){System.out.println("running safely");}

public static void main(String args[]){

Bike obj = new Honda4();

obj.run();

Output

running safely

>Interface:
It can have any no. of abstract methods.it cannot have any concrete
methods. inside interface by default every method is ‘public’ or
‘abstract’.By default every variable are ‘public static final’.not possible to
declare constructors,static and nonstatic blocks,static methods.

>Inside it public methods are allowed but not private and protected.inside
interface static,final,synchronized(illegal) methods are not possible.object
creation is not possible. Interfaces can extend other interfaces but not
classes. Interfaces cannot be instantiated .

interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:

S:\note java>javac A6.java


S:\note java>java A6
Hello
Encapsulation:
It is a process of wrapping code and data together into a
single unit. It is a way to achieve data hiding in Java because
other class will not be able to access the data through the private
data members.
To achieve encapsulation:
1. Declare the variables of a class as private.
2.Provide public setter and getter methods to modify and view the
variables values.
EX:
public class encapsulation{
private String name;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public void setAge(int newAge){
age=newAge;
}
public void setName(String newName){
name=newName;
}
}
public class testencapsulation{
public static void main(String args[]){
encapsulation obj=new encapsulation();
obj.setName("sowmya");
obj.setAge(20);
System.out.print("Name: "+obj.getName()+" Age:
"+obj.getAge();
}
}
Output:
S:\note java>javac testencapsulation.java
S:\note java>java testencapsulation
Name: sowmya Age: 20

Polymorphism: perform a single action in different ways


Types of polymorphism:
1.compile-time polymorphism :
>Method overloading: If a class has multiple methods having
same name but different in parameters, it is known as Method
Overloading.

two ways to overload the method in java:

1. By changing number of arguments


2. By changing the data type

class overloading{

void m1() {
System.out.println("method display");
}
void m1(int a) {
System.out.println("a= "+a);
}
}
class TestOverloading{
public static void main(String[] args){
overloading obj=new overloading();
obj.m1();
obj.m1(30);
}
}
OUTPUT:
S:\note java>javac TestOverloading.java
S:\note java>java TestOverloading
method diaplay
a= 30
2.runtime polymorphism.
>Method overriding:If subclass (child class) has the same method as
declared in the parent class, it is known as method overriding in Java.
class Vehicle{

void run(){

System.out.println("Vehicle is running");

class Bike2 extends Vehicle{

void run(){

System.out.println("Bike is running safely");

public static void main(String args[]){

Bike2 obj = new Bike2();

obj.run();

OUTPUT:

S:\note java>javac Bike2.java

S:\note java>java Bike2

Bike is running safely


Constructors:
constructor is a block of codes similar to the method. It is
called when an instance of the class is created. At the time of
calling constructor, memory for the object is allocated in the
memory..used to initialize object.

Rules for creating Java constructor

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and
synchronized

Types of Constructors:
1.Default constructors.(no-arg)
2.parameterized constructors.(passing parameters)
Example:
class student{
String name;
int rno;
student(){
name="ABC";
rno=123;
}
student(String str,int num){
name=str;
rno=num;
}
public static void main(String args[]){
student obj=new student();
student obj1=new student("DEF",456);
System.out.println(obj.name);
System.out.println(obj.rno);
System.out.println(obj1.name);
System.out.println(obj1.rno);
}
}
OUTPUT:
S:\note java>javac student.java
S:\note java>java student
ABC
123
DEF
456 .
Destructors:
It is a special method that automatically gets called when
an object is no longer used. When an object completes its life-
cycle the garbage collector deletes that object and deallocates
or releases the memory occupied by the object.
>garbage collector invokes finalize() method(available in object class)
before destruction of any object. finalize method invoked , to close
the resources connected to object.
Example:
public class DestructorExample
{
protected void finalize(){
System.out.println("object destroyed by garbage collector");
}
public static void main(String[] args) {
DestructorExample de = new DestructorExample ();
de.finalize();
de = null;
System.gc();
System.out.println("removed the resources connection with
object");
}
}
Output:
S:\note java>javac DestructorExample.java
S:\note java>java DestructorExample
object destroyed by garbage collector
removed the resources connection with object
object destroyed by garbage collector
operator overloading:
class overload
{
void add(){
int a=10,b=20;
int c=a+b;
System.out.println("c:"+c);
}
void add(int x,int y){
int z=x+y;
System.out.println("z:"+z);
}
}
class Ooverload{
public static void main(String args[]){
overload obj=new overload();
obj.add();
obj.add(40,60);
}

}
OUTPUT:
S:\note java>javac Ooverload.java
S:\note java>java Ooverload
c:30
z:100

Static variables:
It can be access directly(single class).access with help of
classname(multiple class)

Static block: It can be executed by default without any explicit class.


Static Methods:
Static Methods can access class variables(static variables) without
using object(instance) of the class, however non-static methods and non-static
variables can only be accessed using objects.

In single class:
class staticexample
{
static int a=10;
static void myMethod()
{
System.out.println("static method displayed");
}
static{
System.out.println("static block");
}
public static void main(String[] args)
{
System.out.println(a);
myMethod();
}
}
OUTPUT:
S:\note java>javac staticexample.java
S:\note java>java staticexample
static block
10
static method displayed
In Multiple class:
class staticexample
{
static int a=10;
static void myMethod()
{
System.out.println("static method displayed");
}
static{
System.out.println("static block");
}
}
class example3{
public static void main(String[] args)
{
System.out.println(staticexample.a);
staticexample.myMethod();
}
}
Output:
S:\note java>javac staticexample.java
S:\note java>java staticexample
static block
10
static method displayed

Non-Static methods :
>A non-static method does not have the keyword static before
the name of the method.

>A non-static method belongs to an object of the class and you


have to create an instance of the class to access it.

>Non-static methods can access any static method and any


static variable without creating an instance of the class.

EX:

class nonstaticexample{

public void method()

System.out.println("non static method execution");

public static void main(String args[]){

nonstaticexample obj= new nonstaticexample();

obj.method();

}
Output:

S:\note java>javac nonstaticexample.java

S:\note java>java nonstaticexample

non static method execution

Access specifiers:
1.Private: The access level of a private modifier is only within
the class. It cannot be accessed from outside the class.

Ex:

class A{

private int data=40;

private void msg(){

System.out.println("Hello java");

public static void main(String args[]){

A obj=new A();

System.out.println(obj.data);

obj.msg();

Output:

S:\note java>javac A.java

A.java:10: error: data has private access in B


System.out.println(obj.data);

A.java:11: error: msg() has private access in B

obj.msg();

2 errors

Explanation: we have created two classes A and Simple.


A class contains private data member and private method.
We are accessing these private members from outside the
class, so there is a compile-time error.

2.Default: The access level of a default modifier is only


within the package. It cannot be accessed from outside the
package. If you do not specify any access level, it will be the
default.

File name :A.java

package pack;

class A{

void msg(){

System.out.println("Hello");

Filename:B.java

package mypack;

class B{

public static void main(String args[]){


A obj = new A();

obj.msg();

Explanation: we have created two packages pack and


mypack. We are accessing the A class from outside its
package, since A class is not public, so it cannot be
accessed from outside the package.

3.Protected: The access level of a protected modifier is within


the package and outside the package through child class. If
you do not make the child class, it cannot be accessed from
outside the package.

package pack;

public class A{

protected void msg(){

System.out.println("Hello");

package mypack;

class B extends A{

public static void main(String args[]){

B obj = new B();

obj.msg();

}
}

Explanation: we have created the two packages pack


and mypack. The A class of pack package is public, so can
be accessed from outside the package. But msg method of
this package is declared as protected, so it can be
accessed from outside the class only through inheritance.

4.Public: The access level of a public modifier is


everywhere. It can be accessed from within the class, outside
the class, within the package and outside the package.

Filename :A.java

package pack;

public class A{

protected void msg(){

System.out.println("Hello");

Filename:B.java

package mypack;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

OUTPUT:
Hello
Static Binding (also known as Early Binding):
When type of the object is determined at compiled time(by the
compiler), it is known as static binding.

If there is any private, final or static method in a class, there is


static binding.

class Dog{

private void eat(){

System.out.println("dog is eating...");

public static void main(String args[]){

Dog d1=new Dog();

d1.eat();

OUTPUT:

S:\note java>javac Dog.java

S:\note java>java Dog

dog is eating...

Dynamic Binding (also known as Late Binding):


 When type of object is determined at the run time so this is known as
dynamic binding.

class Animal{
void eat(){

System.out.println("animal is eating");

class Dog extends Animal{

void eat(){

System.out.println("dog is eating");

public static void main(String args[]){

Animal a=new Dog();

a.eat();

OUTPUT:

S:\note java>javac Dog.java

S:\note java>java Dog

dog is eating
UNIT-II
Features of java:
1. Simple: easy to learn, syntax is simple(c++), clean and easy to understand
removed unessential features.no need to remove unessential objects(automatic
garbage collector).

2. Object-Oriented: Any programming provides good environment to represent


data inside classes. That is in form of objects.

3. Portable: Can carry Java bytecode to any platform. It doesn't require any
implementation.
4. platform independent: Java is a write once, run anywhere language. Java code
can be run on multiple platforms.

5. Secured-no explicit pointer, problems like virus and threats are eliminated
6. Robust-java has inbuilt exception handling and memory, Management features.
7. Architecture neutral-there is no implementation of dependent features, size of
primitive data types are fixed.
8. Interpreted-java programs to generate byte code. byte code can be downloaded
and interpreted by interpreter in java.
9. High Performance-problem with interpreter inside JVM is that it is slow. Java
developers introduce JIT compiler which enhances speed of Execution.
10. Multithreaded: java uses several threads to execute different blocks of code.so
creating multiple threads is called Multithreading
11. Distributed-java makes us able to access files by calling methods from any
machine on internet.
12. Dynamic- In java all operation(memory allocation and deallocation) are
performed at run time.

Structure of java program:

Documentation section:

Statements in it are ignored during execution of program.To write statements we use

o single line comment://statement


o Multiline statement-/* statement*/
o Documentation comment-/** statement */

Package declaration:

here we declare package name in which class is placed.


>only one package statement.it must be defined before any class and interface
declaration

Package packagename

Import statements:

It contains predefined classes and interfaces,it represents class stored in other


package.it is written b/w class declaration ad package statement.we can import a
specific class(import java.util.Scanner;) or import all classes(import java.util.*;) of
aparticular package.

Interface section(optional):

It contains constants and method declarations.it cannot be instantiated we can use


interface in classes by using implements keyword.it can be used with other interfaces by
using extends keyword.

Ex: interface classname{

Void m1();

Void m2();

Class Definition:

We define class.java program can contain more than one class.it is blue print of java
program.it contain information about userdefined methods,variables,and constants.every
java program has atleast one class that contains main() method.

Class classname{

Class variables and constants(store value of


parameters):

We define variables,constants that are used later in program.

Class classname{

Datatype variablename;
}

Main Method class:

Public static void main(String args[]){

Methods and behaviour:

we define the functionality of the program by using the methods.

1. public class Demo //class definition  
2. {  
3. public static void main(String args[])  
4. {  
5. void display()  
6. {  
7. System.out.println("Welcome to javatpoint");  
8. }  
9. //statements  
10. }  
11. }  
JAVA PROGRAM:

1. /*Program name: Number*/  
2. //Author's name: sowmya
3. /*show enter number.*/  
4. //imports the Scanner class of the java.util package  
5. import java.util.Scanner;
6. //class definition
7. public class Number
8. {
9. //main method
10. public static void main(String args[])
11. {
12. //variables to be used in program
13. int x; //It is the number variable
14. Scanner sc= new Scanner(System.in);
15. System.out.print("Enter number: ");
16. //reading a number from the user
17. x=sc.nextInt();
18. System.out.println("entered number is: " +x);
19. }
20. }
OUTPUT:

S:\note java>javac Number.java

S:\note java>java Number

Enter number:3

entered number is: 3

Built in data types:


1)primitive – It is pre-defined by the programming language. The size and type of
variable values are specified, and it has no additional methods.it always has value.
start with lower case letter. size of it depends on data type .

Ex:Byte(1),short(2byte),int(4),long(8),float(4),double(8),Boolean(1),char(2).

2)nonprimitive- These data types are not actually defined by the programming
language but are created by the programmer. They are also called “reference
variables” or “object references” since they reference a memory location which
stores the data. It can be used to call methods to perform certain operations.it can be
null. start with upper case letter.All nonprimitives datatypes have same size.

Ex: Strings, arrays and classes ,interfaces


Sample Code:
class classname{
public static void main(String args[]) {
datatype variable = value;
System.out.println(variable);
}
}

Scope and lifetime of variables:


Scope of variable->it refers to areas or sections of
program in which variable can be accessed.
Lifetime of variable->it indicates how long variable
stays alive in memory.
 Local variables − Variables defined inside methods, constructors or blocks
are called local variables. The variable will be declared and initialized within
the method and the variable will be destroyed when the method has
completed.
 Instance variables − Instance variables are variables within a class but
outside any method. These variables are initialized when the class is
instantiated. Instance variables can be accessed from inside any method,
constructor or blocks of that particular class.
 Class variables − Class variables are variables declared within a class,
outside any method, with the static keyword.
Ex:
public class scope_and_lifetime {
int num1, num2; //Instance Variables
static int result; //Class Variable
int add(int a, int b){ //Local Variables
num1 = a;
num2 = b;
return a+b;
}
public static void main(String args[]){
scope_and_lifetime ob = new scope_and_lifetime();
result = ob.add(10, 20);
System.out.println("Sum = " + result);
}
}

For Loop:
Syntax of for loop:
for(initialization; condition ; increment/decrement)
{
statement(s);
}
class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
}
}
}

If-else
Syntax:
if(condition) {
Statement(s);
}
else {
Statement(s);
}

public class IfElseExample {

public static void main(String args[]){


int num=120;
if( num < 50 ){
System.out.println("num is less than 50");
}
else {
System.out.println("num is greater than or equal 50");
}
}
}
Output:

num is greater than or equal 50

While loop:
Syntax of while loop
while(condition)
{
statement(s);
}

class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.println(i);
i--;
}
}
}
Output:
10
9
8
7
6
5
4
3
2

do-while loop:
do
{
statement(s);
} while(condition);

class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
Output:

10
9
8
7
6
5
4
3
2
Operators: It is a symbol which is used to perform operations.

1. Arithmetic operators: +, -, *, /, %, ++, --


2. Relational operators; == , !=, >, <, >=, <=
3. Bitwise operators: &, |, ^, ~, <<,>>,>>>
4. Logical operators: &&(t+t=t), || (f+f=f), !
5. Assignment operators: =, +=, -+, *=, /=, %=, <<=,>>=, &=,^=,!=

class operatorexam ple {

public static void main(String args[]){

int a=10,b=11,c=20;

System.out.println(a*b);

System.out.println(a==b);

a+=3;

System.out.println(a);

System.out.println(a++);

System.out.println(a<b&a<c);

System.out.println(a<b&&a<c);

System.out.println(a>b||a<c);

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

System.out.println(10*10/5+3-1*4/2);

System.out.println(10<<2);//10*2^2=10*4=40

System.out.println(10>>2);//10/2^2=10/4=2

Conditional operator(ternary):It consists of three operands and


is used to evaluate Boolean expressions. 

Syntax: variable x = (expression) ? value if true: value if false

public class Test {


public static void main(String args[]) {
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}

Output: Value of b is : 30
Value of b is : 20

Parameter Passing:
>Function parameters:
Syntax: functionname(datatype variablename);
>Actual parameters:
Syntax: functionname(variable name(s));

CallByValue:calling a method with a parameter as value.


Through this, the argument value is passed to the parameter.
class CallByValue{
public static void Example(int x, int y) {
x++;
y++;
}
}
public class Main {
public static void main(String[] args) {
int a = 10,b=20;
CallByValue object = new CallByValue();
System.out.println("Value of a: " + a + " & b: " + b);
object.Example(a, b);
System.out.println("Value of a: "+ a + " & b: " + b);
}
}
Output:
S:\note java>javac Main.java
S:\note java>java Main
Value of a: 10 & b: 20
Value of a: 10 & b: 20

callByReference:calling a method with a parameter as a


reference. Through this, the argument reference is passed to the
parameter.
class CallByReference {
int a, b;
CallByReference(int x, int y) {
a = x;
b = y;
}
void ChangeValue(CallByReference obj)
{
obj.a += 10;
obj.b += 20;
}
}
public class Main {
public static void main(String[] args) {
CallByReference object = new CallByReference(10, 20);
System.out.println("Value of a: "+ object.a + " & b: "+
object.b);
object.ChangeValue(object);
System.out.println("Value of a: "+ object.a + " & b: "+
object.b);
}
}
Output:
S:\note java>javac Main.java
S:\note java>java Main
Value of a: 10 & b: 20
Value of a: 20 & b: 40

Final : used to restrict the user.


Final keyword with Variables: If you make any variable as final, you
cannot change the value of final variable(It will be constant).

class Bike9{
final int speedlimit=90;
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
OUTPUT:
S:\note java>javac Bike9.java
Bike9.java:4: error: cannot assign a value to final variable speedlimit
speedlimit=400;
^
1 error
FinalKeyword with Methods: If you make any method as final,
you cannot override it.
>Final method can be inherited.
class Bike9{
final void run(){
System.out.println("running");
}
}
class Honda extends Bike9{
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
OUTPUT:
S:\note java>javac Bike9.java
Bike9.java:6: error: run() in Honda cannot override run() in Bike9
void run(){System.out.println("running safely with 100kmph");}
^
overridden method is final
1 error

Final Keyword with classes: If you make any class as final, you
cannot extend it.
final class Bike9{
}
class Honda1 extends Bike9{
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
OUTPUT:
S:\note java>javac Bike9.java
Bike9.java:3: error: cannot inherit from final Bike9
class Honda1 extends Bike9{
^
1 error
NOTE: A final variable that is not initialized at the time of
declaration is known as blank final variable. It can be initialized
only in constructor.
A static final variable that is not initialized at the time of
declaration is known as static blank final variable. It can be
initialized only in static block.
If you declare any parameter as final, you cannot change the
value of it

Single dimensional array:


Declaring an array:
Datatype Arrayname[];
Allocating Memory:
Arrayname =new datatype[size]
NOTE: datatype Arrayname[] =new datatype[size];
initialization:
datatype Arrayname[] =new datatype[size];
Arrayname[indexno]=value;
Declaration and initializing:
Datatype Arrayname[] ={list of values};
Source Code:
import java.util.*;
class singleDarray{
public static void main(String args[]){
Scanner S =new Scanner(System.in);
System.out.print("Enter array size:");
int length=S.nextInt();
int[] a=new int[length];
System.out.println("Enter "+length+" elements");
for(int i=0;i<length;i++){
a[i]=S.nextInt();}
arraydisplay obj=new arraydisplay();
obj.display(a);
}
}
class arraydisplay {
void display(int a[]){
System.out.println("entered array elements are:");
for(int i=0;i<a.length;i++){
System.out.println("a["+i+"]:"+a[i]);}
}
}
OUTPUT:
S:\note java>javac singleDarray.java
S:\note java>java singleDarray
Enter array size:3
Enter 3 elements
8
9
0
entered array elements are:
a[0]:8
a[1]:9
a[2]:0

Quadratic equation using constructors and method:


class QEQN {
double a,b,c;
double root1, root2;
QEQN(double a,double b,double c){
this.a=a;
this.b=b;
this.c=c;
}
void display(){
double determinant = b * b - 4 * a * c;
double sqrt=Math.sqrt(determinant);
if (determinant > 0) {
root1 = (-b + sqrt) / (2 * a);
root2 = (-b - sqrt) / (2 * a);
System.out.format("two real roots:%.2f ,%.2f", root1, root2);
}
else if(determinant == 0) {
System.out.format("root1 = root2 = %.2f",-b / (2 * a));
}
else{
System.out.format("no real roots");}
}
public static void main(String[] args) {
QEQN obj= new QEQN(1,-2,1);
obj.display();
}
}
OUTPUT:
S:\note java>javac QEQN.java
S:\note java>java QEQN
root1 = root2 = 1.00

Stack clas:
import java.util.*;
public class Stackoperations {
public static void main(String a[]){
Stack stack = new Stack();
System.out.println("Initial stack : " + stack);
System.out.println("Is stack Empty? : " + stack.isEmpty());
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
System.out.println("Stack after push operation: " + stack);
System.out.println("Element popped out:" + stack.pop());
System.out.println("Stack after Pop Operation : " + stack);
System.out.println("Element 10 found at position: " + stack.search(10));
System.out.println("Is Stack empty? : " + stack.isEmpty());
}
}
Output:
S:\note java>javac Stackoperations.java
S:\note java>java Stackoperations
Initial stack : []
Is stack Empty? : true
Stack after push operation: [10, 20, 30, 40]
Element popped out:40
Stack after Pop Operation : [10, 20, 30]
Element 10 found at position: 3
Is Stack empty? : false

UNIT-III
Specialization form of inheritance satisfies substitutability or
not :
substitutability: if B is a subclass of A, anywhere we expect an instance of A we
can use an instance of B.
specialization -- the subclass is a special case of the parent class.it holds
substitutability.
class parentclass{
void parent(){
System.out.println("parentclass");
}
}
class subclass extends parentclass {
void sub(){
System.out.println("subclass");
}
}
class Testspecialization {
public static void main(String args[]){
subclass obj=new subclass();
obj.parent();
obj.sub();

}
}
OUTPUT:

S:\note java>javac Testspecialization.java


S:\note java>java Testspecialization
parentclass
subclass
Specification form of inheritance
parent class just specifies which methods should be available to the child class but
doesn't implement them. The java provides concepts like abstract and interfaces to
support this form of inheritance. It holds the principle of substitutability.
Abstract :
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){
System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output:

S:\note java>javac Honda4.java

S:\note java>java Honda4


running safely

interface:
interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:

S:\note java>javac A6.java


S:\note java>java A6
Hello

Creating a class that is inherited from two different


interfaces
interface FirstInterface {
public void myMethod();
}
interface SecondInterface {
public void myOtherMethod();
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
class MyMainClass {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
Output:
S:\note java>javac MyMainClass.java
S:\note java>java MyMainClass
Some text..
Some other text...

Concrete Class

A concrete class in Java is a type of subclass, which implements all the abstract methods
of its super abstract class which it extends to. It also has implementations of all methods
of interfaces it implements.

Example:

public class ConcreteClassExample {

public int add(int a, int b){

int c = a + b;

return c;

public int subtract(int a, int b){

int c = a - b;

return c;

}
public void display(){

System.out.println("Hello");

public static void main(String args[]){

ConcreteClassExample obj = new ConcreteClassExample();

System.out.println(obj.add(25, 347));

System.out.println(obj.subtract(500, 456));

obj.display();

Output:

372

44

Hello

Super: It is a reference variable that is used to refer parent class


objects. 
Super Keyword with constructors:
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
class Student extends Person
{
Student()
{
super();

System.out.println("Student class Constructor");


}
}
class Testconstructor
{
public static void main(String[] args)
{
Student s = new Student();
}
}
OUTPUT:
S:\note java>javac Testconstructor.java
S:\note java>java Testconstructor
Person class Constructor
Student class Constructor

Super keyword with methods:


class Person
{
void message()
{
System.out.println("This is person class");
}
}
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
void display()
{
message();
super.message();
}
}
class Testconstructor
{
public static void main(String args[])
{
Student s = new Student();
s.display();
}
}
OUTPUT:
S:\note java>javac Testconstructor.java
S:\note java>java Testconstructor
This is student class
This is person class

Super keyword with variables:


class Vehicle
{
int maxSpeed = 120;
}
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
class Testconstructor
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

OUTPUT:
S:\note java>javac Testconstructor.java
S:\note java>java Testconstructor
Maximum Speed: 120
Inheritance(IS-A):it is of two types
 class inheritance
 interface inheritance
1.inheritance is unidirectional. If you we have extends keyword or implements
keyword in a class declaration, then this class is said to have IS-A
relationship.it is static binding(compile time).tightly coupled.code reusuability
.reduce redundancy.

class Animal{

   String name="Orio";

class Dog extends Animal{

   String type="Dog";

   public static void main(String args[]){

      Dog p=new Dog();

      System.out.println("Name:"+p.name);

      System.out.println("Type:"+p.type);

   }

Composition(Has-A)
use of instance variables that are references to other objects.it is dynamic
binding(run time).loosely coupled.

Exception: Exceptions:
Exceptions are the errors that occurs during execution of program that
interrupts normal flow of program..
Runtime/unchecked exception:It is not checked at compile-
time, they occurs at runtime.
class unchecked{
public static void main(String args[])
{
int a=10,b=0;
int res=a/b;
System.out.println(res);
}
}

Output:
S:\note java>javac unchecked.java
S:\note java>java unchecked
Exception in thread "main" java.lang.ArithmeticException: / by zero
at unchecked.main(unchecked.java:
Checked/static:it is checked at compile time.
import java.io.*;
public class checked {
public static void main(String args[]) {
File file = new File("S://notejava");

FileReader Input = new FileReader(file);


}
}
Output:
S:\note java>javac checked.java
checked.java:5: error: unreported exception FileNotFoundException;
must be caught or declared to be thrown
FileReader Input = new FileReader(file);
^
1 error

Difference between checked and unchecked exceptions


Checked exception unchecked exception
1)It is also known as 1)It is also known as run
Compile time exception. time exception.
2)Checked exceptions are 2)unchecked exceptions
Propagated using throws are propogated
keyword. Automatically.
3)Not subclass of runtime 3)subclass of runtime
Exception. Exception.
4)IO Exception,FileNotFound 4)NullPointerException,
Exception etc.. ArithmeticException etc..
4)we can create custom 5)By extending Runtime
Exception by extending Exception we can create
Java.lang.Exception class. Custom Exception.
5) classes which directly inherit 6)  classes which inherit RuntimeException

Throwable class except Runtime

Exception and Error

Exception handling: advantage of exception handling is to maintain the


normal flow of the application.
Code1:
class exceptionhandling{
public static void main(String arg[]) {
System.out.println("Computer");
System.out.println(4/0);
System.out.println("Programming");
}
}
Output :second statement will raise an exception and
terminates the program.
S:\note java>javac exceptionhandling.java
S:\note java>java exceptionhandling
Computer
Exception in thread "main" java.lang.ArithmeticException: / by zero
at exceptionhandling.main(exceptionhandling.java:4)

Exception keywords : used in handling exceptions in


Java.
1) try-used to specify a block where we should place exception code .It
must be followed by either catch or finally .If an exception occurs in
the try block, the rest of the block code will not execute.
2) Catch- used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be
followed by finally block later.
3) Finally-used to execute the important code of the program. It is
executed whether an exception is handled or not.
4) Throw-used to throw an exception.
5) Throws-used to declare exceptions. It doesn't throw an exception.
It specifies that there may occur an exception in the method. It is
always used with method signature.

Advantages of Exception Handling:


1) Easy Identification of Program Code and Error-Handling Code: The use of try/catch
blocks segregates error-handling code and program code making it easier to identify
the logical flow of a program.
2)Meaningful Error reporting
3)propogation of Errors
4)identifying error types
5)possible to continue execution of program after an exception has occurred if
it is handled properly.
6)separate error-handlig code from “Regular code”
7)Grouping and Differentiating Error types.
Code2 with try and catch block:
class check{
public static void main(String arg[]) {
System.out.println("Computer");
try
{
System.out.println(4/0);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Programming");
}
}

Output:
S:\note java>javac check.java
S:\note java>java check
Computer
java.lang.ArithmeticException: / by zero
Programming

Explanation: The statements that may raise an exception are placed in the ‘try’
block. If an exception is raised the control goes to the ‘catch’ block.

If no exception is raised, then the catch block is skipped .


Multiple catch block:

*At a time only one exception occurs and at a time only one
catch block is executed.

public class Multiplecatchblock{


public static void main(String[] args){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Output:
S:\note java>javac Multiplecatchblock.java
S:\note java>java Multiplecatchblock
java.lang.ArithmeticException: / by zero
Out of try-catch block…
Nested try :
*The try block within a try block .
class Nestedtry{
public static void main(String args[]){
try{
try{
int b =39/0;
}
catch(ArithmeticException e){
System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("out of try catch block");
}
}

Output:
S:\note java>javac Nestedtry.java
S:\note java>java Nestedtry
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
out of try catch block.

Finally try:
*It is always executed whether exception is handled or not.

*finally block follows try or catch block.only one finally block

public class Finaltry{


public static void main(String args[]){
try{
int c=25/0;
System.out.println(c);
}
catch(ArithmeticException e){
System.out.println(e);
}
finally{
System.out.println("final end");
}
System.out.println("done");
}
}
Output:
S:\note java>javac Finaltry.java
S:\note java>java Finaltry
java.lang.ArithmeticException: / by zero
final end
Done

Index OutofBound Exception:


Source code:
import java.util.*;
class IOB{
public static void main(String args[]){
Scanner S=new Scanner(System.in);
System.out.println("Enter count:");
int length=S.nextInt();
int a[]=new int[length];
System.out.println("Enter values:");
for(int i=0;i<a.length;i++){
a[i]=S.nextInt();}
System.out.println("Elements are:");
System.out.println(Arrays.toString(a));
System.out.println("Enter index:");
try{
int i=S.nextInt();
System.out.println("Element is:"+a[i]);}
catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);}
finally{
System.out.println("end");}
}
}

Output1:
S:\note java>javac IOB.java
S:\note java>java IOB
Enter count:
5
Enter values:
90
80
70
60
50
Elements are:
[90, 80, 70, 60, 50]
Enter index:
3
Element is:60
End

Output2:
Enter count:
3
Enter values:
50
90
80
Elements are:
[50, 90, 80]
Enter index:
4
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3
end

NullPointer Exception:
public class NullExceptionExample{
public static void main(String args[]){
String s="sowmya",w=null;
try{
System.out.println(s.length());
System.out.println(w.length());
}
catch(NullPointerException e){
System.out.println(e);
}
System.out.println("length of string");
}
}
OUTPUT:
S:\note java>javac NullExceptionExample.java
S:\note java>java NullExceptionExample
6
java.lang.NullPointerException
length of string

NumberFormatException:
Source code:
import java.util.*;
class NFE{
public static void main(String args[]){
try{
int num=Integer.parseInt("XYZ");
System.out.println(num);}
catch(NumberFormatException e){
System.out.println(e);}
finally{
System.out.println("end");}
}
}

Output1:
If input is XYZ.
S:\note java>javac NFE.java
S:\note java>java NFE
java.lang.NumberFormatException: For input string: "XYZ"
end

output2:
if input is 123.
S:\note java>javac NFE.java
S:\note java>java NFE
123
End
ClassNotFoundException:
class FileA{}
class FileB{}
class MyClass{
public static void main(String[] args)
{
try{
Class cls =Class.forName("FileC");
ClassLoader obj=cls.getClassLoader();
System.out.println("found: " + cls.getName());
}
catch(ClassNotFoundException e)
{
System.out.println("class not found in class path");
}
}
}
OUTPUT:
S:\note java>javac MyClass.java
S:\note java>java MyClass
class not found in class path
Method 2:
class FileA{}
class FileB{}
class MyClass{
public static void main(String[] args) throws ClassNotFoundException{
Class cls =Class.forName("FileB");
ClassLoader obj=cls.getClassLoader();
System.out.println("found: " + cls.getName());
}
}
Output :

Q. Exception by command line arguments:


Source code:
import java.util.*;
class CLA{
public static void main(String args[]){
int count= args.length;
try{
if(count==1){
System.out.println("Divide by zero exception");}
if(count==2){
System.out.println("IndexOutOfBounds exception");}
if(count==3){
System.out.println("user defined exception");}
}
catch(Exception e){
System.out.println(e);}
finally{
System.out.println("end");}
}
}

Output:
S:\note java>javac CLA.java
1)S:\note java>java CLA ab
Divide by zero exception
end
2)S:\note java>java CLA ab df
IndexOutOfBounds exception
end
3)S:\note java>java CLA ab df gh
user defined exception
end

Q. user defined exceptions by checking two


strings are equal or not:
Source code:
import java.util.*;
class strexception{
public static void main(String args[]){
Scanner S=new Scanner(System.in);
System.out.println("enter two strings:");
try{
String a=S.next();
String b=S.next();
if(a.equals(b)){
System.out.println("same strings ,no exception");}
else{
System.out.println("different strings,exception");}
}
catch(Exception e){
System.out.println(e);}
finally{
System.out.println("end");}
}
}

Output:
S:\note java>javac strexception.java
1)S:\note java>java strexception
enter two strings:
vinu
vinu
same strings ,no exception
end

2)S:\note java>java strexception


enter two strings:
vinu
sowmya
different strings,exception
end
Throws:
class invalidException extends Exception{
public invalidException(String s){
super(s);}
}
class examplethrows{
void check(int age) throws invalidException{
if(age<18){
throw new invalidException("not eligible to vote");}
else{
System.out.println("eligible to vote");
}
}
public static void main(String args[]){
examplethrows obj=new examplethrows();
try{

obj.check(10);
}
catch(invalidException ex){
System.out.println("caught Exception");
System.out.println(ex.getMessage());
}
}
}
Termination or Resumptive Model:
When an exception is thrown, control is transferred to the catch block that
handles the error. programmer has 2 choices. he can print error message and
exit from program. this technique is called Termination Model. The user can
also continue execution by calling some other function after printing the error
message. this technique is called as Resumptive model.
If exception handling is not provided, then in java application the
program terminates automatically after printing the default exception
message.
Source code:
class TERORRESEXAMPLE{
public static void main(String arg[]) {
try
{
System.out.println(4/0);
}
catch(ArithmeticException e)
{
System.out.println(e);
System.exit(0);
}
System.out.println("resumptive model");
}
}
OUTPUT 1: Termination
S:\note java>javac TERORRESEXAMPLE.java
S:\note java>java TERORRESEXAMPLE
java.lang.ArithmeticException: / by zero
OUTPUT2: Resumptive model
S:\note java>javac TERORRESEXAMPLE.java
S:\note java>java TERORRESEXAMPLE
java.lang.ArithmeticException: / by zero
resumptive model

Synchronisation :
It is the capability to control the access of multiple threads to any shared
resource. without synchronisation the output is inconsistent.
Synchronized block:
It is synchronized on same object can only have one thread during executing
inside them at the same time .All other threads attempting to enter the
synchronized block are blocked until the thread inside the synchronized block
exits the block.
Ex: void synchronizedEx(){
Synchronized(this){
//All code goes here..
}
}

synchronised class(static) methods :


Memory is allocated only once at the time of class loading. While execution of
static method Synchronize on class object. If one thread is executing a static ,all
other threads are trying to execute any static synchronized methods will be
blocked.

Source code:
class sync {
synchronized static void table(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try {
Thread.sleep(400);}
catch(Exception e){
System.out.println(e)}
}
}
}
class Thread1 extends Thread{
public void run(){
sync.table(1);
}
}
class Thread2 extends Thread{
public void run(){
sync.table(10);
}
}
public class testsync{
public static void main(String args[]){
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
t1.start();
t2.start();
}
}

Output:
S:\note java>javac testsync.java
S:\note java>java testsync
1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100

Synchronized instance methods :


Memory is allocated multiple time whenever method is calling. Synchronize on
instance of class. If one thread is executing a synchronized method , all other
threads are trying to execute any synchronized methods will be blocked.

Source code:
class Thread1 extends Thread{
synchronized public void run(){
try{
sleep(1000);
System.out.println("good mrng");}
catch(Exception e){}
}
}
class Thread2 extends Thread{
synchronized public void run(){
try{
sleep(2000);
System.out.println("hello");}
catch(Exception e){}
}
}
public class instsync{
public static void main(String args[]){
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
t1.start();
t2.start();}
}

output:
S:\note java>javac instsync.java
S:\note java>java instsync
good mrng
hello

Synchronized method by using anonymous class:


class sync {
synchronized void table(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try {
Thread.sleep(400);}
catch(Exception e){}
}
}
}
public class testsync{
public static void main(String args[]){
final sync obj=new sync();
Thread t1=new Thread(){
public void run(){
obj.table(1);
}
};
Thread t2=new Thread(){
public void run(){
obj.table(10);
}
};
t1.start();
t2.start();
}
}
Output:
S:\note java>javac testsync.java

S:\note java>java testsync


1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100

Alternatives to synchronization in java:


The java.util.concurrent package has a whole range of classes
that can be used to make multi-threaded code thread-safe without
explicitly using the "synchronized" keyword.
Synchronized program with wait() and notify():
This must be synchronized within a synchronized block only.
*Wait()-it tells the calling thread to give up the lock and go to sleep until some
other thread enters the same monitor and calls notify().
*notify()-it takes up one single thread that calls wait() on the same object.
*notifyAll():if more than one thread is waiting for an object,we can notify all
other threads using notifyAll.
Source code:
public class ThreadA {
public static void main(String[] args){
ThreadB obj= new ThreadB();
obj.start();
synchronized(obj){
try{
System.out.println("HII....");
obj.wait();
}
catch(Exception e){}
}
}
}
class ThreadB extends Thread{
int n=3;
public void run(){
synchronized(this){
System.out.println("table:");
for(int i=0; i<5 ; i++){
System.out.println(n + " * " + i + " = "+n*i);
}
notify();
}
}
}
Output:
S:\note java>javac ThreadA.java

S:\note java>java ThreadA


HII....
table:
3*0=0
3*1=3
3*2=6
3*3=9
3 * 4 = 12

Threads:
threads allows a program to operate more efficiently by doing multiple
things at the same time.

Threads can be used to perform complicated tasks in the background without


interrupting the main program

create a thread:
1. Extending the Thread class
2. Implementing the Runnable Interface
Differences:
Runnable interface extending thread class
Runnable is an interface in Java to create a The thread is a class in Java to create a thread
thread that allows many threads to share the where each thread has a unique object
same thread object. associated with it.

In Runnable, multiple threads share the same In Thread class, each thread creates a unique
object, so require less memory. object, therefore requires more memory.

Multiple inheritances are not supported in


After implementing Runnable interface, it can
Java. After extending Thread class, it cannot
extend a class.
extend any other class.

Runnable interface makes code more In Thread class, maintaining is time-


maintainable. consuming.

multithreading by extending thread


class:We create an object of our new class and call start() method to
start the execution of a thread. Start() invokes the run() method on the
Thread object.

Source code:
import java.util.*;
class Oddeven{
public static void main(String args[]){
Thread1 obj1=new Thread1();
obj1.start();
Thread2 obj2=new Thread2();
obj2.start();
}
}
class Thread1 extends Thread {
public void run(){
try{
System.out.println("even numbers");
sleep(1000);
for(int i=0;i<=20;i+=2){
System.out.println(i);}
}
catch(Exception e){
System.out.println(e);}
}
}
class Thread2 extends Thread {
public void run(){
try{
sleep(2000);
System.out.println("odd numbers");
for(int i=1;i<=20;i+=2){
System.out.println(i);}
}
catch(Exception e){
System.out.println(e);}

}
}

Output:
S:\note java>javac Oddeven.java
S:\note java>java Oddeven
even numbers
0
2
4
6
8
10
12
14
16
18
20
odd numbers
1
3
5
7
9
11
13
15
17
19

Multi threading by runnable interface with


delay of time:We create a new class which implements
java.lang.Runnable interface and override run() method. Then
we instantiate a Thread object and call start() method on this
object.

Source code:
class Thread1 implements Runnable{
public void run(){
try{
Thread.sleep(1000);
System.out.println("Oops Lab");
}
catch(Exception e){
System.out.println(e);}
}
}
class Thread2 implements Runnable{
public void run(){
try{
Thread.sleep(2000);
System.out.println("java programming");
}
catch(Exception e){
System.out.println(e);}
}
}
class Thread3 implements Runnable{
public void run(){
try{
Thread.sleep(3000);
System.out.println("multithreading");
}
catch(Exception e){
System.out.println(e);}
}
}
class Runthread{
public static void main(String args[]){
Thread1 obj1=new Thread1();
Thread2 obj2=new Thread2();
Thread3 obj3=new Thread3();
Thread ob1=new Thread(obj1);
ob1.start();
Thread ob2=new Thread(obj2);
ob2.start();
Thread ob3=new Thread(obj3);
ob3.start();
}
}

Output:
S:\note java>javac Runthread.java
S:\note java>java Runthread
Oops Lab
java programming
multithreading

Threads:
1)Printing 5 numbers from 5 to 1:
source code:
import java.util.*;
class Num5{
public static void main(String args[]){
numbers obj=new numbers();
obj.start();
}
}
class numbers extends Thread {
public void run(){
try{
System.out.println("5 numbers");
for(int i=5;i>=1;i--){
sleep(1000);
System.out.println(i);}
}
catch(Exception e){
System.out.println(e);}
}
}

Output:
S:\note java>javac Num5.java
S:\note java>java Num5
5 numbers
5
4
3
2
1

Week-12
Q. Reverse a list of elements using stack class in
java.
Source code:
import java.util.*;
import java.io.*;
public class Elementstack{
public static void main(String args[]) {
Stack<Integer> stack = new Stack<Integer>();
Scanner S=new Scanner(System.in);
System.out.println("Enter count:");
int length=S.nextInt();
int a[]=new int[length];
System.out.println("Enter the elements:");
for(int i=0;i<a.length;i++){
a[i] = S.nextInt();
stack.push(a[i]);}
System.out.println("Original List:");
System.out.println(stack);
for(int i=0;i<a.length;i++){
a[i] = stack.pop();}
System.out.println("Reverse list: ");
for(int i=0;i<a.length;i++){
System.out.println(a[i]);}
}
}
Output:
S:\note java>javac Elementstack.java
S:\note java>java Elementstack
Enter count:
5
Enter the elements:
90
80
70
60
50
Original List:
[90, 80, 70, 60, 50]
Reverse list:
50
60
70
80
90

Connection-Less communication using


Datagram socket class:udp
SERVER PROGRAM:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class udpServer {
public static void main(String[] args) throws IOException {
DatagramSocket DS= new DatagramSocket(3333);
byte[] rd = new byte[65535];
DatagramPacket DpReceive = null;
while (true) {
DpReceive = new DatagramPacket(rd, rd.length);
DS.receive(DpReceive);
System.out.println("Client:-" + data(rd));
if (data(rd).toString().equals("bye")) {
System.out.println("Client sent bye.....");
break; }
rd = new byte[65535];
}
}
public static StringBuilder data(byte[] a) {
int i=0;
if (a == null)
return null;
StringBuilder r= new StringBuilder();
while (a[i] != 0) {
r.append((char) a[i]);
i++; }
return r;
}
}

Output:

CLIENT PROGRAM:
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class udpClient {
public static void main(String args[]) throws IOException {
Scanner S= new Scanner(System.in);
DatagramSocket ds = new DatagramSocket();
InetAddress ip = InetAddress.getLocalHost();
byte buf[] = null;
while (true) {
String i= S.nextLine();
buf = i.getBytes();
DatagramPacket DpSend = new DatagramPacket(buf, buf.length, ip,
3333);
ds.send(DpSend);
if (i.equals("bye"))
break; }
}
}
OUTPUT:

Then we can see it in server output:

Q. Client server program. client sends radius of circle to


server and server calculates the area of circle and send
result back to client.
Server input program:
Source code:
import java.io.*;
import java.net.*;
class SERVERWAIT{
public static void main(String args[]){
try{
ServerSocket SS=new ServerSocket(1065);
System.out.println("Waiting for Client Request");
Socket S=SS.accept();
BufferedReader BR;
PrintStream PS;
String str;
BR=new BufferedReader(new
InputStreamReader(S.getInputStream()));
str=BR.readLine();
System.out.println("Received radius");
double r=Double.parseDouble(str);
double area=3.14*r*r;
PS=new PrintStream(S.getOutputStream());
PS.println(String.valueOf(area));
BR.close();
PS.close();
S.close();
SS.close();
}
catch(Exception e){
System.out.println(e);}
}
}

OUTPUT:
CLIENTINPUT PROGRAM:
import java.io.*;
import java.net.*;
class CLIENTINPUT{
public static void main(String args[])throws IOException{
Socket S=new Socket(InetAddress.getLocalHost(),1065);
BufferedReader BR;
PrintStream PS;
String str;
System.out.print("Enter Radius :");
BR=new BufferedReader(new InputStreamReader(System.in));
PS=new PrintStream(S.getOutputStream());
PS.println(BR.readLine());
BR=new BufferedReader(new
InputStreamReader(S.getInputStream()));
str=BR.readLine();
System.out.println("Area of the circle is : "+str);
BR.close();
PS.close();
}
}

Output:

THEN IT SHOWA RECEIVED RADIUS IN SERVER :


FRAMES

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class testswing extends JFrame

public testswing(){

JButton jb1 = new JButton("Yes");

JButton jb2 = new JButton("No");

JCheckBox jcb = new JCheckBox("may be");

JRadioButton jrb = new JRadioButton("A");

JTextField jtf = new JTextField(20);

String language[]={"Java","Python","Android","PHP","Swift"};

JComboBox cb=new JComboBox(language);

JLabel l = new JLabel("select your city ");

JPanel p = new JPanel();

add(cb);

p.add(l);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new FlowLayout());

setSize(400, 400);

add(jb1);

add(jb2);

add(jtf);
add(jcb);

add(jrb);

setVisible(true);

public static void main (String args[]){

new testswing();

OUTPUT:

S:\note java>javac testswing.java

Note: testswing.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

S:\note java>javac -Xlint:unchecked

error: no source files

S:\note java>java testswing


JComboBox using ItemListenerEvent:
import java.awt.event.*;

import java.awt.*;

import javax.swing.*;

class solve extends JFrame implements ItemListener {

static JFrame f;

static JLabel l, l1;

static JComboBox c1;

public static void main(String[] args) {

f = new JFrame("frame");

solve s = new solve();

f.setLayout(new FlowLayout());

String s1[] = { "Jalpaiguri", "Mumbai", "Noida", "Kolkata", "New Delhi" };

c1 = new JComboBox(s1);
c1.addItemListener(s);

l = new JLabel("select your city ");

l1 = new JLabel("Jalpaiguri selected");

l.setForeground(Color.red);

l1.setForeground(Color.blue);

JPanel p = new JPanel();

p.add(l);

p.add(c1);

p.add(l1);

f.add(p);

f.setSize(400, 300);

f.show();

public void itemStateChanged(ItemEvent e){

if (e.getSource() == c1) {

l1.setText(c1.getSelectedItem() + " selected");

OUTPUT:

S:\note java>javac solve.java

Note: solve.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

Note: solve.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

S:\note java>javac -Xlint:unchecked

error: no source files

S:\note java>java solve


Week-1
Fibonocci series:
Source code:
import java.lang.*;
class Fibb{
public static void main(String args[]){
int a=0,b=1,c;
int n=Integer.parseInt(args[0]);
System.out.print("fibonoci series:");
for(int i=1;i<=n;i++){
c=a+b;
System.out.print(" " +a);
a=b;
b=c;}
}
}
Output:
S:\note java>javac Fibonocci.java
S:\note java>java Fibonocci 5
fibonoci series: 0 1 1 2 3

Factorial of a number:
Source code:
import java.lang.*;
class Fact{
public static void main(String arg[]){
int fact=1;
int n=Integer.parseInt(arg[0]);
for(int i=1;i<=n;i++){
fact*=i;}
System.out.println("factorial of "+n+" is ="+fact);
}
}

Output:
S:\note java>javac Fact.java
S:\note java>java Fact 4
factorial of 4 is =24

gcd of two numbers:


source code:
import java.util.Scanner;
public class gcd {
public static void main(String args[]){
Scanner Sc=new Scanner(System.in);
System.out.println("enter two numbers:");
int n1=Sc.nextInt();
int n2=Sc.nextInt();
System.out.println("gcd of two numbers:"+gcd(n1,n2));
}
static int gcd(int n1,int n2){
if(n2==0)
return n1;
else
return gcd(n2,n1%n2);
}
}
Output:
S:\note java>javac gcd.java
S:\note java>java gcd
enter two numbers:
24 56
gcd of two numbers:8

Multiplication table:
Source code:
import java.util.Scanner;
public class Mtable{
public static void main(String args[]){
Scanner S=new Scanner(System.in);
System.out.print("enter no:");
int n=S.nextInt();
System.out.println("multiplication table of "+n+"");
for(int i=1;i<=10;i++){
System.out.println(n+"*"+i+"="+(n*i));
}
}
}

Output:
S:\note java>javac Mtable.java
S:\note java>java Mtable
enter no:4
multiplication table of 4
4*1=4
4*2=8
4*3=12
4*4=16
4*5=20
4*6=24
4*7=28
4*8=32
4*9=36
4*10=40

Q.Min and max of no.in an array:


Source code:
import java.util.Scanner;
public class maxmin{
public static void main(String[] args){
int[] a={3,4,6,9,7,10};
int max=Max(a);
int min=Min(a);
System.out.println("max:"+max);
System.out.println("min:"+min);
}
public static int Max(int[] a) {
int max=a[0];
for(int i=1;i<a.length;i++){
if(a[i]>max)
max=a[i];}
return max;
}
public static int Min(int[] a) {
int min=a[0];
for(int i=1;i<a.length;i++){
if(a[i]<min)
min=a[i];}
return min;
}
}

Output:
S:\note java>javac maxmin.java
S:\note java>java maxmin
max:10
min:3

Q. passing an array as an argument to a function:


source code:
import java.util.*;
class Parray{
public static void main(String args[]){
Scanner S=new Scanner(System.in);
System.out.print("enter count:");
int length=S.nextInt();
int a[] =new int[length];
System.out.print("enter values:");
for( int i=0;i<a.length;i++){
a[i]=S.nextInt();}
cname obj = new cname();
obj.display(a);
}
}
class cname {
void display(int a[]){
System.out.print("entered array is:");
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");}
}
}

Output:
S:\note java>javac Parray.java
S:\note java>java Parray
enter count:4
enter values:3 5 8 9
entered array is:3 5 8 9

Q. Arithmetic operations:
Source code:
import java.util.*;
class AO{
public static void main(String arg[]){
Scanner S=new Scanner(System.in);
System.out.print("enter n1 and n2:");
int n1=S.nextInt();
int n2=S.nextInt();
System.out.print("select operator:");
char operator=S.next().charAt(0);
switch(operator)
{
case '+':System.out.println("add: "+(n1+n2));
break;
case '-':System.out.println("sub: "+(n1-n2));
break;
case '*':System.out.println("mult: "+(n1*n2));
break;
case '%':if (n1>n2)
System.out.println("mod:"+(n1%n2));
else
System.out.println("mod:"+(n2%n1));
break;
case '/':if(n1>n2)
System.out.println("div:"+(n1/n2));
else
System.out.println("div:"+(n2/n1));
break;
default:System.out.println("incorect option");
return;
}
}
}

Output:
S:\note java>javac AO.java
S:\note java>java AO
1)enter n1 and n2:4 5
select operator:-
sub: -1
2)S:\note java>java AO
enter n1 and n2:4 6
select operator:*
mult: 24

Q. Grades of students based on marks:


source code:
import java.util.Scanner;
public class Grade{
public static void main(String arg[]){
int S1,S2,S3,total,per;
Scanner S=new Scanner(System.in);
System.out.print("marks:");
S1=S.nextInt();
S2=S.nextInt();
S3=S.nextInt();
total=S1+S2+S3;
System.out.println("total:"+total);
per=total/3;
switch(per/10){
case 9:System.out.println("per:"+per+" grade:Exe");
break;
case 8:System.out.println("per:"+per+" grade:A");
break;
case 7:System.out.println("per:"+per+" grade:B");
break;
case 6:System.out.println("per:"+per+" grade:C");
break;
case 5:System.out.println("per:"+per+" grade:D");
break;
case 4:System.out.println("per:"+per+" grade:E");
break;
default:System.out.println("per:"+per+" FAIL");
break;
}
}
}

Output:
S:\note java>javac Grade.java
1)S:\note java>java Grade
marks:60 80 85
total:225
per:75 grade:B
2)S:\note java>java Grade
marks:0 40 30
total:70
per:23 FAIL

Q. shortlist of students:
Source code:
import java.util.*;
class shortlist{
public static void main(String arg[]){
Scanner S=new Scanner(System.in);
System.out.print("enter students:");
int n=S.nextInt();
student obj[]=new student[n];
for(int i=0;i<n;i++){
obj[i]=new student();
System.out.println("enter details of person:"+(i+1));
obj[i].eligible();}
}
}
class student{
static int mp=80,mt=70;
int per,TM,BL;
void eligible(){
Scanner S=new Scanner(System.in);
System.out.println("enter name :");
String name =S.nextLine();
System.out.println("enter percentage :");
per=S.nextInt();
System.out.println("enter backlogs:");
BL=S.nextInt();
System.out.println("enter testmarks :");
TM=S.nextInt();
if(per>=student.mp && BL==0 && TM>=student.mt)
System.out.println("ELIGIBLE");
else
System.out.println("REGECTED");
}
}

Output:
S:\note java>javac shortlist.java
S:\note java>java shortlist
enter students:2
enter details of person:1
enter name :
vinu
enter percentage :
90
enter backlogs:
0
enter testmarks :
75
ELIGIBLE
enter details of person:2
enter name :
sowmya
enter percentage :
75
enter backlogs:
1
enter testmarks :
50
REGECTED

Q. calculating monthly salary:


Source code:
import java.util.*;
class Salary{
public static void main(String args[]){
calcsalary obj=new calcsalary();
Scanner S=new Scanner(System.in);
System.out.print("daily wages:");
obj.DW=S.nextInt();
System.out.print("workdays:");
obj.WD=S.nextInt();
System.out.print("HRA,ALLOWANCES,INCOMETAX:");
obj.HRA=S.nextInt();
obj.ALLOWANCES=S.nextInt();
obj.INCOMETAX=S.nextInt();
obj.display();
System.out.println("basic salary:"+obj.MS);
System.out.println("final salary:"+obj.FS);
}
}
class calcsalary{
int DW,WD,MS,HRA,ALLOWANCES,INCOMETAX,FS;
void display(){
MS=DW*WD;
FS=MS+HRA+ALLOWANCES-INCOMETAX;}
}

Output:
S:\note java>javac Salary.java
S:\note java>java Salary
daily wages:200
workdays:28
HRA,ALLOWANCES,INCOMETAX:300 3000 1500
basic salary:5600
final salary:7400
UNIT-V
Collections(single unit of objects) framework
(represent set of classes and interfaces).
It gives the programmer access to prepackaged data structures as well as to
algorithms for manipulating them.
A collection is an object that can hold references to other objects. The collection
interfaces declare the operations that can be performed on each type of collection.
The classes and interfaces of the collections framework are in package java.util.
Interfaces:
Iterable interface: Iterable interface is the root interface for all the collection
classes.

Collection interface:This enables you to work with groups of objects; it is at the top of
the collections hierarchy.
List interface:This extends Collection and an instance of List stores an ordered collection of
elements.
Queue interface: ordered list that is used to hold the elements which are about to be
processed.

Deque interface: we can remove and add the elements from both the side

Set: This extends Collection to handle sets, which must contain unique elements.
Sortedsets: This extends Set to handle sorted sets.

Classes:
Array list:Implements a dynamic array by extending AbstractList.
Linkedlist: Implements a linked list by extending AbstractSequentialList.

Vector: This implements a dynamic array. It is similar to ArrayList, but with some
differences.
Stack: Stack is a subclass of Vector that implements a standard last-in, first-out stack.

Priority Queue: It holds the elements or objects which are to be processed by their
priorities.it doesn't allow null values to be stored in the queue.

Array Deque: we can add or delete the elements from both the ends.

Hashset:Extends AbstractSet for use with a hash table


Linkedhashset: Extends HashSet to allow insertion-order iterations.
Treeset: Implements a set stored in a tree. Extends AbstractSet.

Program to read from a file using BufferedReader class

import java.IO.*;
class Readtest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}

Program to write to a File using FileWriter class

import java.IO.*;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
Standard streams:
By default, they read input from the keyboard and write output to the display. They also support
I/O operations on files.

 Standard Input: This is used to read data from user through input devices.
keyboard is used as standard input stream and represented as System.in.
 Standard Output:  This is used to project data (results) to the user through output
devices. A computer screen is used for standard output stream and represented
as System.out.
 Standard Error: This is used to output the error data produced by the user's
program and usually a computer screen is used for standard error stream and
represented as System.err.

import java.io.*;

public class ReadStandardIO{

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

InputStreamReader inp = new InputStreamReader(System.in)

BufferedReader br = new BufferedReader(inp);

System.out.println("Enter text : ");

String str = in.readLine();

System.out.println("You entered String : ");

System.out.println(str);

}
Expected output:
Enter text :
this is an Input Stream
You entered String :
this is an Input Stream

Buffered streams classes in Java

There are four buffered stream classes-

BufferedInputStream and BufferedOutputStream are used to wrap


unbuffered byte streams to create buffered byte
streams.BufferedReader and BufferedWriter are used to wrap unbuffered
character streams to create buffered character streams.

flush() Method

To clear the internal buffer, we can use the  flush()  method. This method forces
the output stream to write all data present in the buffer to the destination file. 

Constructors:

BufferedReader(Reader rd)

BufferedReader(Reader rd, int size)

Methods:

Void close();

Void reset();

int read()l

1. package com.javatpoint;  
2. import java.io.*;  
3. public class BufferedReaderExample {  
4.     public static void main(String args[])throws Exception{    
5.           FileReader fr=new FileReader("D:\\testout.txt");    
6.           BufferedReader br=new BufferedReader(fr);    
7.   
8.           int i;    
9.           while((i=br.read())!=-1){  
10.           System.out.print((char)i);  
11.           }  
12.           br.close();    
13.           fr.close();    
14.     }    
15. }    
16.
17.import java.io.BufferedInputStream;
18.import java.io.FileInputStream;
19.class Main {
20. public static void main(String[] args) {
21. try {
22. FileInputStream file = new FileInputStream("input.txt");
23. BufferedInputStream input = new BufferedInputStream(file);
24. int i = input .read();
25. while (i != -1) {
26. System.out.print((char) i);
27. i = input.read();
28. }
29. input.close();
30. }
31. catch (Exception e) {
32. e.getStackTrace();
33. }
34. }
35.}

String Tokenizer:
java.util.StringTokenizer class allows you to break a string into tokens. 

import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}  
Output:my
name
is
khan
String Buffer class:
StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in
java is same as String class except it is mutable i.e. it can be changed.

StringBuffer() creates an empty string buffer with the initial capacity of

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int capacity) creates an empty string buffer with the specified capacity

class StringBufferExample{

public static void main(String args[]){

StringBuffer sb=new StringBuffer("Hello ");

sb.append("Java");

System.out.println(sb);

Output:Hello java

Java DatagramSocket class


Java DatagramSocket class represents a connection-less socket for sending and
receiving datagram packets.

A datagram is basically an information but there is no guarantee of its content, arrival or


arrival time.
Constructors:

o DatagramSocket() throws SocketException


o DatagramSocket(int port) throws SocketException
o DatagramSocket(int port, InetAddress address) throws SocketException

Java DatagramPacket class


Java DatagramPacket is a message that can be sent or received. If you send multiple
packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.

Constructors:

o DatagramPacket(byte[] barr, int length)->used to receive packets.


o DatagramPacket(byte[] barr, int length, InetAddress address, int port): used
to send the packets.

Java InetAddress class:
It represents an IP address. The java.net.InetAddress class provides methods to get the
IP of any host name.

An IP address is represented by 32-bit or 128-bit unsigned number. An instance of


InetAddress represents the IP address with its corresponding host name. There are two
types of address types: Unicast and Multicast. The Unicast is an identifier for a single
interface whereas Multicast is an identifier for a set of interfaces.

Method names:

getHostName();

getHostAddress();

1. import java.util.*;  
2. class TreeMap1{  
3.  public static void main(String args[]){  
4.    TreeMap<Integer,String> map=new TreeMap<Integer,String>();    
5.       map.put(100,"Amit");    
6.       map.put(102,"Ravi");    
7.       map.put(101,"Vijay");    
8.       map.put(103,"Rahul");    
9.         
10.       for(Map.Entry m:map.entrySet()){    
11.        System.out.println(m.getKey()+" "+m.getValue());    
12.       }    
13.  }  
14. }  

Output:100 Amit
101 Vijay
102 Ravi
103 Rahul
1. import java.io.*;  
2. public class ReaderExample {  
3.     public static void main(String[] args) {  
4.         try {  
5.             Reader reader = new FileReader("file.txt");  
6.             int data = reader.read();  
7.             while (data != -1) {  
8.                 System.out.print((char) data);  
9.                 data = reader.read();  
10.             }  
11.             reader.close();  
12.         } catch (Exception ex) {  
13.             System.out.println(ex.getMessage());  
14.         }  
15.     }  
16. }  

1. import java.io.*;  
2. public class WriterExample {  
3.     public static void main(String[] args) {  
4.         try {  
5.             Writer w = new FileWriter("output.txt");  
6.             String content = "I love my country";  
7.             w.write(content);  
8.             w.close();  
9.             System.out.println("Done");  
10.         } catch (IOException e) {  
11.             e.printStackTrace();  
12.         }  
13.     }  
14. }  

Output:done

Sort list in java

1. import java.util.*;  
2. import java.util.stream.*;  
3. public class SortListExample1  
4. {  
5. public static void main(String[] args)   
6. {  
7. //returns a list view   
8. List<String> slist = Arrays.asList("Tanu", "Kamal", "Suman", "Lucky", "Bunty", "A
mit");  
9. List<String> sortedList = slist.stream().sorted().collect(Collectors.toList());     
10. sortedList.forEach(System.out::println);  
11. }  
12. }  

1. public class WritePropertyFile{


2.
3. public static void main(String[] args) {
4.
5. try (OutputStream output = new FileOutputStream("config.properties")) {
6.
7. Properties prop = new Properties();
8.
9. // set the properties value
10. prop.setProperty("database", "localhost");
11. prop.setProperty("username", "Codingeek");
12. prop.setProperty("password", "Codingeek");
13.
14. // save properties to project root folder.
15. prop.store(output, null);
16.
17. } catch (IOException exception) {
18. exception.printStackTrace();
19. }
20.
21. }
22. }

Output:-
#Sun Aug 24 13:34:24 IST 2014
password=Codingeek
database=localhost
username=Codingeek

Serialization: Serialization in Java is a mechanism of writing the state of an object into


a byte-stream. deserialization where byte-stream is converted into an object. The
serialization and deserialization process is platform-independent, it means you can
serialize an object in a platform and deserialize in different platform.

For serializing the object, we call the writeObject() method ObjectOutputStream, and


for deserialization we call the readObject() method of ObjectInputStream class.

1. import java.io.*;  
2. class Persist{  
3.  public static void main(String args[]){  
4.   try{  
5.   //Creating the object  
6.   Student s1 =new Student(211,"ravi");  
7.   //Creating stream and writing the object  
8.   FileOutputStream fout=new FileOutputStream("f.txt");  
9.   ObjectOutputStream out=new ObjectOutputStream(fout);  
10.   out.writeObject(s1);  
11.   out.flush();  
12.   //closing the stream  
13.   out.close();  
14.   System.out.println("success");  
15.   }catch(Exception e){System.out.println(e);}  
16.  }  
17. }  

You might also like