0% found this document useful (0 votes)
93 views78 pages

Java Programs

The document contains code examples demonstrating various Java programming concepts including: 1) Defining classes with methods and using objects of those classes. Code shows defining classes with fields and methods, and creating objects to call methods. 2) Using arrays of objects by defining a class with fields, a default constructor, and creating an array of objects of that class. 3) Demonstrating inheritance by defining a superclass with fields and methods, and subclasses that inherit from the superclass.

Uploaded by

Radhika Rahane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
93 views78 pages

Java Programs

The document contains code examples demonstrating various Java programming concepts including: 1) Defining classes with methods and using objects of those classes. Code shows defining classes with fields and methods, and creating objects to call methods. 2) Using arrays of objects by defining a class with fields, a default constructor, and creating an array of objects of that class. 3) Demonstrating inheritance by defining a superclass with fields and methods, and subclasses that inherit from the superclass.

Uploaded by

Radhika Rahane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 78

Chapter 01 : Introduction to Java

class AsciiValues
{
public static void main(String[] args)
{
char c;
for(int i=0;i<=255;i++)
{
c=(char)i;
System.out.print(i+" : "+c+" ");
}
}
}

class DemoVar
{

int data=50;

static int d=100;

public static void main(String[] args)


{
int c = 20;

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

DemoVar obj=new DemoVar();

System.out.println("data="+obj.data);
}
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

class CheckAlpha
{
public static void main(String[] args) throws IOException
{
char c;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter character : ");
c = (char)br.read();
if((c>='a' && c<='z') || (c>='A' && c<='Z'))
{
System.out.println("Given character is alphabet");
}
else
{
System.out.println("Given character is not alphabet");
}
}
}

import java.util.Scanner;

class AcceptInput
{
public static void main(String[] args)
{
int a,b,c;

Scanner sc=new Scanner(System.in);

System.out.println("Enter value of a : ");


a=sc.nextInt();

System.out.println("Enter value of b : ");


b=sc.nextInt();

c=a+b;

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

}
}

import java.util.Scanner;

class LargestNumber
{
public static void main(String[] args)
{
int a,b,c;
Scanner sc=new Scanner(System.in);
System.out.println("Enter any three numbers : ");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();

if(a>b)
{
if(a>c)
{
System.out.println(a+" is Largest");
}
else
{
System.out.println(c+" is Largest");
}
}
else
{
if(b>c)
{
System.out.println(b+" is Largest");
}
else
{
System.out.println(c+" is Largest");
}
}
}
}

import java.util.Scanner;

class SwitchDemo
{
public static void main(String[] args)
{
int no1,no2,result = 0;
int ch,ch1;
Scanner sc=new Scanner(System.in);
System.out.println("Enter no1 and no2 : ");
no1 = sc.nextInt();
no2 = sc.nextInt();
do{
System.out.println("MENU");
System.out.println("1:ADD\n2:SUB\n3:MUL\n4:DIV");
System.out.println("Enter Your Choice : ");
ch=sc.nextInt();
switch(ch)
{
case 1:
result = no1 + no2;
System.out.println("Addition = "+result);
break;
case 2:
result = no1 - no2;
System.out.println("Subtraction = "+result);
break;
case 3:
result = no1 * no2;
System.out.println("Multiplication = "+result);
break;
case 4:
result = no1 / no2;
System.out.println("Division = "+result);
break;
default:
System.out.println("Please enter valid choice");
}
System.out.println("Do you want to continue,");
System.out.println("Enter 1 else Enter 0 : ");
ch1 = sc.nextInt();
}while(ch1==1);

}
}

import java.util.Scanner;

class MultiplicationTable
{
public static void main(String[] args)
{
int n,i;
Scanner sc=new Scanner(System.in);

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


n=sc.nextInt();

for(i=1;i<=10;i++)
{
System.out.println(n+" * "+i+" = "+(n*i));
}
}
}

public class ForLoop


{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50, 60, 70, 80};
for(int x : numbers )
{
System.out.print( x );
System.out.print(",");
}
}
}

class CmdArgs
{
public static void main(String[] args)
{
int len;
len=args.length;
for(int i=0;i<len;i++)
{
System.out.println("args["+i+"] = "+args[i]);
}
}
}

class CmdArgs1
{
public static void main(String[] args)
{
int arg1=Integer.parseInt(args[0]);
float arg2=Float.parseFloat(args[1]);
String s=args[2];

float sum = arg2 + arg1;

System.out.println("Addition = "+sum);
System.out.println("String = "+s);
}
}

class CmdArgs2
{
public static void main(String[] args)
{
int n = Integer.parseInt(args[0]);
int fact = 1;
for(int i=n;i>=1;i--)
{
fact = fact * i;
}
System.out.println("Factorial = "+fact);
}
}

