[Go to site: main page, start]

0% found this document useful (0 votes)
10 views84 pages

Java OOP Concepts and Programming Examples

The document provides an overview of Java as an object-oriented programming language, detailing its features such as encapsulation, inheritance, and polymorphism. It discusses the Java Virtual Machine (JVM), Java Development Kit (JDK), and various Java versions and editions. Additionally, it includes code examples demonstrating concepts like arrays, classes, inheritance, abstract classes, interfaces, and exception handling.

Uploaded by

itscynthi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views84 pages

Java OOP Concepts and Programming Examples

The document provides an overview of Java as an object-oriented programming language, detailing its features such as encapsulation, inheritance, and polymorphism. It discusses the Java Virtual Machine (JVM), Java Development Kit (JDK), and various Java versions and editions. Additionally, it includes code examples demonstrating concepts like arrays, classes, inheritance, abstract classes, interfaces, and exception handling.

Uploaded by

itscynthi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA

OOP AND JAVA:


Introduction:
 Java is a purely an object oriented language.
 C is structured programming language.
 C++ is partially object oriented language.
In oops concept the program is divided into isolated parts
called objects.
Object has 2 parts:
1) Data & Function:
Data: Functions are implemented by data.
2) Class:
Class is a collection of object.
Features of oops:
1) Encapsulation:
Data hiding – data can be handled by objects of that same
class.
2) Inheritance:
We can access above class properties by the derived class
properties.
3) Polymorphism:
Functions with same name doing different action.
Eg: Function overloading.
Java Language:
In 1991 James Gosling and Patrick Naught on developed a
language named “oak” at sun Microsystems.
In 1995 it was renamed as “Java”.
In 2010 Java goes to oracle.

JVM: (Java Virtual Machine)


1) JVM is a idealized CPU.
2) JVM is a stimulated program which executes on an real CPU.
3) Java program is first compiled into byte code and then convert
to actual machine code.
JIT: (Just In Time)
The JIT compiler change the byte code into executable machine
code.
JDK: (Java Development Kit)
1) Java language.
2) Java language package.
3) Set of Java development tools.
The important tools are,
o Java Compiler (javac)
o Java Interpreter (java)
o Java disassemble (javap)
o Java debugger (jdp)
o Tools for header files (javah)
o Tools for creating html document (java doc)
o Tools for viewing java applets. (appletviewer)

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 Source code

Java Compiler
Java Class File

Java Interpreter
Machine Code

window Linux Unix


s
Java program runs JVM and JDK tools, they make the program a
Platform Independent.
To save java program:
Filename-> class name in which main() function resides in a java
program.
<filename>.java
To compile:
Javac [Link] (create a class file)
To run:
Java filename (convert the class file byte code into machine
code)
Functions are called as methods.

RUNTIME VALUE GETTING


MULTIPLICATION TABLE
import [Link].*;
class table
{
public void get(int x)
{
int n=x;
for(int i=1;i<=10;i++)
{
int t=i*n;
[Link](i+" * "+n+" = "+t);
}
}
}
public class TableMain
{
public static void main(String arg[])throws IOException
{
DataInputStream d=new DataInputStream([Link]);
[Link]("Enter N value=");
int n=[Link]([Link]());
table s=new table();
[Link](n);
} }

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]);
}
}
}

Write a program to find the N is a factor of M or not.


import [Link].*;
class factor
{
public static void main(String args[])throws IOException
{
inti,s=0;
DataInputStream d=new DataInputStream([Link]);
[Link]("Enter n value:");
int n=[Link]([Link]());
[Link]("Enter m value:");
int m=[Link]([Link]());
for(i=2;i<m;i++)
{
if(m%i==0)
{
if(n==i)
{
s=1;
}
}
}
if(s==1)
{
[Link](n+" is factor of "+m);
}
else
{
[Link](n+" is not factor of "+m);
}
}
}

TWO DIMENSIONAL ARRAY-MATRIC MULTIPLICATION


import [Link].*;
classMultimat
{
public static void main(String ar[])throws IOException
{
inti,j,r,c;
int a[][]=new int[5][5];
int b[][]=new int[5][5];
int s[][]=new int[5][5];
DataInputStream d=new DataInputStream([Link]);
[Link]("Enter row value:");
r=[Link]([Link]());
[Link]("Enter col value:");
c=[Link]([Link]());
[Link]("Enter A matrix:");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
a[i][j]=[Link]([Link]());
}

}
[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]();
}
}
}

CLASSES & OBJECTS


class Rectangle
{
intlength,width;

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]();
}
}

THIS KEYWORD USING ARMSTRONG NO:


classAms
{
int n;
Ams(int n)
{
this.n=n;
}

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.

DIFFERENCE BETWEEN ABSTRACT CLASS & INTERFACE:

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)

1)Process-based Multitasking (Multiprocessing)


 Each process have its own address in memory 1i.e. each process
allocates separate memory area.
 Process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another require some time for
