Java OOP Concepts and Programming Examples
Java OOP Concepts and Programming Examples
Java version:
100 -> 1.1 -> 1.8 are versions of java.
The Editions of java:
J2SE : Java2 platform, Standard Edition.
J2EE : Java2 platform, Enterprise Edition
J2ME : Java2 platform, Micro Edition.
Java is a Platform Independent.
Java Compiler
Java Class File
Java Interpreter
Machine Code
ARRAYS
ONE DIMENSIONAL ARRAY – ASCENDING ORDER
import [Link].*;
class onearray
{
public static void main(String ar[])throws IOException
{
int n=5,t,i,j;
int a[]=new int[5];
DataInputStream d=new DataInputStream([Link]);
[Link]("Enter 5 values:");
for(i=0;i<n;i++)
{
a[i]=[Link]([Link]());
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
[Link]("Ascending order is:");
for(i=0;i<n;i++)
{
[Link](a[i]);
}
}
}
}
[Link]("Enter B matrix:");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
b[i][j]=[Link]([Link]());
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
s[i][j]=0;
for(int k=0;k<r;k++)
{
s[i][j]=s[i][j]+(a[i][k]*b[k][j]);
}
}
}
[Link]("Multiplication of the matrix:");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
[Link]("\t"+s[i][j]);
}
[Link]();
}
}
}
Rectangle(inta,int b)
{
length=a; width=b;
}
void Area()
{
int area=length*width;
[Link](“Area of rectangle(2,4)="+area);
}
void Perimeter()
{
int perimeter=2*(length+width);
[Link]("Perimeter of
rectangle(3,5)="+perimeter);
}
}
classClassDemo
{
public static void main(String arg[])
{
Rectangle o=new Rectangle(2,4);
[Link]();
[Link]();
Rectangle o1=new Rectangle(3,5);
[Link]();
[Link]();
}
}
MULTIPLE NOTEPAD
CLASS PROGRAM:
public class RevPalin
{
public void reverse(int x)
{
int n=x;
int s=0;
int t=n;
do
{
int r=n%10;
s=s*10+r;
n=n/10;
}while(n>0);
[Link]("Rev is"+s);
palindrome(t,s);
}
public void palindrome(intt,int s)
{
if(s==t)
{
[Link]("Palindrome no");
}
else
{
[Link]("Not palindrome no");
}
}
}
MAIN PROGRAM:
classRPMain
{
public static void main(String arg[])
{
RevPalinob=new RevPalin();
int n=121;
[Link](n);
}
}
COPY CONSTRUCTOR
import [Link].*;
class cons
{
inta,b;
cons()
{
a=5;b=5;
}
cons(inta,int b)
{
this.a=a;
this.b=b;
}
cons(cons obj)
{
a=obj.a;
b=obj.b;
}
void dis()
{
[Link]("Sum of"+a+"and"+b+"is="+(a+b));
}
}
classCopyCons
{
public static void main(String arg[])throws IOException
{
[Link]("Empty constuctor:");
cons o1=new cons();
[Link]();
[Link]("Getting the value cons:");
cons o2=new cons(10,20);
[Link]();
[Link]("Using Copy cons:");
cons o3=new cons(o1);
[Link]();
}
}
intcal()
{
int s=0;
do
{
int r=n%10;
s=s+(r*r*r);
n=n/10;
}while(n>0);
return(s);
}
}
classAmstrongThis
{
public static void main(String arg[])
{
int n=152;
Ams o=new Ams(n);
if(n==[Link]())
{
[Link]("Amstrong no");
}
else
{
[Link]("Not Amstrong no");
}
}
}
INHERITANCE
SINGLE INHERITANCE – ASCENDING ORDER
import [Link].*;
class a
{
inti,j,n=5;
int c[]=new int[5];
BufferedReader d=new BufferedReader(new
InputStreamReader([Link]));
void get()throws IOException
{
[Link]("Enter the values:");
for(i=0;i<n;i++)
{
c[i]=[Link]([Link]());
}
}
}
class b extends a
{
voidcal()
{
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(c[i]>c[j])
{
int t=c[i];
c[i]=c[j];
c[j]=t;
}
}
}
[Link]("Ascending order is:");
for(i=0;i<n;i++)
{
[Link](c[i]);
}
}
}
classSingleInheritance
{
public static void main(String arg[])throws IOException
{
b o1=new b();
[Link]();
[Link]();
}
}
HIRARCHICAL INHERITANCE
import [Link].*;
class a
{
int n;
DataInputStream d=new DataInputStream([Link]);
public void get()throws IOException
{
[Link]("Enter N value:");
n=[Link]([Link]());
}
}
class b extends a
{
int i,f,f1=-1,f2=1,s=0;
void fib()
{
for(i=0;i<n;i++)
{
f=f1+f2;
s=s+f;
f1=f2;
f2=f;
}
[Link]("Fibonacci Series is="+s);
}
}
class c extends a
{
inti,f=1;
voidfac()
{
for(i=1;i<=n;i++)
{
f=f*i;
}
[Link]("Factorial is="+f);
}
}
classHyrarical
{
public static void main(String arg[])throws IOException
{
c o2=new c();
b o1=new b();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
ABSTRACT CLASSES
Abstract class:
A class for which we cannot create object is called extract class.
Interface:
An interface declares a set of method and their signatures. A
class can inherit the interface should provide definition to the method
inside the method.
Keyword:
“extends” is used when an interface inherit other one.
Keyword “implements” is used in a class inheritance interface.
Interface is used to create hybrid inheritance and hierarical
inheritance.
ABSTRACT INTERFACE
Abstract class can have abstract Interface can have only abstract
and non-abstract method. method.
Abstract class doesn’t support Interface supports multiple
multiple inheritances. inheritances.
Abstract class can have final Interface has only static and final
static and non-static variables. variables.
Abstract class can have static Interface can’t have static
methods main method and method main method or
constructor. constructor.
Abstract class can provide the Interface can provide the extends
implementation of interface. of abstract class.
Eg: Eg:
public abstract class shape public interface drawable
{ {
public abstract void draw(); void draw();
} }
The abstract keyword is used to The interface keyword is used to
declare abstract class. declare interface.
Example:
abstract class abs
{
abstract void addmul();
}
class add extends abs
{
voidaddmul()
{
int a=2;int b=3;
[Link]("Addition of"+a+"and"+b+"is ="+(a+b));
}
}
classmul extends abs
{
voidaddmul()
{
int a=2;int b=3;
[Link]("Multiplication of"+a+"and"+b+"is"+(a*b));
}
}
class Abstract
{
public static void main(String arg[])
{
add o1=new add();
mul o2=new mul();
[Link]();
[Link]();
}
}
TO FIND THE PERFECT SQUARE:
import [Link].*;
abstract class perfsq
{
abstract void cal()throws IOException;
}
class a extends perfsq
{
voidcal()throws IOException
{
DataInputStream d=new DataInputStream([Link]);
[Link]("Enter N1 value:");
int n1=[Link]([Link]());
[Link]("Enter N2 value:");
int n2=[Link]([Link]());
inti,j,f;
for(i=n1;i<n2;i++)
{
for(j=1;j<=i;j++)
{
f=j*j;
if(f==i)
{
[Link](i);
break;
}
}
}
}
}
classPerfectSquare
{
public static void main(String arg[])throws IOException
{
a o=new a();
[Link]();
}
}
INTERFACE
PRIME & PERFECT NO:
import [Link].*;
interface A
{
void cal1()throws IOException;
}
interface B
{
void cal2()throws IOException;
}
class prime implements A
{
public void cal1()throws IOException
{
DataInputStream d=new DataInputStream([Link]);
[Link]("Enter value for prime:");
int n1=[Link]([Link]());
int s=0;
for(int i=2;i<n1;i++)
{
if(n1%i==0)
{
s=1;
break;
}
}
if(s==0)
{
[Link]("It is prime no");
}
else
{
[Link]("Not prime no");
}
}
}
class perfect implements B
{
public void cal2()throws IOException
{
DataInputStream d=new DataInputStream([Link]);
[Link]("Enter value for perfect:");
int n2=[Link]([Link]());
int s=0;
for(int j=1;j<n2;j++)
{
if(n2%j==0)
{
s=s+j;
}
}
if(s==n2)
{
[Link]("It is perfect no");
}
else
{
[Link]("Not a perfect no");
}
}
}
classInterf_pripef
{
public static void main(String arg[])throws IOException
{
prime o1=new prime();
perfect o2=new perfect();
o1.cal1();
o2.cal2();
}
}
PACKAGE
[Link]:
package pack;
public class Class1
{
public static void great()
{
[Link]("Hello");
}
}
[Link]:
[Link];
public class Class2
{
public static void farewell()
{
[Link]("bye");
}
}
[Link]:
import pack.*;
[Link].*;
class Importer
{
public static void main(String arg[])
{
[Link]();
[Link]();
}
}
Output:
EXCEPTION HANDLING
PRE-DEFINED EXCEPTION:
import [Link].*;
classWithException
{
public static void main(String arg[])
{
DataInputStream d=new DataInputStream([Link]);
try
{
int x=[Link](arg[0]);
[Link]("Given no "+x);
int a[]=new int[x];
[Link]("Enter array values");
for(int i=0;i<x;i++)
{
a[i]=[Link]([Link]());
}
[Link]("Array values are:");
for(int i=0;i<x;i++)
{
[Link](a[i]);
}
}
catch(ArithmeticException ex)
{
[Link]("Error in Denominator");
}
catch(ArrayIndexOutOfBoundsException ex)
{
[Link]("U must pass value at run time");
}
catch(NumberFormatException ex)
{
[Link]("U must pass integer numbers");
}
catch(IOException ex)
{
[Link]("Error at input");
}
catch(NegativeArraySizeException ex)
{
[Link]("U must enter positive nos");
}
catch(Exception ex)
{
[Link]("ERROR:"+[Link]());
}
}
}
Output:
USER-DEFINED EXCEPTION:
import [Link].*;
class ManualExcep extends Exception
{
public String toString()
{
return "IllegalMark";
}
}
class mark
{
void get()
{
try
{
DataInputStream d=new DataInputStream([Link]);
[Link]("Enter Student name:");
String name=[Link]();
[Link]("Enter mark1=");
int m1=[Link]([Link]());
[Link]("Enter mark2=");
int m2=[Link]([Link]());
if((m1<0)||(m2<0))
{
throw new ManualExcep();
}
else if((m1>35)&&(m2>35))
{
[Link]("Pass");
}
else if((m1<35)&&(m2<35))
{
[Link]("Fail");
}
}
catch(ManualExcep ex)
{
[Link](ex);
}
catch(IOException ex)
{
[Link](ex);
}
finally
{
[Link]("Finally block execution");
}
}
}
classUserException
{
public static void main(String arg[])throws IOException
{
markob=new mark();
[Link]();
}
}
LOGIN PROCESS:
import [Link].*;
classLoginDetails extends Exception
{
public String toString()
{
return "Your password is mismatch to your Id";
}
}
class Login
{
voidcal()throws IOException
{
try
{
DataInputStream d=new DataInputStream([Link]);
[Link]("Enter your ID");
String a=[Link]();
[Link]("Enter your Password");
String b=[Link]();
StringBuffersb=new StringBuffer(b);
int l=[Link]();
if((l<5)||(l>15))
{
throw new LoginDetails();
}
else
{
[Link]("YOURLOGIN SUCCESS");
}
}
catch(LoginDetails ex)
{
[Link](ex);
}
}
}
classUserdefinedLogin
{
public static void main(String arg[])throws IOException
{
Login o1=new Login();
[Link]();
}
}
MULTI-THREADING
Multithreading:
Multithreading is a process of executing multiple threads
simultaneously.
Multithreading is mostly used in games, animation etc.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously.
We use multitasking to utilize the CPU. Multitasking can be achieved
by two ways:
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
Sleeping a thread
class Multi extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
[Link](1000);
}
catch(InterruptedException e)
{
[Link](e);
}
[Link](i);
}
}
public static void main(String args[])
{
Multi t1=new Multi();
Multi t2=new Multi();
[Link]();
[Link]();
}
}
Output:
1
1
2
2
3
3
4
4
5
5
run() method:
class Multi extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
[Link](500);
}
catch(InterruptedException e)
{
[Link](e);
}
[Link](i);
}
}
public static void main(String args[])
{
Multi t1=new Multi();
Multi t2=new Multi();
[Link]();
[Link]();
}
}
Output:
1
2
3
4
5
1
2
3
4
5
Output:
1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
lbldemo1()
{
setTitle("Example of TextField, Label,Button");
setVisible(true);
setSize(600,300);
setLayout(null);
t1=new TextField(25);
[Link](300,150,100,30);
add(t1);
t2=new TextField(25);
[Link](300,200,100,30);
add(t2);
t3=new TextField(25);
[Link](300,250,100,30);
add(t3);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
if([Link]()==b1)
{
i=[Link]([Link]());
j=[Link]([Link]());
k=i+j;
[Link]("Sum is"+k);
[Link]([Link](k));
}
if([Link]()==b2)
{
i=[Link]([Link]());
j=[Link]([Link]());
k=i-j;
[Link]("Differece is" +k);
[Link]([Link](k));
}
if([Link]()==b3)
{
i=[Link]([Link]());
j=[Link]([Link]());
k=i*j;
[Link]("Multiplication "+k);
[Link]([Link](k));
}
if([Link]()==b4)
{
i=[Link]([Link]());
j=[Link]([Link]());
k=i/j;
[Link]("Division is "+k);
[Link]([Link](k));
}
}
public static void main(String arg[])
{
new lbldemo1();
}
}
Output:
CHOICE:
[Link].*;
[Link].*;
classchoiceexam extends Frame implements
ActionListener,ItemListener
{
Label l1,l2;
TextArea A;
Choice C1;
Button B;
TextField tx1;
choiceexam(String s)
{
setTitle(s);
setVisible(true);
setSize(800,500);
setLayout(null);
l1=new Label("Address:");
[Link](50,50,70,20);
add(l1);
l2=new Label("Qualification:");
[Link](50,200,70,20);
add(l2);
B=new Button("Click");
[Link](100,300,50,20);
add(B);
[Link](this);
A=new
TextArea("",5,10,TextArea.SCROLLBARS_NONE);
[Link](150,50,150,60);
add(A);
C1=new Choice();
[Link]("MCA");
[Link]("[Link]");
[Link]("[Link](Computer)");
[Link]("[Link](I.T)");
[Link]("[Link](S.W)");
[Link]("B.E(ECE)");
[Link]("others");
[Link](this);
[Link](150,200,70,20);
add(C1);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if([Link]()==B)
{
String s="Qualification ::"+[Link]();
[Link](s);
}
}
public void itemStateChanged(ItemEventie)
{
[Link]("Hai");
}
public static void main(String arg[])
{
newchoiceexam("Choice and Text Area Demo");
}
}
OUTPUT:
GRID LAYOUT:
[Link].*;
[Link].*;
OUTPUT:
SCROLL BAR:
[Link].*;
[Link].*;
public class ScrollDemo extends Frame implements
AdjustmentListener
{
private Scrollbar sr,sg,sb;
privateTextArea ta;
private Label rl,gl,bl;
private Label rval,gval,bval;
ScrollDemo(String s)
{
setTitle(s);
setVisible(true);
setLayout(null);
setSize(600,800);
ta=new
TextArea("",5,50,TextArea.SCROLLBARS_NONE);
[Link](60,10,200,100);
add(ta);
rl=new Label("Red:",[Link]);
[Link](2,120,50,30);
add(rl);
sr=new Scrollbar([Link],0,1,0,255);
[Link](10);
[Link](60,120,200,30);
[Link](this);
add(sr);
rval=new Label();
[Link](270,120,30,30);
add(rval);
gl=new Label("Green:",[Link]);
[Link](2,150,50,30);
add(gl);
sg=new Scrollbar([Link],0,1,0,255);
[Link](10);
[Link](10);
[Link](60,150,200,30);
[Link](this);
add(sg);
gval=new Label();
[Link](270,150,30,30);
add(gval);
bl=new Label("Blue:",[Link]);
[Link](2,180,50,30);
add(bl);
sb=new Scrollbar([Link],0,1,0,255);
[Link](10);
[Link](10);
[Link](60,180,200,30);
[Link](this);
add(sb);
bval=new Label();
[Link](270,180,30,30);
add(bval);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
[Link]([Link]([Link]()));
[Link]([Link]([Link]()));
[Link]([Link]([Link]()));
[Link](new
Color([Link](),[Link](),[Link]()));
}
public static void main(String a[])
{
newScrollDemo("Scroll Application");
}
OUTPUT:
CHECKBOX:
[Link].*;
[Link].*;
classCheckboxexam extends Frame implements ItemListener
{
Checkbox Ch1,Ch2,Ch3,Ch4,Ch5;
Label l1,l2;
TextField t1,t2;
CheckboxGroup cg;
String gen="",lang="";
Checkboxexam(String s)
{
setTitle(s);
setVisible(true);
setSize(800,500);
setLayout(null);
l1=new Label("Gender");
l2=new Label("Languages known");
cg=new CheckboxGroup();
Ch1=new Checkbox("Male",cg,false);
Ch2=new Checkbox("Female",cg,false);
t1=new TextField(25);
Ch3=new Checkbox("Tamil");
Ch4=new Checkbox("English");
Ch5=new Checkbox("Hindi");
t2=new TextField(25);
[Link](100,100,100,30);
[Link](250,100,100,30);
[Link](350,100,100,30);
[Link](450,100,100,30);
[Link](100,200,100,30);
[Link](250,200,75,30);
[Link](325,200,75,30);
[Link](400,200,75,30);
[Link](475,200,100,30);
add(l1);
add(Ch1);
[Link](this);
add(Ch2);
[Link](this);
add(t1);
add(l2);
add(Ch3);
[Link](this);
add(Ch4);
add(Ch5);
add(t2);
[Link](this);
[Link](this);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
}
public void itemStateChanged(ItemEvent e)
{
lang="";
if([Link]()==Ch1)
gen=[Link]();
else if([Link]()==Ch2)
gen=[Link]();
[Link](gen);
[Link]("Ur Gender is:"+gen);
if(([Link]()==Ch3)||([Link]()==Ch4)||([Link]()==Ch5))
{
if([Link]())
{
lang+=[Link]();
}
if([Link]())
{
lang+=[Link]();
}
if([Link]())
{
lang+=[Link]();
}
[Link](lang);
Applets
Applet is a special type of program that is embedded in the webpage
to generate the dynamic content. It runs inside the browser and works
at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured
It can be executed by browsers running under many platforms,
including Linux, Windows, Mac Os etc.
Drawback of Applet
Plug-in is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel
class extends Container which is the subclass of Component.
Lifecycle of an Applet:
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Output:
Commonly used methods of Graphics class:
1. drawString(String str, int x, int y): is used to draw the
specified string.
2. drawRect(int x, int y, int width, int height): draws a rectangle
with the specified width and height.
3. fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
4. drawOval(int x, int y, int width, int height): is used to draw
oval with the specified width and height.
5. fillOval(int x, int y, int width, int height): is used to fill oval
with the default color and specified width and height.
6. drawLine(int x1, int y1, int x2, int y2): is used to draw line
etween the points(x1, y1) and (x2, y2).
7. drawImage(Image img, int x, int y,
ImageObserverobserver): is used draw the specified image.
8. drawArc(int x, int y, int width, int height, intstartAngle,
intarcAngle): is used draw a circular or elliptical arc.
9. fillArc(int x, int y, int width, int height, intstartAngle,
intarcAngle): is used to fill a circular or elliptical arc.
10. setColor(Color c): is used to set the graphics current color
to the specified color.
11. setFont(Font font): is used to set the graphics current font
to the specified font.
DIFFERENT SHAPES:
EXAMPLE:
[Link].*;
[Link].*;
Output:
HOUSEAPPLET :
[Link].*;
[Link].*;
[Link](200,300,100,150);
[Link](200,300,250,220);
[Link](250,220,300,300);
[Link](250,220,470,220);
[Link](470,220,530,300);
[Link](400,350,50,100);
[Link](230,255,35,35);
[Link](227,350,45,45);
[Link](250,350,250,395);
[Link](227,373,272,373);
}
}
Output:
Animation in Applet
Applet is mostly used in games and animation. For this purpose image
is required to be moved.
Example of animation in applet:
import [Link].*;
import [Link].*;
3) Fill the Field Name & Data Type. Then save & close.
CONNECT DATABASE:
while([Link]())
{
[Link]("\t\t Student Record No "+i+"\n\n");
[Link]("\t Student Name="+[Link](1));
[Link]("\t Student [Link]="+[Link](2));
[Link]("\t Department="+[Link](3));
[Link]();
i++;
}
[Link]();
[Link]();
[Link]();
}
catch(Exception se)
{
[Link](se);
}
}
}
Output:
Insert database:
[Link].*;
import [Link].*;
classupdatedb
{
public static void main(String[]ar)throws IOException
{
Connection con;
Statement st;
DataInputStream d=new DataInputStream([Link]);
try
{
[Link]("[Link]");
con=[Link]("jdbc:odbc:stu");
st=[Link]();
[Link]("student name");
String s=[Link]();
[Link]("regno");
int no=[Link]([Link]());
[Link]("dept");
String s1=[Link]();
int x=[Link]("update into Student set studName=' "+s+" ',dept="
'+s1+" 'where studRegno="+no);
if(x>0)
{
[Link]("x value is="+x);
[Link]("r u s");
}
[Link]();
[Link]();
}
catch(Exception se)
{
[Link](se);
}
}
}
Delete database:
[Link].*;
import [Link].*;
classdeletedb
{
public static void main(String[]ar)throws IOException
{
Connection con;
Statement st;
DataInputStream d=new DataInputStream([Link]);
try
{
[Link]("[Link]");
con=[Link]("jdbc:odbc:stu");
st=[Link]();
[Link]("regno");
intrno=[Link]([Link]());
int x=[Link]("delete from Student where rno="+rno);
if(x>0)
{
[Link]("r d s");
}
else
{
[Link]("i n f ");
}
[Link]();
[Link]();
}
catch(Exception se)
{
[Link](se);
}
}
}
Update database:
[Link].*;
import [Link].*;
classupdatedb
{
public static void main(String[]ar)throws IOException
{
Connection con;
Statement st;
DataInputStream d=new DataInputStream([Link]);
try
{
[Link]("[Link]");
con=[Link]("jdbc:odbc:stu");
st=[Link]();
[Link]("student name");
String s=[Link]();
[Link]("regno");
intrno=[Link]([Link]());
[Link]("dept");
String s1=[Link]();
int x=[Link]("update Student set n=' "+s+" ',d=' "+s1+" 'where
rno="+rno);
if(x>0)
{
[Link]("x value is="+x);
[Link]("r u s");
}
[Link]();
[Link]();
}
catch(Exception se)
{
[Link](se);
}
}
}