class TypeCastingDemo
{
int a;
long l;
float b;
double d;

void autoCasting()
{
a=100;
l=a;
System.out.println("l : "+l);
b=(float)75.23;
d=b;
System.out.println("d : "+d);

void manualCasting()
{
l=10000;
//a=l;
a=(int)l;
System.out.println("a : "+a);

d=755.23;
//b=d;
b=(float)d;
System.out.println("b : "+b);
}
}

public class RunTypeCastingDemo


{
public static void main(String[] args)
{
TypeCastingDemo obj1=new TypeCastingDemo();
obj1.autoCasting();
obj1.manualCasting();
}
}

class MathFunctions
{
public static void main(String[] args)
{
int i1,i2;
double d1;
double a1,b1;
double e1;
float f1;
float f2;

i1=35;
i2=58;
int minimum=Math.min(i1,i2);
int maximum=Math.max(i1,i2);

d1=64.00;
double squareroot=Math.sqrt(d1);

a1=2;
b1=4;
double power=Math.pow(a1,b1);
e1=175;
double exponential=Math.exp(e1);

f1=75.20f;
int roundval=Math.round(f1);

f2=50.26f;
float absval=Math.abs(f2);

System.out.println("min() = "+minimum);
System.out.println("max() = "+maximum);
System.out.println("sqrt() = "+squareroot);
System.out.println("pow() = "+power);
System.out.println("exp() = "+exponential);
System.out.println("round() = "+roundval);
System.out.println("abs() = "+absval);
}
}

public class AbsExample1


{
public static void main(String args[])
{
int x = 78;
int y = -48;
//print the absolute value of int type
System.out.println(Math.abs(x));
System.out.println(Math.abs(y));
System.out.println(Math.abs(Integer.MIN_VALUE));
}
}

Chapter 02 : Classes and Objects

class DemoClass
{

void show()
{
System.out.println("Welcome to GPN");
}

public static void main(String [] args)


{
DemoClass obj=new DemoClass();
obj.show();
}

}
class MyClassDemo
{
int a=10;
float b=20.5f;
char c='N';

public void myFirstMethod()


{
System.out.println("a = "+a);
System.out.println("b = "+b);
System.out.println("c = "+c);
}
public static void main(String[] args)
{

MyClassDemo obj1=new MyClassDemo();


MyClassDemo obj2=new MyClassDemo();
MyClassDemo obj3=new MyClassDemo();

obj1.a++;
obj2.b++;
obj3.c='B';

obj1.myFirstMethod();
obj2.myFirstMethod();
obj3.myFirstMethod();
}
}

class DemoArrayOfObjects
{
int rollno;
String sname;

public DemoArrayOfObjects() //default constructor


{
rollno=145108;
sname="Nikita";
}
public static void main(String [] args)
{
DemoArrayOfObjects array[]=new DemoArrayOfObjects[5];
for(int i=0; i<5; i++)
{
array[i] = new DemoArrayOfObjects(); //array of objects
}
for(int i=0; i<5; i++)
{
System.out.println(array[i].toString());
}
}
}
Constructor programs:

class ConstructorDemo1 //jvm will provide its own default constructor


{
int a;
float f;
String s;

public void display()


{
System.out.println("a = "+a);
System.out.println("f = "+f);
System.out.println("s = "+s);
}

public static void main(String[] args)


{
ConstructorDemo1 obj=new ConstructorDemo1();
obj.display();
}
}

class ConstructorDemo2
{
int a;
float f;
String s;

public ConstructorDemo2() //default constructor


{
a = 05;
f = 5.23f;
s = "Nikita";
}

public void display()


{
System.out.println("a = "+a);
System.out.println("f = "+f);
System.out.println("s = "+s);
}

public static void main(String[] args)


{
ConstructorDemo2 obj=new ConstructorDemo2();
obj.display();
}
}
class ConstructorDemo3
{
int a;
float f;
String s;

public ConstructorDemo3()
{
a = 05;
f = 5.23f;
s = "Nikita";
}

public void display()


{
System.out.println("a = "+a);
System.out.println("f = "+f);
System.out.println("s = "+s);
}

public static void main(String[] args)


{
ConstructorDemo3 obj1=new ConstructorDemo3();
obj1.display();

ConstructorDemo3 obj2=new ConstructorDemo3();


obj2.display();

ConstructorDemo3 obj3=new ConstructorDemo3();


obj3.display();
}
}

class ConstructorDemo4
{
int a;
float f;
String s;

public ConstructorDemo4()
{
a = 0;
f = 0.0f;
s = null;
}

public ConstructorDemo4(int para1, float para2, String para3)


{
a = para1;
f = para2;
s = para3;
}
public void display()
{
System.out.println("a = "+a);
System.out.println("f = "+f);
System.out.println("s = "+s);
}

public static void main(String[] args)


{
ConstructorDemo4 obj1=new ConstructorDemo4();
obj1.display();

ConstructorDemo4 obj2=new ConstructorDemo4(14,8.26f,"Nachiket");


obj2.display();
}
}

class ConstructorDemo5 //constructor overloading


{
int a;
float f;
String s;

public ConstructorDemo5()
{
a=0;
f=0.0f;
s=null;
}

public ConstructorDemo5(int para1)


{
a=para1;
f=0.0f;
s=null;
}

public ConstructorDemo5(int para1, String para2)


{
a=para1;
f=0.0f;
s=para2;
}

public ConstructorDemo5(float para1)


{
a=0;
f=para1;
s=null;
}
public ConstructorDemo5(int para1, float para2, String para3)
{
a = para1;
f = para2;
s = para3;
}

public void display()


{
System.out.println("a = "+a);
System.out.println("f = "+f);
System.out.println("s = "+s);
}

public static void main(String[] args)


{
ConstructorDemo5 obj1=new ConstructorDemo5();
obj1.display();

ConstructorDemo5 obj2=new ConstructorDemo5(14);


obj2.display();

ConstructorDemo5 obj3=new ConstructorDemo5(23,"Shivam");


obj3.display();

ConstructorDemo5 obj4=new ConstructorDemo5(32.53f);


obj4.display();

ConstructorDemo5 obj5=new ConstructorDemo5(35,44.50f,"Shivam");


obj5.display();
}
}

class ConstructorDemo7 //this keyword example


{
int rollno;
float marks;
String name;
public ConstructorDemo7(int rollno, float marks, String name)
{
this.rollno = rollno;
this.marks = marks;
this.name = name;
}
public void display()
{
System.out.println("rollno = "+rollno);
System.out.println("marks = "+marks);
System.out.println("name = "+name);
this.show();
}
public void show()
{
System.out.println("Show");
}

public static void main(String[] args)


{
ConstructorDemo7 obj1=new ConstructorDemo7(5,90.23f,"Nikita");
obj1.display();
}
}

class ChainedConstructor
{
int a;
String sname;

public ChainedConstructor()
{
this(10);
}

public ChainedConstructor(int p1)


{
this(p1,"GPN");
}

public ChainedConstructor(int p2,String p3)


{
a=p2;
sname=p3;
}

void show()
{
System.out.println("a = "+a);
System.out.println("sname = "+sname);
}

public static void main(String[] args)


{
ChainedConstructor obj=new ChainedConstructor();
obj.show();
}
}

import java.io.IOException;
class GarbageDemo1
{
int a;
String s;
public GarbageDemo1()
{
a=10;
s="nashik";
}

void display()
{
System.out.println("a = "+a);
System.out.println("s = "+s);
}

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


{
GarbageDemo1 obj=new GarbageDemo1();

obj.display();

obj=null;

System.gc();

System.out.println("object has no reference");

System.in.read();

System.out.println("now object is destroyed by GC");


}
}

import java.io.IOException;

class GarbageDemo3
{
int a;
String s;

public GarbageDemo3()
{
a=10;
s="nashik";
}

void display()
{
System.out.println("a = "+a);
System.out.println("s = "+s);
}

protected void finalize()


{
System.out.println("");
System.out.println("finalize() method");
System.out.println("this method is called automatically");
System.out.println("just before deleting object");
System.out.println("so write your clean up code here");
}

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


{
GarbageDemo3 obj=new GarbageDemo3();
obj.display();
obj=null;
System.gc();
GarbageDemo3 obj1=new GarbageDemo3();
obj1.display();
int c=10+25;
System.out.println("c = "+c);
obj1.display();
}
}

class MethodOverloading1
{
void area()
{
System.out.println("default method - area");
}
void area(int r)
{
float pi = 3.14f;
float ac = pi * r * r;
System.out.println("circle = "+ac);
}
void area(int b, int h)
{
float at = (b*h)/2;
System.out.println("triangle = "+at);
}
void area(float l, float br)
{
float ar = l * br;
System.out.println("rectangle = "+ar);
}

public static void main(String[] args)


{
MethodOverloading1 obj=new MethodOverloading1();
obj.area();
obj.area(14);
obj.area(8,6);
obj.area(5.0f,8.5f);
}
}
class InnerStaticClass
{
int a = 10;
static class InnerStatic
{
static int b=25;

static void demo()


{
b=b+5;
}
}
void display()
{
InnerStatic.demo();
a = a + InnerStatic.b;
System.out.println("a = "+a);
System.out.println("b = "+InnerStatic.b);
}
public static void main(String[] args)
{
InnerStaticClass obj=new InnerStaticClass();
obj.display();
}
}

class Outer{

int a=5;

class Inner{
public void show(){
System.out.println("Inside inner and a = "+a);
}
}

public void show()


{
System.out.println("Inside show");
}

public void display(){


Inner in=new Inner();
in.show();
show();
System.out.println("..and then outside class");
}
public static void main(String[] args){
Outer ot=new Outer();
ot.display();
}
}
class Outer1{
int count;
public void display()
{
for(int i=0;i<5;i++)
{
class Inner1 //Inner class defined inside for loop
{
public void show(){
System.out.println("Inside inner "+(count++));
}
}

Inner1 in=new Inner1();


in.show();
}
}
public static void main(String[] args)
{
Outer1 ot=new Outer1();
ot.display();
}
}

interface Animal{
void type();
}
public class ATest
{
public static void main(String args[])
{
Animal an = new Animal(){ //Annonymous class created
public void type(){
System.out.println("Annonymous animal");
}
};
an.type();
}
}

class StaticVariable
{
static String college = "GPN";
}
class StaticVarDemo
{
public static void main(String[] args)
{
System.out.println(StaticVariable3.college);
}
}
class VarDemo1
{
int counter;

public VarDemo1()
{
counter=0;
}

public void increment()


{
counter++;
}

public void display()


{
System.out.println("counter = "+counter);
}

public static void main(String[] args)


{
VarDemo1 o1=new VarDemo1();
VarDemo1 o2=new VarDemo1();
VarDemo1 o3=new VarDemo1();
VarDemo1 o4=new VarDemo1();
VarDemo1 o5=new VarDemo1();

o1.increment();
o1.display();
Output:
o2.increment();
o2.display();
1
o3.increment();
1
o3.display();
1
o4.increment();
o4.display();
1
o5.increment();
1
o5.display();
}
}

class VarDemo2
{
static int counter = 0;
public void increment()
{
counter++;
}
public void display()
{
System.out.println("counter = "+counter);
}

public static void main(String[] args)


{
VarDemo2 o1=new VarDemo2();
VarDemo2 o2=new VarDemo2();
VarDemo2 o3=new VarDemo2();
VarDemo2 o4=new VarDemo2();
VarDemo2 o5=new VarDemo2();

o1.increment();
o1.display();

o2.increment(); Output:
o2.display();
1
o3.increment();
o3.display(); 2
o4.increment(); 3
o4.display();
4
o5.increment();
o5.display(); 5
}
}
class StaticVariable2
{
int rollno;
String sname;
static String college = "GPN";

public StaticVariable2(int rn,String sn)


{
rollno = rn;
sname = sn;
}

public void display()


{
System.out.println(rollno+" , "+sname+" , "+college);
}

public static void main(String[] args)


{
StaticVariable1 o1=new StaticVariable1(01,"Jay");
StaticVariable1 o2=new StaticVariable1(02,"Mayuri");
StaticVariable1 o3=new StaticVariable1(03,"Priyanka");
o1.display();
o2.display();
o3.display();
}
}

class StaticMethod
{
void show1()
{
System.out.println("This is non-static method");
}

static void show2()


{
System.out.println("This is static method");
}

public static void main(String[] args)


{
StaticMethod obj=new StaticMethod();
obj.show1();

show2();
}
}

class StaticMethod1
{
public static void main(String[] args)
{
StaticMethod.show2();
}
}

class StaticBlock
{
static int college_id;
static String college;
static float rating;

static
{
System.out.println("try it");
college_id = 3;
college = "GPN";
rating = 5.5f;
}

static void show()


{
System.out.println(college_id+" , "+college+" , "+rating);
}
public static void main(String[] args)
{
show();
}
}

class Empty //this is a valid class definition


{

class SuperMethod1
{
void display()
{
System.out.println("In Super 1");
}
}

class SubMethod1 extends SuperMethod1


{
public static void main(String [] args)
{
SubMethod1 obj=new SubMethod1();
obj.display();
}
}

class Bank
{
int roi()
{
return 0;
}
}

class SBI extends Bank


{
int roi()
{
return 7;
}
}
class ICICI extends Bank
{
int roi()
{
return 8;
}
}
class BOB extends Bank
{
int roi()
{
return 9;
}
}

class Test2
{
public static void main(String [] args)
{
SBI o1=new SBI();
ICICI o2=new ICICI();
BOB o3=new BOB();
System.out.println("SBI : "+o1.roi());
System.out.println("ICICI : "+o2.roi());
System.out.println("BOB : "+o3.roi());
}
}
class A
{
int a=25;

void show1()
{
System.out.println("In A");
}
}
class B extends A
{
int b=26;
void show2()
{
System.out.println("In B");
show1();
}
}
class c extends B
{
int c1=27;
void show3()
{
System.out.println("In C");
show2();
}
}

class d extends c
{
int d1=28;
void show4() {
System.out.println("In D");
show3();
System.out.println(a);
System.out.println(b);
System.out.println(c1);
System.out.println(d1);
}
}

class e
{
public static void main(String [] args)
{
d obj=new d();
obj.show4();
}
}

import java.awt.*;
class MyFrame extends Frame
{
public MyFrame()
{
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout());
Button b1=new Button("Click Me");
add(b1);
Label i1=new Label("GPN");
add(i1);
}
public static void main(String[] args)
{
MyFrame obj=new MyFrame();
}
}

class Super1
{
String name;

void display()
{
System.out.println("stud name : "+name);
}
}

class Sub1 extends Super1


{
String name;
void display()
{
name="Ajay";
name="GPN";
System.out.println("college name : "+name);
}
}

class RunDemo1
{
public static void main(String [] args)
{
Sub1 obj=new Sub1();
obj.display();
}
}

class Super2
{
String name;

void display()
{
System.out.println("stud name : "+name);
}
}

class Sub2 extends Super2


{
String name;

void display()
{
super.name="Ajay";
name="GPN";
super.display();
System.out.println("college name : "+name);
}
}

class RunDemo2
{
public static void main(String [] args)
{
Sub2 obj=new Sub2();
obj.display();
}
}

class Super3
{
String name;

Super3()
{
name=null;
}

public Super3(String name)


{
this.name=name;
}

void display()
{
System.out.println("stud name : "+name);
}
}

class Sub3 extends Super3


{
String name;

public Sub3(String name)


{
super();
this.name=name;

void display()
{
super.display();
System.out.println("college name : "+name);
}
}

class RunDemo3
{
public static void main(String [] args)
{
Sub3 obj=new Sub3("GPN");
obj.display();
}
}

class Animal{
void eat(){
System.out.println("eating");
}
}
class Dog extends Animal{
void eat(){
System.out.println("eating fruits");
}
}
class BabyDog extends Dog{
void eat(){
System.out.println("drinking milk");
}
}
public class Test{
public static void main(String args[]){
Animal a1;
a1=new Animal();
a1.eat();
a1=new Dog();
a1.eat();
a1=new BabyDog();
a1.eat();
}
}

class DemoDyn1
{
void display()
{
System.out.println("In Super");
}
}

class DemoDyn2 extends DemoDyn1


{
void display()
{
System.out.println("In Sub");
}

public static void main(String [] args)


{
DemoDyn1 obj=new DemoDyn2();
obj.display();
obj=new DemoDyn1();
obj.display();
}
}

class DemoFinalVar
{
final int val=25;

void change()
{
val=30;
}
}

class DemoFinalMethod extends DemoFinalVar


{
public static void main(String[] args)
{
DemoFinalMethod obj=new DemoFinalMethod();
obj.change();
}
}

class DemoFinalVar
{
final void demo()
{
System.out.println("Can't Overrride");
}
}

class DemoFinalMethod extends DemoFinalVar


{
void demo()
{
System.out.println("Overrriding is not possible");
}

public static void main(String[] args)


{
DemoFinalMethod obj=new DemoFinalMethod();
obj.demo();
}
}

class DemoFinal
{
int a=10;
}

class DemoFinalInheritance extends DemoFinal


{
public static void main(String[] args)
{
System.out.println("extends not possible");
}
}

class DemoArgs //object as an argument


{
void disp(DemoArgs s1)
{
System.out.println("obj = "+s1);
}
public static void main(String[] args)
{
DemoArgs obj=new DemoArgs();
obj.disp(obj);
}
}

abstract class MyClass


{
abstract void absmethod();
void demo()
{
System.out.println("inside first class");
}
}

class FirstMyClass extends MyClass


{
void absmethod()
{
System.out.println("inside second class - abstract method");
}
void show()
{
System.out.println("inside second class");
}
}

class RunMyClass
{
public static void main(String[] args)
{
FirstMyClass o=new FirstMyClass();
o.absmethod();
o.demo();
o.show();
}
}

package p1;

public class A
{
int a=23;
public int b=35;
private int c=41;
protected int d=50;
public void show()
{
System.out.println("Package p1 - Class A");
System.out.println("default variable a = "+a);
System.out.println("public variable b = "+b);
System.out.println("private variable c = "+c);
System.out.println("protected variable d = "+d);
}
}

package p1;

public class B extends A


{
public void show()
{
System.out.println("\n\nPackage p1 - Sub Class B of A");
System.out.println("default variable a = "+a);
System.out.println("public variable b = "+b);
System.out.println("protected variable d = "+d);
System.out.println("private variable c = "+c);
}
}

package p2;

import p1.A;
import p1.B;

class C extends B
{
public void show()
{
System.out.println("\n\nPackage p2 - Sub Class C of B");
System.out.println("public variable b = "+b);
System.out.println("protected variable d = "+d);
System.out.println("default variable a = "+a);
System.out.println("private variable c = "+c);
}

public static void main(String[] args)


{
A obj;
obj=new A(); obj.show();
obj=new B(); obj.show();
obj=new C(); obj.show();
}
}

package p1;
import p1.A;

class D
{
public void show()
{
A o=new A();
System.out.println("\n\nPackage p2 - Sub Class C of B");
System.out.println("public variable b = "+o.b);
System.out.println("protected variable d = "+o.d);
System.out.println("default variable a = "+o.a);
System.out.println("private variable c = "+o.c);
}

public static void main(String[] args)


{
D obj=new D();
obj.show();
}
}

class StringDemo
{
public static void main(String[] args)
{
String targetString = "Java is fun to learn";
String s1= "JAVA";
String s2= "java";
String s3 = " Hello Java ";

System.out.println("Char at index 2(third position): " + targetString.charAt(2));


System.out.println("After Concat: "+ targetString.concat(s1));
System.out.println("Checking equals ignoring case: " +s2.equalsIgnoreCase(s1));
System.out.println("Checking equals with case: " +s2.equals(s1));
System.out.println("Checking Length: "+ targetString.length());
System.out.println("Replace function: "+ targetString.replace("fun", "easy"));
System.out.println("Trim function: "+s3.trim());
System.out.println("Upper case function: "+s2.toUpperCase());
System.out.println("Lower case function: "+s1.toLowerCase());
System.out.println("Lower case function: "+targetString.substring(5));
}
}

class StringBufferExample{

public static void main(String args[]){

StringBuffer sb1=new StringBuffer("Hello ");


sb1.append("Java");//now original string is changed
System.out.println(sb1);//prints Hello Java
StringBuffer sb2=new StringBuffer("Hello ");
sb2.insert(1,"Java");//now original string is changed
System.out.println(sb2);//prints HJavaello

StringBuffer sb3=new StringBuffer("Hello");


sb3.replace(1,3,"Java");
System.out.println(sb3);//prints HJavalo

StringBuffer sb4=new StringBuffer("Govt. Poly. Nashik");


System.out.println(sb4.reverse());

StringBuffer sb5=new StringBuffer();


System.out.println("Initial Capacity : "+sb5.capacity());
sb5.append("RitikaBhosaleCMIFkjashdkjahdkjashdkjashdkjashdkjashaskjd");
System.out.println("Capacity : "+sb5.capacity());

}
}

import java.util.*;
public class VectorDemo {
public static void main(String args[]) {
int n;
String s;
Vector v = new Vector(3,2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " + v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " +(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}

import java.util.*;
public class VectorDemo1 {

public static void main(String args[]) {

int n;
int s;
Vector v = new Vector(3,2);

Scanner sc=new Scanner(System.in);

System.out.println("Enter no of elements :");


n=sc.nextInt();

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


for(int i=0;i<n;i++)
{
s=sc.nextInt();
v.addElement(new Integer(s));
}

v.remove(2);

System.out.println("\nElements in vector:");
for(int i=0;i<n;i++)
{
System.out.print(v.elementAt(i)+ ", ");
}
System.out.println();
}
}

import java.io.*;
class WrapperExample
{
public static void main(String[] args) throws IOException
{
int a=25;
int b=25;
Integer o1=a;
Integer intObj1 = new Integer (25);
Integer intObj2 = new Integer ("25");
Integer intObj3 = new Integer (15);

//compareTo demo
System.out.println("Comparing using compareTo Obj1 and Obj2: " + intObj1.compareTo(intObj2));
System.out.println("Comparing using compareTo Obj1 and Obj3: " + intObj1.compareTo(intObj3));

//Equals demo
System.out.println("Comparing using equals Obj1 and Obj2: " + intObj1.equals(intObj2));
System.out.println("Comparing using equals Obj1 and Obj3: " + intObj1.equals(intObj3));

System.in.read();

Float f1 = new Float("2.25f");


Float f2 = new Float("20.43f");
Float f3 = new Float(2.25f);

System.out.println("Comparing using compare f1 and f2: " +Float.compare(f1,f2));


System.out.println("Comparing using compare f1 and f3: " +Float.compare(f1,f3));

//Addition of Integer with Float


Float f = intObj1.floatValue() + f1;
System.out.println("Addition of intObj1 and f1: "+ intObj1 +"+" +f1+"=" +f );

int a1=20;
Integer i=new Integer(a1);
double d=i.doubleValue();
System.out.println("int value is "+a1+"; double value is "+d);
}
}

Chapter 03 : Packages and Interfaces

package pack1;

class MyPackageDemo1
{
public static void main(String[] args)
{
System.out.println("hello java");
}
}

javac -d . MyPackageDemo1.java

java pack1.MyPackageDemo1

package pack1.pack2.pack3;

class MyPackDemo2
{
public static void main(String[] args)
{
System.out.println("");
}
}
package p1;

public class A
{
public void show()
{
System.out.println("I AM A");
}
}

package p2;

import p1.A;

class B
{
public static void main(String[] args)
{
A o1=new A();
o1.show();
}
}

interface Demo1
{
void add();
void sub();
}

interface Demo2
{
void add();
}

class Demo3 implements Demo1,Demo2


{
public void sub()
{
System.out.println("sub");
}

public void add()


{
System.out.println("add");
}

void show()
{
System.out.println("Hello Java");
}
public static void main(String [] args)
{
Demo3 obj=new Demo3();
obj.add();
obj.sub();
obj.show();
}

interface Demo11
{
int a=10;
void add();
}

interface Demo12 extends Demo11


{
void sub();
}

class Demo13 implements Demo12


{
public void add()
{
System.out.println("add Overriding");
}

public void sub()


{
System.out.println("sub Overriding");
}

void show()
{
System.out.println("Hello Java : "+a);
}

public static void main(String [] args)


{
Demo13 obj=new Demo13();
obj.show();
obj.add();
obj.sub();
}

}
abstract class DemoAbstract
{
int a,b;

float f;

abstract public void add();

abstract public void sub();

public void mul()


{
System.out.println("Mul");
}
}

class DemoSub1 extends DemoAbstract


{
public void sub()
{
System.out.println("sub");
}
public void add()
{
System.out.println("add");
}
void show()
{
System.out.println("Hello Java");
}
public static void main(String [] args)
{
DemoSub1 obj=new DemoSub1();
obj.show();
obj.add();
obj.sub();
obj.mul();
}
}

import static java.lang.Math.*;


class MyStaticImport
{
public static void main(String[] args)
{
int a=10;
int b=20;
System.out.println("round = "+round(10.23));
System.out.println("min = "+min(10,25));
}
}
Chapter 04 : Multithreading and Exception Handling

class MultiThreading extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
MultiThreading t1=new MultiThreading();
t1.start();
}
}

class MyFirstThread extends Thread


{
public void run()
{
try
{
Thread t=Thread.currentThread();
System.out.println(t);
for (int i=0;i<=10 ;i++ )
{
System.out.println("First Thread Running....."+i);
Thread.sleep(10000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
MyFirstThread t1=new MyFirstThread();
t1.start();
}
}

class MainThread
{
public static void main(String[] args)
{
Thread t=Thread.currentThread();
String st=t.getName();
System.out.println("Name of thread is : "+t);
System.out.println(st);
}
}
class ChildMain extends Thread
{
public void run()
{
try{
for(int i=1;i<=50;i++)
{
System.out.println("i : "+i);
Thread.sleep(1000);
}
}catch(Exception e){
}
}
public static void main(String[] args)
{
ChildMain t1=new ChildMain();
t1.start();
try{
for(int j=100;j>=50;j--)
{
System.out.println("j : "+j);
Thread.sleep(500);
}
}catch(Exception e){
}
System.out.println("Last statement of main thread.....");
}
}

class MySecondThread extends Thread


{
public void run()
{
String tname=Thread.currentThread().getName();
if(tname.equals("one"))
{
try
{
for (int i=0;i<=10 ;i++ )
{
System.out.println("First Thread Running....."+i);
Thread.sleep(5000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
try
{
for (int i=0;i<=10 ;i++ )
{
System.out.println("Second Thread Running....."+i);
Thread.sleep(5000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
MySecondThread t1=new MySecondThread();
t1.setName("one");

MySecondThread t2=new MySecondThread();


t2.setName("two");

t1.start();
t2.start();
}
}

class OneToFiveTable extends Thread


{
public void one()
{
try
{
for (int i=1;i<=10;i++ )
{
System.out.println("One : "+(i*1));
Thread.sleep(5000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

public void two()


{
try
{
for (int i=1;i<=10;i++ )
{
System.out.println("Two : "+(i*2));
Thread.sleep(5000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

public void three()


{
try
{
for (int i=1;i<=10;i++ )
{
System.out.println("Three : "+(i*3));
Thread.sleep(5000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

public void four()


{
try
{
for (int i=1;i<=10;i++ )
{
System.out.println("Four : "+(i*4));
Thread.sleep(5000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

public void five()


{
try
{
for (int i=1;i<=10;i++ )
{
System.out.println("Five : "+(i*5));
Thread.sleep(5000);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

public void run()


{
String tname=Thread.currentThread().getName();
if(tname.equals("one"))
{
one();
}
else if(tname.equals("two"))
{
two();
}
else if(tname.equals("three"))
{
three();
}
else if(tname.equals("four"))
{
four();
}
else
{
five();
}
}

public static void main(String[] args)


{
OneToFiveTable t1=new OneToFiveTable();
OneToFiveTable t2=new OneToFiveTable();
OneToFiveTable t3=new OneToFiveTable();
OneToFiveTable t4=new OneToFiveTable();
OneToFiveTable t5=new OneToFiveTable();

t1.setName("one");
t2.setName("two");
t3.setName("three");
t4.setName("four");
t5.setName("five");

t1.setPriority(1);
t2.setPriority(4);
t3.setPriority(6);
t4.setPriority(8);
t5.setPriority(10);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}

class MySuper
{
public void demo()
{
System.out.println("I am super class");
}
}

class MyRunnableThread extends MySuper


implements Runnable
{
public void run()
{
String tname=Thread.currentThread().getName();
if(tname.equals("str1"))
{
try
{
String s1="govt. poly.";
System.out.println("Thread : "+tname);
Thread.sleep(1000);
System.out.println("Upper Case : "+s1.toUpperCase());
}
catch (Exception e)
{
System.out.println(e);
}
}
else if(tname.equals("str2"))
{
try
{
String s2="GPNASHIK";
System.out.println("Thread : "+tname);
Thread.sleep(1000);
System.out.println("Lower Case : "+s2.toLowerCase());
}
catch (Exception e)
{
System.out.println(e);
}
}
else
{
try
{
String s3="govt. poly. nashik";
System.out.println("Thread : "+tname);
Thread.sleep(1000);
demo();
System.out.println("Substring : "+s3.substring(6));
}
catch (Exception e)
{
System.out.println(e);
}
}
}

public static void main(String [] args)


{
MyRunnableThread r1=new MyRunnableThread();
MyRunnableThread r2=new MyRunnableThread();
MyRunnableThread r3=new MyRunnableThread();

Thread t1=new Thread(r1);


Thread t2=new Thread(r2);
Thread t3=new Thread(r3);

t1.setName("str1");
t2.setName("str2");
t3.setName("str3");

t1.start();
t2.start();
t3.start();
}
}

class Table
{
void printTable(int n) //method not synchronized
{
for(int i=1;i<=10;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(500);
}catch(Exception e){
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}

class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table(); //only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

class Table1
{
synchronized void printTable1(int n) //method synchronized
{
for(int i=1;i<=10;i++)
{
System.out.println(n*i);

try
{
Thread.sleep(400);
}catch(Exception e){
System.out.println(e);
}
}
}
}

class MyThread11 extends Thread


{
Table1 t;
MyThread11(Table1 t)
{
this.t=t;
}
public void run()
{
t.printTable1(5);
}
}

class MyThread22 extends Thread


{
Table1 t;
MyThread22(Table1 t)
{
this.t=t;
}
public void run()
{
t.printTable1(100);
}
}

class TestSynchronization12
{
public static void main(String args[])
{
Table1 obj = new Table1(); //only one object
MyThread11 t1=new MyThread11(obj);
MyThread22 t2=new MyThread22(obj);
t1.start();
t2.start();
}
}

class TestThread1 extends Thread{


public void run(){
try
{
for(int i=1;i<=50;i++)
{
System.out.println(i);
if(i==25)
{
Thread.sleep(1000);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String args[]) throws InterruptedException{
TestThread1 t1=new TestThread1();
t1.start();
Thread.sleep(5);
System.out.println("Main got a chance");
t1.interrupt();
}
}

class TestThread extends Thread


{
public void run(){
try
{
for(int i=1;i<=50;i++)
{
System.out.println(i);
if(i==25)
{
Thread.sleep(1000);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String args[]){
TestThread t1=new TestThread();
t1.start();
try
{
Thread.sleep(500);
}
catch (Exception e){}
System.out.println("In Main thread before stopping t1");
t1.stop();
System.out.println("In Main thread after stopping t1");
}
}
class MyRunnable implements Runnable{

@Override
public void run() {
System.out.println("Thread started:::"+Thread.currentThread().getName());
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread ended:::"+Thread.currentThread().getName());
}

public class ThreadJoinExample {

public static void main(String[] args) {


Thread t1 = new Thread(new MyRunnable(), "t1");
Thread t2 = new Thread(new MyRunnable(), "t2");
Thread t3 = new Thread(new MyRunnable(), "t3");

t1.start();

//start second thread after waiting for 2 seconds or if it's dead


try {
t1.join(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}

t2.start();

//start third thread only when first thread is dead


try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

t3.start();

//let all threads finish execution before finishing main thread


try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("All threads are dead, exiting main thread");
}

class MyIsAliveThread extends Thread


{
String name;

public void run()


{
try
{
name=Thread.currentThread().getName();
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}

public static void main(String[] args)


{
MyIsAliveThread t1=new MyIsAliveThread();
t1.setName("one");
MyIsAliveThread t2=new MyIsAliveThread();
t2.setName("two");
MyIsAliveThread t3=new MyIsAliveThread();
t3.setName("three");

t1.start();
t2.start();
t3.start();

System.out.println("Thread One is alive: "+ t1.isAlive());


System.out.println("Thread Two is alive: "+ t2.isAlive());
System.out.println("Thread Three is alive: "+t3.isAlive());

try
{
System.out.println("Waiting for threads to finish.");
t1.join();
t2.join();
t3.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}

System.out.println("Thread One is alive: "+ t1.isAlive());


System.out.println("Thread Two is alive: "+ t2.isAlive());
System.out.println("Thread Three is alive: "+ t3.isAlive());

System.out.println("Main thread exiting.");


}
}

class Customer
{
int amount=10000;

synchronized void withdraw(int amount)


{
System.out.println("going to withdraw...");

try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println(e);
}

if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
}
this.amount = this.amount - amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
try
{
Thread.sleep(2000);
}
catch (Exception e)
{
System.out.println(e);
}
this.amount = this.amount+amount;
System.out.println("deposit completed... ");
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println(e);
}
notify();
}
}

class CheckThread extends Thread


{
Customer c;

CheckThread(Customer c,String name)


{
super(name);
this.c=c;
}

public void run()


{
String tname=Thread.currentThread().getName();
if (tname.equals("t1"))
{
c.withdraw(15000);
}
else
{
c.deposit(10000);
}
}
}
class TestWait
{
public static void main(String args[])
{
Customer c=new Customer();
CheckThread t1=new CheckThread(c,"t1");
CheckThread t2=new CheckThread(c,"t2");
t1.start();
t2.start();
}
}
class MyYieldThread extends Thread
{
public void run()
{
try
{
System.out.println(Thread.currentThread().getName()+ " started");
for (int i=0; i<5 ; i++)
{
System.out.println(Thread.currentThread().getName()+ " in control");
Thread.sleep(100);
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("Exiting "+Thread.currentThread().getName());
}
}

// Driver Class
public class YieldDemo
{
public static void main(String[]args)
{
System.out.println(Thread.currentThread().getName()+ " started");
MyYieldThread t = new MyYieldThread();
t.setName("t1");
t.setPriority(Thread.MAX_PRIORITY);
t.start();

for (int i=0; i<2; i++)


{
// After execution of child Thread
// main thread takes over
System.out.println(Thread.currentThread().getName()+ " in control");
Thread.sleep(500);
}
// Control passes to child thread
Thread.yield();
System.out.println("Exiting Main");
}
}

Exception Handling :

class DemoException1
{
public static void main(String[] args)
{
int a=10,b=0;

int c=a/b;

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

class DemoException2
{
public static void main(String[] args)
{
int a[]=new int[5];

a[8]=20;

System.out.println("a[8] = "+a[8]);
}
}

import java.io.*;

class DemoException3
{
public static void main(String[] args)
{
String str;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

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


str = br.readLine();

System.out.println("string is : "+str);

}
}

class DemoException4 extends Thread


{
public void run()
{
System.out.println("Thread is running...");
Thread.sleep(500);
}
public static void main(String[] args)
{
DemoException4 t1=new DemoException4();
t1.start();
}
}
class DemoException
{
public static void main(String[] args)
{
System.out.println("Welcome");

try
{
A o=new A();
o.show();
}
catch(NoClassDefFoundError e)
{
System.out.println("class not found");
}

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

import java.io.*;
class ExceptionDemo3
{
String name;

void accept()throws IOException


{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Name : ");
name=br.readLine();
}

void show()
{
try
{
accept();
}
catch (Exception e)
{
System.out.println(e);
}
System.out.println("name = "+name);
}

public static void main(String[] args)


{
ExceptionDemo3 obj=new ExceptionDemo3();
obj.show();
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

class Simple1
{
void show()
{
System.out.println("Hi how r u?");
}
}

class ExceptionDemo
{
void demo()
{
int a=0,b=0;
float c=0.0f;
int arr[]=new int[5];

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

try
{
System.out.println("Enter a : ");
a = Integer.parseInt(br.readLine());
System.out.println("Enter b : ");
b = Integer.parseInt(br.readLine());
}
catch (IOException ioe)
{
System.out.println(ioe);
}
finally
{
System.out.println("finally of first try");
}

try
{
c=a/b;

arr[1]=50;

Simple1 obj=new Simple1();

obj=null;

obj.show();
}
catch (ArithmeticException ae)
{
System.out.println(ae);
}
catch (ArrayIndexOutOfBoundsException obe)
{
System.out.println(obe);
}
catch (Exception e)
{
System.out.println(e);
}
finally
{
System.out.println("finally of second try");
}

System.out.println("division is : "+c);
}
public static void main(String[] args)
{
ExceptionDemo obj=new ExceptionDemo();
obj.demo();
}
}

import java.util.Scanner;

class ExceptionDemo2
{
int age;

void accept()
{
Scanner sc=new Scanner(System.in);

try
{
System.out.println("Enter age : ");
age = sc.nextInt();

if (age > 25)


{
throw new InterruptedException("invalid age, please enter less than 25");
}
else
{
System.out.println("age is : "+age);
}
}
catch (InterruptedException ie)
{
System.out.println(ie);
}
}

public static void main(String[] args)


{
ExceptionDemo2 obj=new ExceptionDemo2();
obj.accept();
}
}

class InvalidAgeException extends Exception


{
InvalidAgeException(String s)
{
super(s);
}
}

class TestCustomException1
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid, please enter age greater than 18");
else
System.out.println("welcome to vote");
}

public static void main(String args[])


{
try
{
validate(17);
}

catch(Exception m)
{
System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}
Applet & Graphics

import java.applet.*;
import java.awt.*;
/* <applet code="AppLife.class" width="200" height="200"> </applet> */

public class AppLife extends Applet


{
String msg="The currently executing method :: ";

public void init(){


msg+=" init()";
Font f=new Font("Tahoma",Font.BOLD,18);
setFont(f);
}

public void start(){


msg+=" start()";
}

public void stop(){


msg+=" stop()";
}

public void paint(Graphics g){


g.drawString(msg,100,100);
showStatus("Test applet");
}

public void destroy(){


msg = null;
}
}
import java.applet.*;
import java.awt.*;
/* <applet code="AppLife1.class" width="500" height="500"> </applet> */
public class AppLife1 extends Applet
{
public void paint(Graphics g){
g.setColor(Color.PINK);
g.fillRect(100,100,300,200);
g.setColor(Color.BLUE);
g.fillOval(150,150,100,100);
}
}
import java.applet.*;
import java.awt.*;
/* <applet code="AppLife2.class" width="500" height="500">

<param name="p1" value="GPN"></param>


<param name="p2" value="KKW"></param>
<param name="p3" value="MVP"></param>

</applet> */

public class AppLife2 extends Applet


{
String m1,m2,m3;

public void init()


{
m1=getParameter("p1");
m2=getParameter("p2");
m3=getParameter("p3");
}

public void paint(Graphics g){

g.setColor(Color.RED);
g.drawString(m1,100,100);

g.setColor(Color.RED);
g.drawString(m2,150,100);

g.setColor(Color.RED);
g.drawString(m3,200,100);
}
}
import java.applet.*;
import java.awt.*;

/* <applet code="AppLife3.class" width="500" height="500">

<param name="p1" value="140"></param>


<param name="p2" value="215"></param>
<param name="p3" value="96"></param>

</applet> */

public class AppLife3 extends Applet


{
int m1,m2,m3;

public void init()


{
m1=Integer.parseInt(getParameter("p1"));
m2=Integer.parseInt(getParameter("p2"));
m3=Integer.parseInt(getParameter("p3"));
Color c1=new Color(m1,m2,m3);
Color c2=new Color(0.5f,0.78f,0.45f);

setForeground(c1);
setBackground(Color.BLACK);

Font f=new Font("Times New Roman",Font.BOLD,44);


setFont(f);
}

public void paint(Graphics g){

g.drawString("Welcome to GPN",50,50);

g.fillArc(50,100,300,250,90,270);

}
}
import java.awt.*;
class AppLife4
{
public static void main(String[] args)
{
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();

String fonts[]=ge.getAvailableFontFamilyNames();

for (String f : fonts)


{
System.out.println(f);
}
}
}
import java.applet.*;
import java.awt.*;

/* <applet code="AppLife5.class" width="500" height="500">


</applet> */

public class AppLife5 extends Applet


{
public void init()
{
Font f=new Font("Times New Roman",Font.PLAIN,44);
setFont(f);
}

public void paint(Graphics g){

g.drawString("Welcome to GPN",50,50);
Font f=g.getFont();

int i=f.getStyle();

g.drawString(Integer.toString(i),50,150);

}
}
import java.applet.*;
import java.awt.*;

/* <applet code="AppLife6.class" width="500" height="500">


</applet> */

public class AppLife6 extends Applet


{
public void paint(Graphics g){

Font f=new Font("consolas",Font.BOLD,44);


g.setFont(f);

g.drawString("Welcome to GPN",50,50);

}
}
import java.applet.*;
import java.awt.*;

/* <applet code="AppLife7.class" width="700" height="500">


</applet> */

public class AppLife7 extends Applet


{
public void init()
{
setLayout(null);

Label l1=new Label("Roll Number");


l1.setBounds(50,50,150,30);
add(l1);

TextField t1=new TextField();


t1.setBounds(210,50,150,30);
add(t1);

Label l2=new Label("Enter Name");


l2.setBounds(50,100,150,30);
add(l2);

TextField t2=new TextField();


t2.setBounds(210,100,150,30);
add(t2);
Label l3=new Label("Enter Branch");
l3.setBounds(50,150,150,30);
add(l3);

TextField t3=new TextField();


t3.setBounds(210,150,150,30);
add(t3);

Button b1=new Button("SAVE");


b1.setBounds(210,200,74,30);
add(b1);

Button b2=new Button("EXIT");


b2.setBounds(288,200,70,30);
add(b2);
}
}
import java.applet.*;
import java.awt.*;

/* <applet code="AppLife8.class" width="700" height="500">


</applet> */

public class AppLife8 extends Applet


{
public void init()
{
setLayout(null);

Font f=new Font("Tahoma",Font.BOLD,24);


setFont(f);

Label l1=new Label("Roll Number");


l1.setBounds(50,50,150,30);
add(l1);

TextField t1=new TextField();


t1.setBounds(210,50,150,30);
add(t1);

Label l2=new Label("Enter Name");


l2.setBounds(50,100,150,30);
add(l2);

TextField t2=new TextField();


t2.setBounds(210,100,150,30);
add(t2);

Label l3=new Label("Enter Branch");


l3.setBounds(50,150,150,30);
add(l3);
TextField t3=new TextField();
t3.setBounds(210,150,150,30);
add(t3);

Button b1=new Button("SAVE");


b1.setBounds(210,200,74,30);
add(b1);

Button b2=new Button("EXIT");


b2.setBounds(288,200,70,30);
add(b2);
}
}
import java.applet.*;
import java.awt.*;

/* <applet code="AppLife9.class" width="700" height="500">


</applet> */

public class AppLife9 extends Applet


{
public void init()
{
setLayout(null);

Font f=new Font("Tahoma",Font.BOLD,24);


setFont(f);

Color c1=new Color(10,254,26);


setBackground(c1);

Color c2=new Color(240,17,196);


setForeground(c2);

Label l1=new Label("Roll Number");


l1.setBounds(50,50,150,30);
add(l1);

TextField t1=new TextField();


t1.setBounds(210,50,150,30);
add(t1);

Label l2=new Label("Enter Name");


l2.setBounds(50,100,150,30);
add(l2);

TextField t2=new TextField();


t2.setBounds(210,100,150,30);
add(t2);

Label l3=new Label("Enter Branch");


l3.setBounds(50,150,150,30);
add(l3);

TextField t3=new TextField();


t3.setBounds(210,150,150,30);
add(t3);

Button b1=new Button("SAVE");


b1.setBounds(210,200,74,30);
add(b1);

Button b2=new Button("EXIT");


b2.setBounds(288,200,70,30);
add(b2);
}
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/* <applet code="AppLife10.class" width="700" height="500">


</applet> */

public class AppLife10 extends Applet implements ActionListener


{
public void init()
{
setLayout(null);

Font f=new Font("Tahoma",Font.BOLD,24);


setFont(f);

Color c1=new Color(10,254,26);


setBackground(c1);

Color c2=new Color(240,17,196);


setForeground(c2);

Label l1=new Label("Roll Number");


l1.setBounds(50,50,150,30);
add(l1);

TextField t1=new TextField();


t1.setBounds(210,50,150,30);
add(t1);

Label l2=new Label("Enter Name");


l2.setBounds(50,100,150,30);
add(l2);

TextField t2=new TextField();


t2.setBounds(210,100,150,30);
add(t2);

Label l3=new Label("Enter Branch");


l3.setBounds(50,150,150,30);
add(l3);

TextField t3=new TextField();


t3.setBounds(210,150,150,30);
add(t3);

Button b1=new Button("SAVE");


b1.setBounds(210,200,74,30);
b1.addActionListener(this);
b1.setActionCommand("b1");
add(b1);

Button b2=new Button("EXIT");


b2.setBounds(288,200,70,30);
b2.addActionListener(this);
b2.setActionCommand("b2");
add(b2);
}

public void actionPerformed(ActionEvent ae)


{
Button b=(Button)ae.getSource();
String s=b.getActionCommand().toString();
if (s.equals("b1"))
{
}
else
{
//System.exit(0);
}
}
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/* <applet code="AppLife11.class" width="700" height="500">


</applet> */

public class AppLife11 extends Applet implements ActionListener


{
String msg="";
public void init()
{
setLayout(null);

Font f=new Font("Tahoma",Font.BOLD,24);


setFont(f);
Color c1=new Color(10,254,26);
setBackground(c1);

Color c2=new Color(240,17,196);


setForeground(c2);

Label l1=new Label("Roll Number");


l1.setBounds(50,50,150,30);
add(l1);

TextField t1=new TextField();


t1.setBounds(210,50,150,30);
add(t1);

Label l2=new Label("Enter Name");


l2.setBounds(50,100,150,30);
add(l2);

TextField t2=new TextField();


t2.setBounds(210,100,150,30);
add(t2);

Label l3=new Label("Enter Branch");


l3.setBounds(50,150,150,30);
add(l3);

TextField t3=new TextField();


t3.setBounds(210,150,150,30);
add(t3);

Button b1=new Button("SAVE");


b1.setBounds(210,200,74,30);
b1.addActionListener(this);
b1.setActionCommand("b1");
add(b1);

Button b2=new Button("EXIT");


b2.setBounds(288,200,70,30);
b2.addActionListener(this);
b2.setActionCommand("b2");
add(b2);
}

public void actionPerformed(ActionEvent ae)


{
Button b=(Button)ae.getSource();
String s=b.getActionCommand().toString();
if (s.equals("b1"))
{
}
else
{
//System.exit(0);
msg="Exit Button was Pressed...";
repaint();
}
}

public void paint(Graphics g)


{
g.drawString(msg,300,350);
}
}

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/* <applet code="AppLife12.class" width="700" height="500">


</applet> */

public class AppLife12 extends Applet implements ActionListener


{
Label msg;
public void init()
{
setLayout(null);

Font f=new Font("Tahoma",Font.BOLD,24);


setFont(f);

Color c1=new Color(10,254,26);


setBackground(c1);

Color c2=new Color(240,17,196);


setForeground(c2);

Label l1=new Label("Roll Number");


l1.setBounds(50,50,150,30);
add(l1);

TextField t1=new TextField();


t1.setBounds(210,50,150,30);
add(t1);

Label l2=new Label("Enter Name");


l2.setBounds(50,100,150,30);
add(l2);

TextField t2=new TextField();


t2.setBounds(210,100,150,30);
add(t2);
Label l3=new Label("Enter Branch");
l3.setBounds(50,150,150,30);
add(l3);

TextField t3=new TextField();


t3.setBounds(210,150,150,30);
add(t3);

Button b1=new Button("SAVE");


b1.setBounds(210,200,74,30);
b1.addActionListener(this);
b1.setActionCommand("b1");
add(b1);

Button b2=new Button("EXIT");


b2.setBounds(288,200,70,30);
b2.addActionListener(this);
b2.setActionCommand("b2");
add(b2);

msg=new Label();
msg.setBounds(50,350,300,40);
add(msg);
}

public void actionPerformed(ActionEvent ae)


{
Button b=(Button)ae.getSource();
String s=b.getActionCommand().toString();
if (s.equals("b1"))
{
msg.setText("Save button was pressed...");
}
else
{
msg.setText("Exit button was pressed...");
}
}
}
import java.applet.*;
import java.awt.*;

/* <applet code="AppLife13.class" width="500" height="500">


</applet> */

public class AppLife13 extends Applet


{
public void paint(Graphics g){

g.drawString("Welcome to GPN",50,450);

int noofpts=5;
int x[]={100,200,300,250,150};
int y[]={100,50,100,250,250};

g.fillPolygon(x,y,noofpts);

I/O & Collections

import java.io.*;

class TestFileOutputStream
{
public static void main(String args[])
{
try{
FileOutputStream fout=new FileOutputStream("File_01.txt");

String s="Sachin Pawar is a student of GPN.";

//converting string into byte array


byte b[]=s.getBytes();

fout.write(s);

fout.close();

System.out.println("success...");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

import java.io.*;

class TestFileInputStream
{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream("File_01.txt");

int i=0;
while((i=fin.read())!=-1)
{
System.out.print((char)i);
}

fin.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
import java.io.*;

public class TestDataIOStream{

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

double d=458976.256;

DataOutputStream dataOut;
dataOut = new DataOutputStream(new FileOutputStream("File_03.txt"));
dataOut.writeDouble(d);
dataOut.writeUTF("Hello java");

System.in.read();

DataInputStream dataIn;
dataIn = new DataInputStream(new FileInputStream("File_03.txt"));

while(dataIn.available()>0){
double d1 = dataIn.readDouble();
System.out.print(d1+" ");
}
}
}
import java.io.*;

class TestFileWriter
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("File_02.txt");
fw.write("my name is sachin");
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("success");
}
}
import java.io.*;

class TestFileReader
{
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader("File_02.txt");

int i;

while((i=fr.read())!= -1)
{
System.out.print((char)i);
}

fr.close();
}
}
import java.io.File;

public class MyFileOperations {

public static void main(String[] a){

try{
File file = new File("utility");
System.in.read();
//Tests whether the application can read the file
System.out.println(file.canRead());
//Tests whether the application can modify the file
System.out.println(file.canWrite());
//Tests whether the application can modify the file
int ch=System.in.read();
System.out.println(file.createNewFile());
int ch1=System.in.read();
//Deletes the file or directory
System.out.println(file.delete());
//Tests whether the file or directory exists.
System.out.println(file.exists());
//Returns the absolute pathname string.
System.out.println(file.getAbsolutePath());
//Tests whether the file is a directory or not.
System.out.println(file.isDirectory());
//Tests whether the file is a hidden file or not.
System.out.println(file.isHidden());
//Returns an array of strings naming the
//files and directories in the directory.
System.out.println(file.list());
}
catch(Exception ex){}
}
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample


{
public static void main(String[] args)
{
try {
String content = "This is the content to write into file";
File file = new File("File_04.txt");

if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
class StudentInfo implements Serializable
{
String name;
int rid;
static String contact;

public StudentInfo(String n, int r, String c){


this.name = n;
this.rid = r;
contact = c;
}
}

class TestSerialization
{
public static void main(String[] args)
{
try{
StudentInfo si = new StudentInfo("Abhi", 104, "110044");
FileOutputStream fos = new FileOutputStream("student.txt");
System.in.read();
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(si);
oos.close();
fos.close();
}catch (Exception e){
e. printStackTrace();
}
}
}
import java.io.* ;
class TestDeserialization
{
public static void main(String[] args)
{
StudentInfo si=null ;
try{
FileInputStream fis = new FileInputStream("student.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
si = (StudentInfo)ois.readObject();
}catch (Exception e){
e.printStackTrace();
}
System.out.println(si.name);
System.out. println(si.rid);
System.out.println(si.contact);
}
}

Utility Classes

import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}
import java.util.*;

public class DateDemo


{
public static void main(String[] args)
{
Date mydate = new Date();

System.out.println("System date : "+ mydate.toString() );

mydate.setTime(15680);

System.out.println("Time after setting: " + mydate.toString());

int d = mydate.hashCode();
System.out.println("Amount (in ms) by which time is shifted : " + d);

Date date1 = new Date(2016, 11, 18);


Date date2 = new Date(1997, 10, 27);

boolean a = date2.after(date1);
System.out.println("Is date2 is after date1 : " + a);

a = date1.after(date2);
System.out.println("Is date1 is after date2 : " + a);
System.out.println("");

Object date3 = date1.clone();


System.out.println("Cloned date3 :" + date3.toString());
System.out.println("");
boolean b = date2.before(date1);
System.out.println("Is date2 is before date1 : " + a);
}
}
import java.util.Random;
public class RandomNumberExample {

public static void main(String[] args) {

//initialize random number generator


Random random = new Random();

//generates boolean value


System.out.println(random.nextBoolean());

//generates double value


System.out.println(random.nextDouble());

//generates float value


System.out.println(random.nextFloat());

//generates int value


System.out.println(random.nextInt());

//generates int value within specific limit


System.out.println(random.nextInt(20));
}
}
Collection Classes

import java.io.*;
import java.util.*;

class arraylist
{
public static void main(String[] args)
throws IOException
{
// size of ArrayList
int n = 5;

//declaring ArrayList with initial size n


ArrayList<Integer> arrli = new ArrayList<Integer>(n);

// Appending the new element at the end of the list


for (int i=1; i<=n; i++)
arrli.add(i);

// Printing elements
System.out.println(arrli);

// Remove element at index 3


arrli.remove(3);

// Displaying ArrayList after deletion


System.out.println(arrli);

// Printing elements one by one


for (int i=0; i<arrli.size(); i++)
System.out.print(arrli.get(i)+" ");
}
}
import java.util.*;

public class LinkedListTest


{
public static void main(String args[])
{
// Creating object of class linked list
LinkedList<String> object = new LinkedList<String>();

// Adding elements to the linked list


object.add("A");
object.add("B");
object.addLast("C");
object.addFirst("D");
object.add(2, "E");
object.add("F");
object.add("G");
System.out.println("Linked list : " + object);

// Removing elements from the linked list


object.remove("B");
object.remove(3);
object.removeFirst();
object.removeLast();
System.out.println("Linked list after deletion: " + object);

// Finding elements in the linked list


boolean status = object.contains("E");

if(status)
System.out.println("List contains the element 'E' ");
else
System.out.println("List doesn't contain the element 'E'");

// Number of elements in the linked list


int size = object.size();
System.out.println("Size of linked list = " + size);

// Get and set elements from linked list


Object element = object.get(2);
System.out.println("Element returned by get() : " + element);
object.set(2, "Y");
System.out.println("Linked list after change : " + object);
}
}
import java.util.*;

class HashSetTest
{
public static void main(String[]args)
{
HashSet h = new HashSet();

// Adding elements into HashSet usind add()


h.add("India");
h.add("Australia");
h.add("South Africa");
h.add("India");// adding duplicate elements

// Displaying the HashSet


System.out.println(h);
System.out.println("List contains India or not:" +
h.contains("India"));

// Removing items from HashSet using remove()


h.remove("Australia");
System.out.println("List after removing Australia:"+h);

// Iterating over hash set items


System.out.println("Iterating over list:");
Iterator i = h.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}
import java.util.*;

class TreeSetDemo
{
public static void main (String[] args)
{
TreeSet<String> ts1= new TreeSet<String>();

// Elements are added using add() method


ts1.add("A");
ts1.add("B");
ts1.add("C");

// Duplicates will not get insert


ts1.add("C");

// Elements get stored in default natural


// Sorting Order(Ascending)
System.out.println(ts1);
}
}
import java.util.*;
class LinkedHashSetDemo
{
public static void main(String args[])
{
LinkedHashSet< String> hs = new LinkedHashSet< String>();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
import java.util.*;

class PriorityQueueDemo
{
public static void main(String args[])
{
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("WE");
queue.add("LOVE");
queue.add("STUDY");
queue.add("TONIGHT");
System.out.println("At head of the queue:"+queue.element());
System.out.println("At head of the queue:"+queue.peek());
System.out.println("Iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("After removing two elements:");
Iterator itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
import java.util.*;
class HashMapDemo
{
public static void main(String args[])
{
HashMap< String,Integer> hm = new HashMap< String,Integer>();
hm.put("a",new Integer(100));
hm.put("b",new Integer(200));
hm.put("c",new Integer(300));
hm.put("d",new Integer(400));

Set< Map.Entry< String,Integer> > st = hm.entrySet(); //returns Set view


for(Map.Entry< String,Integer> me:st)
{
System.out.print(me.getKey()+":");
System.out.println(me.getValue());
}
}
}
import java.util.*;
class TreeMapDemo
{
public static void main(String args[]) {
TreeMap< String,Integer> tm = new TreeMap< String,Integer>();
tm.put("a",new Integer(100));
tm.put("b",new Integer(200));
tm.put("c",new Integer(300));
tm.put("d",new Integer(400));
Set< Map.Entry< String,Integer> > st = tm.entrySet();
for(Map.Entry me:st) {
System.out.print(me.getKey()+":");
System.out.println(me.getValue());
}
}
}
import java.util.*;
class HashTableDemo
{
public static void main(String args[])
{
Hashtable< String,Integer> ht = new Hashtable< String,Integer>();
ht.put("a",new Integer(100));
ht.put("b",new Integer(200));
ht.put("c",new Integer(200));
ht.put("d",new Integer(100));

Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
{
Map.Entry m=(Map.Entry)itr.next();
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

***** Nikita Education – Best of Luck *****

You might also like