saving and loading registers, memory maps, updating lists etc.
2)Thread-based Multitasking (Multithreading)
 Threads share the same address space.
 Thread is lightweight.
 Cost of communication between the thread is low.
 Note:At least one process is required for each thread.
What is Thread?
A thread is a lightweight subprocess, a smallest unit of processing. It
is a separate path of execution. It shares the memory area of process.
Life cycle of a Thread (Thread States)
A thread can be in one of the five states in the thread. According to
sun, there is only 4 states new, runnable, non-runnable and
terminated. There is no running state. But for better understanding the
threads, we are explaining it in the 5 states. The life cycle of the
thread is controlled by JVM. The thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1)New
The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
2)Runnable
The thread is in runnable state after invocation of start() method, but
the thread scheduler has not selected it to be the running thread.
3)Running
The thread is in running state if the thread scheduler has selected it.
4)Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not
eligible to run.
5)Terminated
A thread is in terminated or dead state when its run() method exits.
How to create thread:
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform
operations on a [Link] class extends Object class and
implements Runnable interface.
Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

1)By extending Thread class:


class Multi extends Thread
{
public void run()
{
[Link]("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
[Link]();
}
}
Output: thread is running...

2)By implementing the Runnable interface:


class Multi3 implements Runnable
{
public void run()
{
[Link]("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
[Link]();
}
}
Output: thread is running...

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

The join() method:


The join() method waits for a thread to die. In other words, it causes
the currently running threads to stop executing until the thread it joins
with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
The join() method:
class Multi extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
[Link](500);
}
catch(Exception e)
{
[Link](e);
}
[Link](i);
}
}
public static void main(String args[])
{
Multi t1=new Multi();
Multi t2=new Multi();
Multi t3=new Multi();
[Link]();
try
{
[Link](); // [Link](1500);
}
catch(Exception e)
{
[Link](e);
}
[Link]();
[Link]();
}
}

Output:
1
2
3
4
5
1
1
2
2
3
3
4
4
5
5

Priority of a Thread (Thread Priority):


3 constants defined in Thread class:
1. public static int MIN_PRIORITY - 1
2. public static int NORM_PRIORITY - 5
3. public static int MAX_PRIORITY - 10

class Multi extends Thread


{
public void run()
{
[Link]("running thread name is:"+[Link]
rentThread().getName());
[Link]("running thread priority is:
"+[Link]().getPriority());
}
public static void main(String args[])
{
Multi m1=new Multi();
Multi m2=new Multi();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}
}
Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

AWT – Abstract Windowing Toolkit


Label, TextField& Button:
Arithmetic operation:
[Link].*;
[Link].*;
public class lbldemo1 extends Frame implements ActionListener
{
String str;
inti,j,k;
TextField t1,t2,t3;
Button b1,b2,b3,b4;

lbldemo1()
{
setTitle("Example of TextField, Label,Button");
setVisible(true);
setSize(600,300);
setLayout(null);

Label l1=new Label("Simple Calculator");


[Link](50,100,100,30);
add(l1);

Label l2=new Label("Enter First No ");


[Link](50,150,100,30);
add(l2);

Label l3=new Label("Enter Second NO ");


[Link](50,200,100,30);
add(l3);

Label l4=new Label("Result ");


[Link](50,250,100,30);
add(l4);

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);

b1=new Button(" Sum ");


[Link](50,300,75,30);
add(b1);

b2=new Button(" Sub ");


[Link](150,300,75,30);
add(b2);

b3=new Button(" Mul ");


[Link](250,300,75,30);
add(b3);
b4=new Button(" Div ");
[Link](350,300,75,30);
add(b4);

[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].*;

/*<applet code="GridLayoutDemo" width=300


height=200></applet>*/

public class GridLayoutDemo extends Applet


{
static final int n=4;
public void init()
{
setLayout(new GridLayout(n,n));
setFont(new Font("SansSerif",[Link],24));
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
int k=i*n+j;
if(k>0)
{
add(new Button(" "+k));
}
}
}
}
}

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);

[Link]("Ur selected languages are:"+lang);


}
}
public static void main(String[] arg)
{
newCheckboxexam("Check Box and Radio Button Demo");
}
}
OUTPUT:
MENUBARS & MENUS – FILE DIALOG BOX:
[Link].*;
[Link].*;
import [Link].*;
[Link].*;
public class Editor extends Frame
{
String filename;
TextAreatx;
Editor()
{
setLayout(new GridLayout(1,1));
tx=new TextArea();
add(tx);
MenuBarmb=new MenuBar();
Menu F=new Menu("File");
MenuItem n=new MenuItem("New");
MenuItem o=new MenuItem("Open");
MenuItem s=new MenuItem("Save");
MenuItem e=new MenuItem("Exit");
[Link](new New());
[Link](n);
[Link](new Open());
[Link](o);
[Link](new Save());
[Link](s);
[Link](new Exit());
[Link](e);
[Link](F);
setMenuBar(mb);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
class New implements ActionListener
{
public void actionPerformed(ActionEventae)
{
[Link](" ");
setTitle("Notepad");
}
}
class Open implements ActionListener
{
public void actionPerformed(ActionEventae)
{
FileDialogfd=new FileDialog([Link],"Select
File",[Link]);
[Link]();
if([Link]()!=null)
{
filename=[Link]()+[Link]();
setTitle(filename);
ReadFile();
}
[Link]();
}
}
class Save implements ActionListener
{
public void actionPerformed(ActionEventae)
{
FileDialogfd=new FileDialog([Link],"Save
File",[Link]);
[Link]();
if([Link]()!=null)
{
filename=[Link]()+[Link]();
setTitle(filename);
try
{
DataOutputStream d=new
DataOutputStream(new FileOutputStream(filename));
String line=[Link]();
[Link](line);
BufferedReaderbr=new BufferedReader(new
StringReader(line));
while((line=[Link]())!=null)
{
[Link](line+"\r\n");
}
[Link]();
}
catch(Exception ex)
{
[Link]("FileNotFound");
}
[Link]();
}
}
}
class Exit implements ActionListener
{
public void actionPerformed(ActionEventae)
{
[Link](0);
}
}
voidReadFile()
{
BufferedReader d;
StringBuffersb=new StringBuffer();
try
{
d=new BufferedReader(new FileReader(filename));
String line;
while((line=[Link]())!=null)
[Link](line + "\n");
[Link]([Link]());
[Link]();
}
catch(FileNotFoundException ex)
{
[Link]("File Not Found");
}
catch(IOExceptionioe){}
}
public static void main(String[] ar)
{
Frame f=new Editor();
[Link](500,400);
[Link](true);
[Link]();
}
}
OUTPUT:

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.

Lifecycle methods for Applet:


The [Link] class 4 life cycle methods and
[Link] class provides 1 life cycle methods for an applet.
[Link] class:
For creating any applet [Link] class must be inherited. It
provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked
only once.
2. public void start(): is invoked after the init() method or
browser is maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked
when Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is
invoked only once.
[Link] class:
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It
provides Graphics class object that can be used for drawing
oval, rectangle, arc etc.

How to run an Applet?


There are two ways to run an applet
1. By html file.
2. By appletviewer tool (for testing purpose).

Simple example of Applet by html file:


//[Link]
import [Link];
import [Link];
public class First extends Applet
{
public void paint(Graphics g)
{
[Link]("welcome",150,150);
}
}
Note: class must be public because its object is created by Java Plugin
software that resides on the browser.
//[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:


//[Link]
import [Link].*;
import [Link].*;
public class First extends Applet
{
public void paint(Graphics g)
{
[Link]("welcome to applet",150,150);
}
}
/* <applet code="[Link]" width="300" height="300">
</applet> */

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].*;

/*<applet code="[Link]" height="800"


width="800"></applet>*/
public class DemoApplet extends Applet
{
public void paint(Graphics g)
{
[Link](new Font("TimesNewRoman",[Link],25));
[Link]([Link]);
[Link]("WELCOME",300,50);
[Link](100,100,200,200);
[Link](300,300,50,80);
[Link](100,200,150,150,70,50);
[Link](200,100,60,60);
}
}

Output:
HOUSEAPPLET :

[Link].*;
[Link].*;

/*<applet code="[Link]" height="700" width="900">


</applet>*/

public class HouseApplet extends Applet


{
public void paint(Graphics g)
{
[Link](300,300,230,150);

[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].*;

/*<applet code="[Link]" width="300" height


="300"></applet> */
public class AnimationExample extends Applet
{
Image picture;

public void init()


{
picture =getImage(getDocumentBase(),"[Link]");
}

public void paint(Graphics g)


{
for(int i=0;i<500;i++)
{
[Link](picture, i,30, this);
try
{
[Link](100);
}
catch(Exception e){}
}
}
}

JDBC – Java Data Base Connectivity


CREATE DATABASE:
1) Open MSAccess blank database  (select path & create
database name)  click create button.

2) Right click Table  Deign View  (set table name)  click


OKbutton.

3) Fill the Field Name & Data Type. Then save & close.

CONNECT DATABASE:

1) Start  control panel  Administrative Tools  Data Sources


(ODBC).
2) Add  select Microsoft Access Driver (*.mdb, *.accdb) click
Finishbutton.
3) Fill Data Source Name  click Select button. Then select the
Java database stored area  then click the current database
name  the click OK button.

Retrieve data from the Database:


[Link].*;
classdbexam
{
public static void main(String arg[])
{
Connection con;
Statement st;
ResultSetrs;
try
{
[Link]("[Link]");
con=[Link]("jdbc:odbc:stu");
st=[Link]();
rs=[Link]("select *from stutable");
int i=1;

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);
}
}
}

You might also like