SlideShare une entreprise Scribd logo
1  sur  115
Télécharger pour lire hors ligne
INTRODUCTION
Java is −
• Object Oriented − In Java, everything is an Object. Java can be easily extended since it
is based on the Object model.
• Platform Independent − Unlike many other programming languages including C and
C++, when Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
• Simple − Java is designed to be easy to learn. If you understand the basic concept of
OOP Java, it would be easy to master.
• Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
• Architecture-neutral − Java compiler generates an architecture-neutral object file
format, which makes the compiled code executable on many processors, with the
presence of Java runtime system.
• Portable − Being architecture-neutral and having no implementation dependent aspects
of the specification makes Java portable. Compiler in Java is written in ANSI C with a
clean portability boundary, which is a POSIX subset.
• Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.
• Multithreaded − With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly.
• Interpreted − Java byte code is translated on the fly to native machine instructions and is
not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and light-weight process.
• High Performance − With the use of Just-In-Time compilers, Java enables high
performance.
• Distributed − Java is designed for the distributed environment of the internet.
• Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many set-top
box projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's
office, also went by the name ‘Green’ and ended up later being renamed as Java, from a list of
random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run
Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software under the
terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-source,
aside from a small portion of code to which Sun did not hold the copyright.
Java is an Object-Oriented Language. As a language that has the Object-Oriented feature,
Java supports the following fundamental concepts −
• Polymorphism
• Inheritance
• Encapsulation
• Abstraction
• Classes
• Objects
• Instance
• Method
• Message Passing
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Object can be defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing details of each other's data or
code, the only necessary thing is that the type of message accepted and type of response returned
by the objects.
Example: A dog is an object because it has states i.e. color, name, breed etc. as well as
behaviors i.e. wagging the tail, barking, eating etc.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class
doesn’t store any space.
Inheritance
When one object acquires all the properties and behaviours of parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
SUM OF TWO NUMBERS
import java.util.Scanner;
class abc
{
int a,b,sum;
public void getdata()
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter two numbers");
a=obj.nextInt();
b=obj.nextInt();
}
public void putdata()
{
sum=a+b;
System.out.println("The sum is "+ sum);
}
}
public class Arr
{
public static void main(String[] args)
{
abc obj=new abc();
obj.getdata();
obj.putdata();
}
}
_________________________________________________________________________
SIMPLE IF STATEMENT
public class Ifpgm
{
public static void main(String[] args)
{
boolean a=true;
if(a)
{
System.out.println("Welcome to CARE Engg College");
}
}
}
output:
Welcome to CARE Engg College
________________________________________________________________________
SIMPLE IF STATEMENT
public class Ifpgm
{
public static void main(String[] args)
{
boolean a=false;
if(a);
{
System.out.println("Welcome to CARE Engg College");
}
}
}
output:
Welcome to CARE Engg College
__________________________________________________________________________
BIGGEST AMONG TWO NUMBERS
import java.util.Scanner;
public class Ifpgm
{
public static void main(String[] args)
{
int a,b;
Scanner obj=new Scanner(System.in);
System.out.println("Enter two numbers");
a=obj.nextInt();
b=obj.nextInt();
if(a>b)
{
System.out.println("A is biggest");
}
else
{
System.out.println("B is biggest");
}
}
}
__________________________________________________________________________
BIGGEST AMONG THREE NUMBERS
import java.util.Scanner;
public class Ifpgm
{
public static void main(String[] args)
{
int a,b,c;
Scanner obj=new Scanner(System.in);
System.out.println("Enter three numbers");
a=obj.nextInt();
b=obj.nextInt();
c=obj.nextInt();
if(a>b && a>c)
{
System.out.println("A is biggest");
}
else if(b>c)
{
System.out.println("B is biggest");
}
else
{
System.out.println("C is biggest");
}
}
}
________________________________________________________________________
TO GENERATE GRADE SYSTEM OF YOUR MARK
import java.util.Scanner;
public class Ifpgm
{
public static void main(String[] args)
{
int m;
Scanner obj=new Scanner(System.in);
System.out.println("Enter your mark");
m=obj.nextInt();
if(m>=50)
{
if(m>=60)
{
if(m>=70)
{
if(m>=80)
{
if(m>=90)
{
System.out.println("S GRADE");
}else
System.out.println("A GRADE");
}else
System.out.println("B GRADE");
}else
System.out.println("C GRADE");
}else
System.out.println("D GRADE");
}
else
{
System.out.println("FAIL");
}
}
}
________________________________________________________________________
TO PRINT ASCENDING ORDER OF GIVEN LIMIT
import java.util.Scanner;
public class For
{
public static void main(String[] args)
{
int i,n;
System.out.println("Enter the limit");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for(i=1;i<=n;i++)
{
System.out.println(i);
}
}
}
________________________________________________________________________
TO PRINT DESCENDING ORDER OF GIVEN LIMIT
import java.util.Scanner;
public class For
{
public static void main(String[] args)
{
int i,n;
System.out.println("Enter the limit");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for(i=n;i>0;i--)
{
System.out.println(i);
}
}
}
________________________________________________________________________
TO PRINT ODD NUMBERS OF GIVEN LIMIT
import java.util.Scanner;
public class For
{
public static void main(String[] args)
{
int i,n;
System.out.println("Enter the limit");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for(i=1;i<=n;i++)
{
System.out.println(i);
i++;
}
}
}
________________________________________________________________________
TO PRINT EVEN NUMBERS OF GIVEN LIMIT
import java.util.Scanner;
public class For
{
public static void main(String[] args)
{
int i,n;
System.out.println("Enter the limit");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for(i=1;i<=n;i++)
{
i++;
System.out.println(i);
}
}
}
________________________________________________________________________
TO CALCULATE SUM OF SERIES OF GIVEN LIMIT
import java.util.Scanner;
public class For
{
public static void main(String[] args)
{
int i,n,sum=0;
System.out.println("Enter the limit");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for(i=1;i<=n;i++)
{
sum=sum+i;
}
System.out.println("The sum of series is "+sum);
}
}
________________________________________________________________________
TO CALCULATE FACTORIAL OF GIVEN LIMIT
import java.util.Scanner;
public class For
{
public static void main(String[] args)
{
int i,n,fact=1;
System.out.println("Enter the limit");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for(i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("The factorial value is "+fact);
}
}
________________________________________________________________________
TO CHECK WHETHER THE GIVEN NUMBER IS PRIME OR NOT
import java.util.Scanner;
public class For
{
public static void main(String[] args)
{
int i,n;
System.out.println("Enter the number");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for(i=2;i<n;i++)
{
if(n%i==0)
{
System.out.println("Given number is not a Prime");
System.exit(0);
}
}
System.out.println("Given number is Prime");
}
}
_______________________________________________________________________
TO GENERATE FIBONACCI SERIES
import java.util.Scanner;
public class For
{
public static void main(String[] args)
{
int a=0,b=1,c,i,n;
System.out.println("Enter the limit");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
System.out.println(a);
System.out.println(b);
for(i=3;i<=n;i++)
{
c=a+b;
System.out.println(c);
a=b;
b=c;
}
}
}
________________________________________________________________________
TO PRINT THE FOLLOWING PATTERN
import java.util.Scanner;
public class Nested
{
public static void main(String[] args)
{
int i,j,n;
System.out.println("Enter the limit");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.print(j+" ");
}
System.out.println();
}
}
}
output:
Enter the limit
5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
___________________________________________________________________________
TO PRINT THE FOLLOWING PATTERN
7
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
import java.util.Scanner;
public class Nested
{
public static void main(String[] args)
{
int i,j,n;
System.out.println("Enter the limit");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(j+" ");
}
System.out.println();
}
}
}
____________________________________________________________________________
TO PRINT THE FOLLOWING PATTERN
6
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
import java.util.Scanner;
public class Nested
{
public static void main(String[] args)
{
int i,j,n,k;
System.out.println("Enter the limit");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for(i=1;i<=n;i++)
{
for(k=1;k<=n-i;k++)
{
System.out.print(" ");
}
for(j=1;j<=i;j++)
{
System.out.print(j+" ");
}
System.out.println();
}
}
}
________________________________________________________________________________
TO PRINT THE FOLLOWING PATTERN
7
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
import java.util.Scanner;
public class Nested
{
public static void main(String[] args)
{
int i,j,n,k;
System.out.println("Enter the limit");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i+1;j++)
{
System.out.print(j+" ");
}
System.out.println();
for(k=1;k<=i;k++)
{
System.out.print(" ");
}
}
}
}
___________________________________________________________________________________
TO PRINT THE FOLLOWING PATTERN
7
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
import java.util.Scanner;
public class Nested
{
public static void main(String[] args)
{
int i,j,n,k;
System.out.println("Enter the limit");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
for(i=1;i<=n;i++)
{
for(k=1;k<=n-i;k++)
{
System.out.print(" ");
}
for(j=1;j<=i;j++)
{
System.out.print(j+" ");
}
System.out.println();
}
for(i=1;i<=n-1;i++)
{
for(k=1;k<=i;k++)
{
System.out.print(" ");
}
for(j=1;j<=n-i;j++)
{
System.out.print(j+" ");
}
System.out.println();
}
}
}
_____________________________________________________________________________
TO PRINT THE FOLLOWING PATTERN
7
1 1
12 12
123 123
1234 1234
12345 12345
123456 123456
1234567 1234567
import java.util.Scanner;
public class Nested
{
public static void main(String[] args)
{
int i,j,n,k,s,m=0;
System.out.println("Enter the limit");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
s=2*n-1;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(j);
}
for(k=1;k<=s-m;k++)
{
System.out.print(" ");
}
m=m+2;
for(j=1;j<=i;j++)
{
System.out.print(j);
}
System.out.println();
}
}
}
__________________________________________________________________________________
SUM OF DIGITS
import java.util.Scanner;
public class _________
{
public static void main(String[] args)
{
int n,r,sum=0;
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
while(n>0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
System.out.println(sum);
}
}
______________________________________________________________
REVERSE OF A NUMBER
public class _________
{
public static void main(String[] args)
{
int n,r,rev=0;
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
while(n>0)
{
r=n%10;
rev=rev*10+r;
n=n/10;
}
System.out.println(rev);
}
}
____________________________________________________________
ARMSTRONG NUMBER OR NOT
public class _________
{
public static void main(String[] args)
{
int n,r,sum=0;
Scanner obj=new Scanner(System.in);
n=obj.nextInt();
m=n;
while(n>0)
{
r=n%10;
sum=sum+r*r*r;
n=n/10;
}
if(sum==m)
{
System.out.println("Given number is Armstrong");
}
else
{
System.out.println("Given number is not an Armstrong");
}
}
}
________________________________________________________________
SUM OF ARRAY
public class _________
{
public static void main(String[] args)
{
int i,sum=0;
int a[]={10,20,30,40,50};
for(i=0;i<a.length;i++)
{
sum=sum+a[i];
}
System.out.println(sum);
}
}
__________________________________________________________________
FIND MINIMUM ELEMENT
public class _________
{
public static void main(String[] args)
{
int i,min;
int a[]={20,30,50,40,10};
min=a[0];
for(i=1;i<a.length;i++)
{
if(min>a[i])
{
min=a[i];
}
}
System.out.println("Minimum element is "+ min);
}
}
_________________________________________________________________
BUBBLE SORTING
public class _________
{
public static void main(String[] args)
{
int i,j,n,temp;
int a[]={20,30,50,40,10};
n=a.length;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("AFTER SORTING");
for(i=0;i<n-1;i++)
{
System.out.println(a[i]);
}
}
}
_________________________________________________________________
STRING MANIPULATION
public class _______
{
public static void main(String[] args)
{
String s1="SACHIN";
String s2="TENDULKAR";
String s3="SARAVANAN";
System.out.println(s1.concat(s2));//SACHINTENDULKAR
System.out.println(s1.charAt(4));//I
System.out.println(s1.substring(2,4));//CH
System.out.println(s2.substring(3));//DULKAR
System.out.println(s1.toLowerCase());//sachin
System.out.println(s1.toUpperCase());SACHIN
System.out.println(s1.indexOf('A'));SACHIN
System.out.println(s3.lastIndexOf('A'));//7
}
}
__________________________________________________________________
EQUALS() METHOD
public class ________
{
public static void main(String[] args)
{
String s1="SACHIN";
String s2="TENDULKAR";
if(s1.equals(s2))
{
System.out.println("Both strings are equal");
}
else
{
System.out.println("Both strings are not equal");
}
}
}
___________________________________________________________________
STRING COMPARETO() METHOD
public class Str
{
public static void main(String[] args)
{
String s1="SACHIN";
String s2="TENDULKAR";
Scanner obj=new Scanner(System.in);
s1=obj.next();//
s2=obj.next();
int l=s1.compareTo(s2);
if(l==0)
{
System.out.println("Both strings are equal");
}
else if(l>0)
{
System.out.println("S1 is biggest");
}
else
{
System.out.println("S2 is biggest");
}
}
}
_____________________________________________________________________
STRING MANIPULATIONS
public class Str11
{
public static void main(String[] args)
{
String Str = new String("Welcome to Sachin");
String SubStr1 = new String("Sachin");
String SubStr2 = new String("Tendulkar");
System.out.print("Found Index :" );
System.out.println(Str.indexOf( 'o' ));
System.out.print("Found Index :" );
System.out.println(Str.indexOf( 'o', 5 )); //After 5th character to search 'o'
System.out.print("Found Index :" );
System.out.println( Str.indexOf(SubStr1 ));
System.out.print("Found Index :" );
System.out.println( Str.indexOf( SubStr1, 15 ));
System.out.print("Found Index :" );
System.out.println(Str.indexOf( SubStr2 ));
}
}
__________________________________________________________________
POLYMORPHISM
polymorphism means ability to take more than one form.
___________________________________________________________________
function overloading
--> Function names are same. But it differ by its arguments.
class fnover
{
public void area(int l, int b)
{
System.out.println("Area of rectangle "+l*b);
}
public void area(double b1, double h)
{
System.out.println("Area of triangle "+05*b1*h);
}
public void area(int a)
{
System.out.println("Area of square "+a*a);
}
}
public class Str
{
public static void main(String[] args)
{
fnover obj=new fnover();
obj.area(10, 20);
obj.area(10.5, 20.5);
obj.area(100);
}
}
Area of rectangle 200
Area of triangle 1076.25
Area of square 10000
_________________________________________________________________
CONSTRUCTOR
-->Class name is same as function name is called as constructor.
-->No need return type.
-->It cannot be inherited.
-->No need dot (.) for call the constructor methods.
-->Assignment operator is used to call the constructor methods.
class sample
{
int a,b,c;
public sample()//Default Constructor
{
a=0;
b=0;
}
public sample(int x, int y)//Parameterized Constructor
{
a=x;
b=y;
}
public void display()
{
c=a+b;
System.out.println("sum is "+c);
}
}
public class Str
{
public static void main(String[] args)
{
sample obj1=new sample();
sample obj2=new sample(10,20);
obj2.display();
}
}
________________________________________________________________
INTERFACE
--> It is act as only super class.
--> It cannot be create any objects.
--> It cannot be defined methods in interface class.
interface A
{
public void getdata();
public void putdata();
}
class B implements A
{
int a,b,c;
public void getdata()
{
Scanner obj=new Scanner(System.in);
a=obj.nextInt();
b=obj.nextInt();
}
public void putdata()
{
c=a+b;
System.out.println(c);
}
}
public class _____
{
public static void main(String[] args)
{
B obj=new B();
obj.getdata();
obj.putdata();
}
}
_____________________________________________________________
MULTILEVEL INTERFACE
interface A
{
public void geta();
}
interface B extends A
{
public void getb();
}
class C implements B
{
int a,b,c;
public void geta()
{
System.out.println("Enter a value");
Scanner obj=new Scanner(System.in);
a=obj.nextInt();
}
public void getb()
{
System.out.println("Enter b value");
Scanner obj=new Scanner(System.in);
b=obj.nextInt();
}
public void putdata()
{
c=a+b;
System.out.println("The sum is "+ c);
}
}
public class Inter
{
public static void main(String[] args)
{
C obj=new C();
obj.geta();
obj.getb();
obj.putdata();
}
}
________________________________________________________________
ABSTRACT CLASS
--> It is act as only super class.
--> It cannot be create any objects.
--> Abstract class contain normal methods and abstract methods.
--> It cannot be defined abstract methods in abstract class.
But normal methods can be defined inside the abstract class.
abstract class abc
{
abstract public void sum();
abstract public void sub();
public void display()
{
System.out.println("This is an Abstract class");
}
}
class pqr extends abc
{
int a,b,c;
public void sum()
{
Scanner obj1=new Scanner(System.in);
a=obj1.nextInt();
b=obj1.nextInt();
c=a+b;
System.out.println("The sum is "+c);
}
public void sub()
{
Scanner obj2=new Scanner(System.in);
a=obj2.nextInt();
b=obj2.nextInt();
c=a-b;
System.out.println("The sub is "+c);
}
}
public class Xyz
{
public static void main(String[] args)
{
pqr obj=new pqr();
obj.display();
obj.sum();
obj.sub();
}
}
__________________________________________________________________
SINGLE LEVEL INHERITANCE
class abc
{
int a,b;
public void getdata()
{
System.out.println("Enter two numbers");
Scanner obj=new Scanner(System.in);
a=obj.nextInt();
b=obj.nextInt();
}
}
class xyz extends abc
{
int c;
public void putdata()
{
c=a+b;
System.out.println(c);
}
}
public class Inherit
{
public static void main(String[] args)
{
xyz obj=new xyz();
obj.getdata();
obj.putdata();
}
}
__________________________________________________________________
MULTITHREADING
-->Multiple flow of control is called as multithreading.
-->It is also called as multitasking or parallel processing or multi
programming.
class thA extends Thread
{
int i;
public void run()
{
for(i=1;i<=5;i++)
{
System.out.println("I= "+i);
}
}
}
class thB extends Thread
{
int j;
public void run()
{
for(j=1;j<=5;j++)
{
System.out.println("J= "+j);
}
}
}
class thC extends Thread
{
int k;
public void run()
{
for(k=1;k<=5;k++)
{
System.out.println("K= "+k);
}
}
}
public class Multi
{
public static void main(String[] args)
{
thA obj1=new thA();
thB obj2=new thB();
thC obj3=new thC();
obj1.start();//start() method call to thA run() method
obj2.start();//start() method call to thB run() method
obj3.start();//start() method call to thC run() method
}
}
First execution
I= 1
I= 2
I= 3
I= 4
I= 5
J= 1
J= 2
J= 3
J= 4
J= 5
K= 1
K= 2
K= 3
K= 4
K= 5
Second execution
I= 1
K= 1
K= 2
K= 3
J= 1
K= 4
I= 2
K= 5
J= 2
J= 3
I= 3
I= 4
I= 5
J= 4
J= 5
Third execution
I= 1
K= 1
K= 2
K= 3
I= 2
I= 3
I= 4
I= 5
J= 1
K= 4
K= 5
J= 2
J= 3
J= 4
J= 5
Fourth execution
I= 1
I= 2
J= 1
J= 2
J= 3
J= 4
I= 3
J= 5
K= 1
K= 2
I= 4
K= 3
I= 5
K= 4
K= 5
__________________________________________________________________
LIFE CYCLE OF THREAD
class thA extends Thread
{
int i;
public void run()
{
for(i=1;i<=5;i++)
{
if(i==3)
{
try {
sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(thA.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("I= "+i);
}
}
}
class thB extends Thread
{
int j;
public void run()
{
for(j=1;j<=5;j++)
{
if(j==4)
{
stop();
}
System.out.println("J= "+j);
}
}
}
class thC extends Thread
{
int k;
public void run()
{
for(k=1;k<=5;k++)
{
System.out.println("K= "+k);
}
}
}
public class Multi
{
public static void main(String[] args)
{
thA obj1=new thA();
thB obj2=new thB();
thC obj3=new thC();
obj1.start();
obj2.start();
obj3.start();
}
}
First
I= 1
I= 2
K= 1
K= 2
K= 3
K= 4
K= 5
J= 1
J= 2
J= 3
I= 3
I= 4
I= 5
second
I= 1
K= 1
J= 1
J= 2
K= 2
K= 3
K= 4
I= 2
K= 5
J= 3
__________________________________________________________________
THREAD PRIORITY
class thA extends Thread
{
int i;
public void run()
{
for(i=1;i<=5;i++)
{
if(i==3)
{
try {
sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(thA.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("I= "+i);
}
}
}
class thB extends Thread
{
int j;
public void run()
{
for(j=1;j<=5;j++)
{
if(j==4)
{
stop();
}
System.out.println("J= "+j);
}
}
}
class thC extends Thread
{
int k;
public void run()
{
for(k=1;k<=5;k++)
{
System.out.println("K= "+k);
}
}
}
public class Multi
{
public static void main(String[] args)
{
thA obj1=new thA();
thB obj2=new thB();
thC obj3=new thC();
obj1.setPriority(MINPRIORITY);
obj2.setPriority(MAXPRIORITY);
obj3.setPriority(NORMPRIORITY);
obj1.start();
obj2.start();
obj3.start();
}
}
EXCEPTION HANDLING
Exception Handling is the mechanism to handle runtime malfunctions. We need to handle
such exceptions to prevent abrupt termination of program. The term exception means exceptional
condition, it is a problem that may arise during the execution of program. A bunch of things can
lead to exceptions, including programmer error, hardware failures, files that need to be opened
cannot be found, resource exhaustion etc.
EXCEPTION
A Java Exception is an object that describes the exception that occurs in a program.
When an exceptional events occurs in java, an exception is said to be thrown. The code that's
responsible for doing something about the exception is called an exception handler.
EXCEPTION CLASS HIERARCHY
All exception types are subclasses of class Throwable, which is at the top of exception class
hierarchy.
• Exception class is for exceptional conditions that program should catch. This class is extended to
create user specific exception classes.
• RuntimeException is a subclass of Exception. Exceptions under this class are automatically
defined for programs.
• Exceptions of type Error are used by the Java run-time system to indicate errors having to do
with the run-time environment, itself. Stack overflow is an example of such an error.
EXCEPTION ARE CATEGORIZED INTO 3 CATEGORY.
• Checked Exception
The exception that can be predicted by the programmer at the compile time.Example :
File that need to be opened is not found. These type of exceptions must be checked at
compile time.
• Unchecked Exception
Unchecked exceptions are the class that extends RuntimeException. Unchecked
exception are ignored at compile time. Example : ArithmeticException,
NullPointerException, Array Index out of Bound exception. Unchecked exceptions are
checked at runtime.
• Error
Errors are typically ignored in code because you can rarely do anything about an error.
Example : if stack overflow occurs, an error will arise. This type of error cannot be
handled in the code.
UNCAUGHT EXCEPTIONS
When we don't handle the exceptions, they lead to unexpected program termination. Lets take an
example for better understanding.
class UncaughtException
{
public static void main(String args[])
{
int a = 0;
int b = 7/a; // Divide by zero, will lead to exception
}
}
This will lead to an exception at runtime, hence the Java run-time system will construct an
exception and then throw it. As we don't have any mechanism for handling exception in the
above program, hence the default handler will handle the exception and will print the details of
the exception on the terminal.
FILE HANDLING IN JAVA USING FILEWRITER AND FILEREADER
Java FileWriter and FileReader classes are used to write and read data from text files (they are Character
Stream classes). It is recommended not to use the FileInputStream and FileOutputStream classes if you
have to read and write any textual information as these are Byte stream classes.
FileWriter
FileWriter is useful to create a file writing characters into it.
• This class inherits from the OutputStream class.
• The constructors of this class assume that the default character encoding and the default byte-
buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on
a FileOutputStream.
• FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider
using a FileOutputStream.
Constructors:
• FileWriter(File file) – Constructs a FileWriter object given a File object.
• FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.
• FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor.
• FileWriter (String fileName) – constructs a FileWriter object given a file name.
• FileWriter (String fileName, Boolean append) – Constructs a FileWriter object given a file
name with a Boolean indicating whether or not to append the data written.
import java.io.FileWriter;
import java.io.IOException;
class CreateFile
{
public static void main(String[] args) throws IOException
{
// Accept a string
String str = "File Handling in Java using "+
" FileWriter and FileReader";
// attach a file to FileWriter
FileWriter fw=new FileWriter("text");
// read character wise from string and write
// into FileWriter
for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));
//close the file
fw.close();
}
}
FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
• This class inherit from the InputStreamReader Class.
• The constructors of this class assume that the default character encoding and the default
byte-buffer size are appropriate. To specify these values yourself, construct an
InputStreamReader on a FileInputStream.
• FileReader is meant for reading streams of characters. For reading streams of raw bytes,
consider using a FileInputStream.
Constructors:
• FileReader(File file) – Creates a FileReader , given the File to read from
• FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter to
read from
• FileReader(String fileName) – Creates a new FileReader , given the name of the file to
read from
Methods:
• public int read () throws IOException – Reads a single character. This method will
block until a character is available, an I/O error occurs, or the end of the stream is
reached.
• public int read(char[] cbuff) throws IOException – Reads characters into an array.
This method will block until some input is available, an I/O error occurs, or the end of the
stream is reached.
• public abstract int read(char[] buff, int off, int len) throws IOException –Reads
characters into a portion of an array. This method will block until some input is available,
an I/O error occurs, or the end of the stream is reached.
Parameters:
cbuf – Destination buffer
off – Offset at which to start storing characters
len – Maximum number of characters to read
• public long skip(long n) throws IOException –Skips characters. This method will
block until some characters are available, an I/O error occurs, or the end of the stream is
reached.
Parameters:
n – The number of characters to skip
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
public static void main(String[] args) throws IOException
{
// variable declaration
int ch;
// check if File exists or not
FileReader fr=null;
try
{
fr = new FileReader("text");
}
catch (FileNotFoundException fe)
{
System.out.println("File not found");
}
// read from FileReader till the end of file
while ((ch=fr.read())!=-1)
System.out.print((char)ch);
// close the file
fr.close();
}
}
_________________________________________________________
CREATE LOGIN FORM
import java.awt.Color;
import javax.swing.*;
class simpleframe extends JFrame
{
public simpleframe()
{
setSize(600,300);
setTitle("login");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setBackground(Color.red);
simplepanel sp=new simplepanel();
add(sp);
}
}
class simplepanel extends JPanel
{
public simplepanel()
{
JLabel l1=new JLabel("USERNAME");
add(l1);
JTextField tf1=new JTextField(10);
add(tf1);
JLabel l2=new JLabel("PASSWORD");
add(l2);
JTextField tf2=new JTextField(25);
add(tf2);
JButton b1=new JButton("OK");
add(b1);
JButton b2=new JButton("CANCEL");
add(b2);
}
}
public class Fr
{public static void main(String[] args)
{
simpleframe obj=new simpleframe();
}
}
__________________________________________________________________
EVENT HANDLING
import java.awt.*;
import java.awt.Color;
import javax.swing.*;
import java.awt.event.*;
class abc extends JFrame implements ActionListener
{
JTextField tf=new JTextField();
abc()
{
getContentPane().setBackground(Color.red);
tf.setBounds(60,50,200,40);
JButton b=new JButton("CLICK");
b.setBounds(100,120,80,30);
JButton b1=new JButton("CLICK1");
b1.setBounds(200,120,80,30);
b.addActionListener(this);
b1.addActionListener(this);
add(b);
add(b1);
add(tf);
setSize(400,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="CLICK")
{
tf.setText("Welcome to CARE Engg College");
}
if(e.getActionCommand()=="CLICK1")
{
tf.setText("Welcome to Trichy");
}
}
}
public class Proj1
{
public static void main(String[] args)
{
abc obj=new abc();
}
}
_______________________________________________________________________
import java.awt.*;
import java.awt.Color;
import javax.swing.*;
import java.awt.event.*;
class abc extends JFrame implements ActionListener
{
JTextField tf=new JTextField();
abc()
{
getContentPane().setBackground(Color.red);
tf.setBounds(60,50,200,40);
JButton b=new JButton("CLICK");
b.setBounds(100,120,80,30);
JButton b1=new JButton("CLICK1");
b1.setBounds(200,120,80,30);
b.addActionListener(this);
b1.addActionListener(this);
add(b);
add(b1);
add(tf);
setSize(400,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="CLICK")
{
tf.setText("Welcome to CARE Engg College");
getContentPane().setBackground(Color.yellow);
}
if(e.getActionCommand()=="CLICK1")
{
tf.setText("Welcome to Trichy");
getContentPane().setBackground(Color.green);
}
}
}
public class Proj1
{
public static void main(String[] args)
{
abc obj=new abc();
}
}
______________________________________________________________________
COLOR CHANGE EVENT
import java.awt.*;
import java.awt.Color;
import javax.swing.*;
import java.awt.event.*;
class abc extends JFrame implements ActionListener
{
JTextField tf=new JTextField();
abc()
{
getContentPane().setBackground(Color.white);
tf.setBounds(115,50,250,40);
JButton b1=new JButton("RED");
b1.setBounds(100,120,80,30);
JButton b2=new JButton("GREEN");
b2.setBounds(200,120,80,30);
JButton b3=new JButton("BLUE");
b3.setBounds(300,120,80,30);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
add(b1);
add(b2);
add(b3);
add(tf);
setSize(400,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="RED")
{
tf.setText("YOU HAVE SELECT RED COLOR");
getContentPane().setBackground(Color.red);
}
if(e.getActionCommand()=="GREEN")
{
tf.setText("YOU HAVE SELECT GREEN COLOR");
getContentPane().setBackground(Color.green);
}
if(e.getActionCommand()=="BLUE")
{
tf.setText("YOU HAVE SELECT BLUE COLOR");
getContentPane().setBackground(Color.blue);
}
}
}
public class Proj1
{
public static void main(String[] args)
{
abc obj=new abc();
}
}
_________________________________________________________________________
COLOR EVENT
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjava.awt.Color;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
public class ColorFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
finalJButtonredButton = new JButton ("Red");
finalJButtongreenButton = new JButton ("Green");
finalJButtonblueButton = new JButton ("Blue");
class Listener extends JPanel implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Color color;
if (event.getSource() == redButton)
{
color = Color.red;
}
else if (event.getSource() == greenButton)
{
color = Color.green;
}
else
{
color = Color.blue;
}
setBackground(color);
System.out.println(color);
repaint();
}
}
redButton.addActionListener(new Listener());
greenButton.addActionListener(new Listener());
blueButton.addActionListener(new Listener());
panel.add(new JButton ("Red"));
panel.add(new JButton ("Green"));
panel.add(new JButton ("Blue"));
frame.add(panel);
}
}
__________________________________________________
DATABASE CONNECTION
importjava.sql.*;
importjava.util.Scanner;
public class dbconnection
{
public static void main(String[] args) throws ClassNotFoundException, SQLException
{
String s1;
String s2;
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/sac","a1","b1");
System.out.println("Connection successful");
Statement st=con.createStatement();
String query = " insert into stud (name, addr)" + " values (?, ?)";
PreparedStatementpst = con.prepareStatement(query);
System.out.println("Enter the username and password");
Scanner obj=new Scanner(System.in);
s1=obj.next();
s2=obj.next();
pst.setString (1, s1);
pst.setString (2, s2);
pst.execute();
ResultSet r = st.executeQuery("select * from stud");
System.out.println(“Display all records”);
while(r.next())
{
System.out.println("username is "+r.getString("uname"));
System.out.println("password is "+r.getString("pwd"));
}
ResultSet r = st.executeQuery("select * from stud");
System.out.println("Enter the search record");
String key=obj.next();
while(r.next())
{
if(r.getString(1).compareTo(key)==0)
{
System.out.println("Username is "+r.getString("uname"));
System.out.println("Address is "+r.getString("pwd"));
}
}
}
}
___________________________________________________________________
EXAM SOFTWARE - PROJECT
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class OnlineTest extends JFrame implements ActionListener
{
JLabel l;
JRadioButton jb[]=new JRadioButton[5];
JButton b1,b2;
ButtonGroup bg;
int count=0,current=0,x=1,y=1,now=0;
int m[]=new int[10];
OnlineTest(String s)
{
super(s);
l=new JLabel();
add(l);
bg=new ButtonGroup();
for(int i=0;i<5;i++)
{
jb[i]=new JRadioButton();
add(jb[i]);
bg.add(jb[i]);
}
b1=new JButton("Next");
b2=new JButton("Bookmark");
b1.addActionListener(this);
b2.addActionListener(this);
add(b1);add(b2);
set();
l.setBounds(30,40,450,20);
jb[0].setBounds(50,80,100,20);
jb[1].setBounds(50,110,100,20);
jb[2].setBounds(50,140,100,20);
jb[3].setBounds(50,170,100,20);
b1.setBounds(100,240,100,30);
b2.setBounds(270,240,100,30);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setLocation(250,100);
setVisible(true);
setSize(600,350);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
if(check())
count=count+1;
current++;
set();
if(current==9)
{
b1.setEnabled(false);
b2.setText("Result");
}
}
if(e.getActionCommand().equals("Bookmark"))
{
JButton bk=new JButton("Bookmark"+x);
bk.setBounds(480,20+30*x,100,30);
add(bk);
bk.addActionListener(this);
m[x]=current;
x++;
current++;
set();
if(current==9)
b2.setText("Result");
setVisible(false);
setVisible(true);
}
for(int i=0,y=1;i<x;i++,y++)
{
if(e.getActionCommand().equals("Bookmark"+y))
{
if(check())
count=count+1;
now=current;
current=m[y];
set();
((JButton)e.getSource()).setEnabled(false);
current=now;
}
}
if(e.getActionCommand().equals("Result"))
{
if(check())
count=count+1;
current++;
//System.out.println("correct ans="+count);
JOptionPane.showMessageDialog(this,"correct ans="+count);
System.exit(0);
}
}
void set()
{
jb[4].setSelected(true);
if(current==0)
{
l.setText("Que1: Which one among these is not a primitive datatype?");
jb[0].setText("int");jb[1].setText("Float");jb[2].setText("boolean");jb[3].setText("char");
}
if(current==1)
{
l.setText("Que2: Which class is available to all the class automatically?");
jb[0].setText("Swing");jb[1].setText("Applet");jb[2].setText("Object");jb[3].setText("ActionEvent");
}
if(current==2)
{
l.setText("Que3: Which package is directly available to our class without importing it?");
jb[0].setText("swing");jb[1].setText("applet");jb[2].setText("net");jb[3].setText("lang");
}
if(current==3)
{
l.setText("Que4: String class is defined in which package?");
jb[0].setText("lang");jb[1].setText("Swing");jb[2].setText("Applet");jb[3].setText("awt");
}
if(current==4)
{
l.setText("Que5: Which institute is best for java coaching?");
jb[0].setText("Utek");jb[1].setText("Aptech");jb[2].setText("SSS IT");jb[3].setText("jtek");
}
if(current==5)
{
l.setText("Que6: Which one among these is not a keyword?");
jb[0].setText("class");jb[1].setText("int");jb[2].setText("get");jb[3].setText("if");
}
if(current==6)
{
l.setText("Que7: Which one among these is not a class? ");
jb[0].setText("Swing");jb[1].setText("Actionperformed");jb[2].setText("ActionEvent");
jb[3].setText("Button");
}
if(current==7)
{
l.setText("Que8: which one among these is not a function of Object class?");
jb[0].setText("toString");jb[1].setText("finalize");jb[2].setText("equals");
jb[3].setText("getDocumentBase");
}
if(current==8)
{
l.setText("Que9: which function is not present in Applet class?");
jb[0].setText("init");jb[1].setText("main");jb[2].setText("start");jb[3].setText("destroy");
}
if(current==9)
{
l.setText("Que10: Which one among these is not a valid component?");
jb[0].setText("JButton");jb[1].setText("JList");jb[2].setText("JButtonGroup");
jb[3].setText("JTextArea");
}
l.setBounds(30,40,450,20);
for(int i=0,j=0;i<=90;i+=30,j++)
jb[j].setBounds(50,80+i,200,20);
}
boolean check()
{
if(current==0)
return(jb[1].isSelected());
if(current==1)
return(jb[2].isSelected());
if(current==2)
return(jb[3].isSelected());
if(current==3)
return(jb[0].isSelected());
if(current==4)
return(jb[2].isSelected());
if(current==5)
return(jb[2].isSelected());
if(current==6)
return(jb[1].isSelected());
if(current==7)
return(jb[3].isSelected());
if(current==8)
return(jb[1].isSelected());
if(current==9)
return(jb[2].isSelected());
return false;
}
public static void main(String s[])
{
new OnlineTest("Online Test Of Java");
}
}
______________________________________________________________________
MINI PROJECT
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.*;
class abc extends JFrame implements ActionListener
{
JTextField tf=new JTextField();
public abc()
{
getContentPane().setBackground(Color.yellow);
JLabel l1=new JLabel("Student Name: ");
tf.setBounds(115,50,250,30);
JLabel l2=new JLabel("Student RegNo: ");
tf.setBounds(115,150,250,30);
JLabel l3=new JLabel("Subject1: ");
tf.setBounds(115,250,250,30);
JLabel l4=new JLabel("Subject2: ");
tf.setBounds(215,250,250,30);
JLabel l5=new JLabel("Subject3: ");
tf.setBounds(315,250,250,30);
JLabel l6=new JLabel("Subject4: ");
tf.setBounds(415,250,250,30);
JLabel l7=new JLabel("Subject5: ");
tf.setBounds(515,250,250,30);
JLabel l8=new JLabel("Subject6: ");
tf.setBounds(615,250,250,30);
JButton b1=new JButton("INSERT");
b1.setBounds(100,350,80,30);
JButton b2=new JButton("TOTAL");
b2.setBounds(200,350,80,30);
JButton b3=new JButton("AVERAGE");
b3.setBounds(300,350,80,30);
JButton b4=new JButton("RANK");
b4.setBounds(400,350,80,30);
JButton b5=new JButton("OK");
b5.setBounds(500,350,80,30);
JButton b6=new JButton("CANCEL");
b6.setBounds(600,350,80,30);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
add(l1);
add(l2);
add(l3);
add(l4);
add(l5);
add(l6);
add(l7);
add(l8);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(tf);
setSize(700,500);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="RED")
{
tf.setText("YOU HAVE SELECT RED COLOR");
getContentPane().setBackground(Color.red);
}
if(e.getActionCommand()=="GREEN")
{
tf.setText("YOU HAVE SELECT GREEN COLOR");
getContentPane().setBackground(Color.green);
}
if(e.getActionCommand()=="BLUE")
{
tf.setText("YOU HAVE SELECT BLUE COLOR");
getContentPane().setBackground(Color.blue);
}
}
}
public class Proj555
{
public static void main(String[] args) throws ClassNotFoundException, SQLException
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/student", "suresh",
"p");
}
}
_________________________________________________________________________
MINI PROJECT-STUDENT MARK DETAILS
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.*;
class abc extends JFrame implements ActionListener
{
JTextField tf1=new JTextField();
JTextField tf2=new JTextField();
JTextField tf3=new JTextField();
JTextField tf4=new JTextField();
JTextField tf5=new JTextField();
JTextField tf6=new JTextField();
JTextField tf7=new JTextField();
JTextField tf8=new JTextField();
JTextArea ta=new JTextArea();
public abc()
{
getContentPane().setBackground(Color.yellow);
JLabel l1=new JLabel("Student Name: ");
l1.setBounds(50,50, 100,30);
tf1.setBounds(150,50,250,30);
JLabel l2=new JLabel("Student RegNo: ");
l2.setBounds(50,150,100, 30);
tf2.setBounds(150,150,250,30);
JLabel l3=new JLabel("Subject1: ");
l3.setBounds(50,250,100, 30);
tf3.setBounds(115,250,250,30);
JLabel l4=new JLabel("Subject2: ");
l4.setBounds(50,250,100, 30);
tf4.setBounds(115,350,250,30);
JLabel l5=new JLabel("Subject3: ");
l4.setBounds(50,350,100, 30);
tf5.setBounds(115,450,250,30);
JLabel l6=new JLabel("Subject4: ");
l6.setBounds(50,450,100, 30);
tf6.setBounds(115,550,250,30);
JLabel l7=new JLabel("Subject5: ");
l7.setBounds(50,550,100, 30);
tf7.setBounds(115,650,250,30);
JLabel l8=new JLabel("Subject6: ");
l8.setBounds(50,650,100, 30);
tf8.setBounds(115,750,250,30);
JLabel l9=new JLabel("DISPLAY YOUR RECORDS");
l9.setBounds(600,40,100, 30);
ta.setBounds(600,80,450,300);
JButton b1=new JButton("INSERT");
b1.setBounds(400,400,120,30);
JButton b2=new JButton("TOTAL");
b2.setBounds(400,500,120,30);
JButton b3=new JButton("AVERAGE");
b3.setBounds(400,600,120,30);
JButton b4=new JButton("RANK");
b4.setBounds(500,400,120,30);
JButton b5=new JButton("SEARCH");
b5.setBounds(500,500,120,30);
JButton b6=new JButton("OK");
b6.setBounds(500,600,80,30);
JButton b7=new JButton("CANCEL");
b7.setBounds(600,400,120,30);
add(l1);
add(l2);
add(l3);
add(l4);
add(l5);
add(l6);
add(l7);
add(l8);
add(l9);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(tf1);
add(tf2);
add(tf3);
add(tf4);
add(tf5);
add(tf6);
add(tf7);
add(tf8);
add(ta);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
setSize(800,900);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/std11", "sachin",
"ten");
Statement st = con.createStatement();
if(e.getActionCommand()=="INSERT")
{
getContentPane().setBackground(Color.green);
String s1,s2;
int m1,m2,m3,m4,m5,m6,t;
double avg;
s1=tf1.getText();
System.out.println(s1);
s2=tf2.getText();
m1=Integer.parseInt(tf3.getText());
m2=Integer.parseInt(tf4.getText());
m3=Integer.parseInt(tf5.getText());
m4=Integer.parseInt(tf6.getText());
m5=Integer.parseInt(tf7.getText());
m6=Integer.parseInt(tf8.getText());
String query = " insert into student11 (name, regno,s1,s2,s3,s4,s5,s6)" + " values (?,?,?,?,?,?,?,?)";
PreparedStatement pst = con.prepareStatement(query);
pst.setString (1, s1);
pst.setString (2, s2);
pst.setInt(3, m1);
pst.setInt(4, m2);
pst.setInt (5, m3);
pst.setInt (6, m4);
pst.setInt (7, m5);
pst.setInt (8, m6);
pst.execute();
}
if(e.getActionCommand()=="TOTAL")
{
int
t=Integer.parseInt(tf3.getText())+Integer.parseInt(tf4.getText())+Integer.parseInt(tf5.getText())+Integer.
parseInt(tf6.getText())+Integer.parseInt(tf7.getText())+Integer.parseInt(tf8.getText());
String query = " insert into student11 (tot)" + " values (?)";
PreparedStatement pst = con.prepareStatement(query);
pst.setInt(9, t);
}
if(e.getActionCommand()=="AVERAGE")
{
int
t=Integer.parseInt(tf3.getText())+Integer.parseInt(tf4.getText())+Integer.parseInt(tf5.getText())+Integer.
parseInt(tf6.getText())+Integer.parseInt(tf7.getText())+Integer.parseInt(tf8.getText());
double avg=t/6;
String query = " insert into student11 (avg1)" + " values (?)";
PreparedStatement pst = con.prepareStatement(query);
pst.setDouble(10, avg);
}
if(e.getActionCommand()=="DISPLAY")
{
ResultSet r = null;
r = st.executeQuery("select * from student11");
while(r.next())
{
ta.setText("Your name is "+r.getString("name")+"n");
ta.setText("Your REGNO is "+r.getString("regno")+"n");
ta.setText("Your total mark is "+r.getString("tot")+"n");
ta.setText("Your average is "+r.getString("avg1")+"n");
}
}
if(e.getActionCommand()=="SEARCH")
{
getContentPane().setBackground(Color.red);
ResultSet r1 = null;
r1 = st.executeQuery("select * from student11");
String key=tf2.getText();
while(r1.next())
{
if(r1.getString(2).compareTo(key)==0)
{
ta.setText("Your name is "+r1.getString("name")+"n");
ta.setText("Your REGNO is "+r1.getString("regno")+"n");
ta.setText("Your total mark is "+r1.getString("tot")+"n");
ta.setText("Your average is "+r1.getString("avg1")+"n");
}
}
}
if(e.getActionCommand()=="CANCEL")
{
getContentPane().setBackground(Color.red);
ta.setText(null);
tf1.setText(null);
tf2.setText(null);
tf3.setText(null);
tf4.setText(null);
tf5.setText(null);
tf6.setText(null);
tf7.setText(null);
tf8.setText(null);
} } catch (ClassNotFoundException ex) {
Logger.getLogger(abc.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(abc.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class Proj777
{
public static void main(String[] args)
{
abc obj=new abc();
}
}
PROJECT
import java.awt.Color;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.*;
class abc extends JFrame implements ActionListener
{
JTextField tf1=new JTextField();
JTextField tf2=new JTextField();
JTextField tf3=new JTextField();
JTextField tf4=new JTextField();
JTextField tf5=new JTextField();
JTextField tf6=new JTextField();
JTextField tf7=new JTextField();
JTextField tf8=new JTextField();
JTextArea ta=new JTextArea();
public abc()
{
getContentPane().setBackground(Color.red);
JLabel l1=new JLabel("Student Name: ");
l1.setBounds(50,50, 100,30);
tf1.setBounds(150,50,250,30);
JLabel l2=new JLabel("Student RegNo: ");
l2.setBounds(50,150,100, 30);
tf2.setBounds(150,150,250,30);
JLabel l3=new JLabel("Subject1: ");
l3.setBounds(50,250,100, 30);
tf3.setBounds(115,250,250,30);
JLabel l4=new JLabel("Subject2: ");
l4.setBounds(50,350,100, 30);
tf4.setBounds(115,350,250,30);
JLabel l5=new JLabel("Subject3: ");
l5.setBounds(50,450,100, 30);
tf5.setBounds(115,450,250,30);
JLabel l6=new JLabel("Subject4: ");
l6.setBounds(50,550,100, 30);
tf6.setBounds(115,550,250,30);
JLabel l7=new JLabel("Subject5: ");
l7.setBounds(50,650,100, 30);
tf7.setBounds(115,650,250,30);
JLabel l8=new JLabel("Subject6: ");
l8.setBounds(50,750,100, 30);
tf8.setBounds(115,750,250,30);
JLabel l9=new JLabel("DISPLAY YOUR RECORDS");
l9.setBounds(600,40,100, 30);
ta.setBounds(600,80,450,300);
JButton b1=new JButton("INSERT");
b1.setBounds(400,400,120,30);
JButton b2=new JButton("TOTAL");
b2.setBounds(400,500,120,30);
JButton b3=new JButton("AVERAGE");
b3.setBounds(400,600,120,30);
JButton b4=new JButton("RANK");
b4.setBounds(500,400,120,30);
JButton b5=new JButton("SEARCH");
b5.setBounds(500,500,120,30);
JButton b6=new JButton("DISPLAY");
b6.setBounds(500,600,80,30);
JButton b7=new JButton("CANCEL");
b7.setBounds(600,400,120,30);
add(l1);
add(l2);
add(l3);
add(l4);
add(l5);
add(l6);
add(l7);
add(l8);
add(l9);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(tf1);
add(tf2);
add(tf3);
add(tf4);
add(tf5);
add(tf6);
add(tf7);
add(tf8);
add(ta);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
setSize(800,900);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/stud11", "suresh",
"p");
Statement st = con.createStatement();
if(e.getActionCommand()=="INSERT")
{
getContentPane().setBackground(Color.green);
String s1,s2;
int m1,m2,m3,m4,m5,m6,t;
double avg;
s1=tf1.getText();
System.out.println(s1);
s2=tf2.getText();
m1=Integer.parseInt(tf3.getText());
m2=Integer.parseInt(tf4.getText());
m3=Integer.parseInt(tf5.getText());
m4=Integer.parseInt(tf6.getText());
m5=Integer.parseInt(tf7.getText());
m6=Integer.parseInt(tf8.getText());
t=m1+m2+m3+m4+m5+m6;
avg=(double)t/6;
String query = " insert into std (name, reg,s1,s2,s3,s4,s5,s6,tot,avg1)" + " values
(?,?,?,?,?,?,?,?,?,?)";
PreparedStatement pst = con.prepareStatement(query);
pst.setString (1, s1);
pst.setString (2, s2);
pst.setInt(3, m1);
pst.setInt(4, m2);
pst.setInt (5, m3);
pst.setInt (6, m4);
pst.setInt (7, m5);
pst.setInt (8, m6);
pst.setInt(9, t);
pst.setDouble(10, avg);
pst.execute();
}
if(e.getActionCommand()=="TOTAL")
{
getContentPane().setBackground(Color.yellow);
}
if(e.getActionCommand()=="AVERAGE")
{
int
t=Integer.parseInt(tf3.getText())+Integer.parseInt(tf4.getText())+Integer.parseInt(tf5.getText())+Integer.
parseInt(tf6.getText())+Integer.parseInt(tf7.getText())+Integer.parseInt(tf8.getText());
double avg=(double)t/6;
String query = " insert into std (avg1)" + " values (?)";
PreparedStatement pst = con.prepareStatement(query);
pst.setDouble(10, avg);
pst.execute();
}
if(e.getActionCommand()=="DISPLAY")
{
getContentPane().setBackground(Color.green);
ResultSet r = null;
r = st.executeQuery("select * from std");
String b,c="";
int i=0,l=0;
while(r.next())
{
b="Your name is "+r.getString("name")+"n"+"Your REGNO is "+r.getString("reg")+"n"+"Your
total mark is "+r.getString("tot")+"n"+"Your average is "+r.getString("avg1")+"n";
c=c+b;
}
ta.setText(c);
}
if(e.getActionCommand()=="SEARCH")
{
getContentPane().setBackground(Color.pink);
ResultSet r1 = null;
r1 = st.executeQuery("select * from std");
String key=tf2.getText();
while(r1.next())
{
if(r1.getString(2).compareTo(key)==0)
{
ta.setText("Your name is "+r1.getString("name")+"n"+"Your REGNO is
"+r1.getString("reg")+"n"+"Your total mark is "+r1.getString("tot")+"n"+"Your average is
"+r1.getString("avg1")+"n");
}
}
}
if(e.getActionCommand()=="CANCEL")
{
getContentPane().setBackground(Color.red);
ta.setText(null);
tf1.setText(null);
tf2.setText(null);
tf3.setText(null);
tf4.setText(null);
tf5.setText(null);
tf6.setText(null);
tf7.setText(null);
tf8.setText(null);
} } catch (ClassNotFoundException ex) {
Logger.getLogger(abc.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(abc.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class Pr1
{
public static void main(String[] args)
{
abc obj=new abc();
}
}
11. Create a student registration form using swing components.
package regform;
import java.awt.Color;
import javax.swing.*;
class simpleframe extends JFrame
{
public simpleframe()
{
setSize(600,300);
setTitle("login");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setBackground(Color.red);
simplepanel sp=new simplepanel();
add(sp);
}
}
class simplepanel extends JPanel
{
public simplepanel()
{
JLabel l1=new JLabel("NAME :");
add(l1);
JTextField tf1=new JTextField(10);
add(tf1);
JLabel l2=new JLabel("ADDRESS :");
add(l2);
JTextArea ta=new JTextArea(5,50);
add(ta);
JLabel l3=new JLabel("GENDER :");
add(l3);
JRadioButton rb1=new JRadioButton("MALE");
add(rb1);
JRadioButton rb2=new JRadioButton("FEMALE");
add(rb2);
JLabel l4=new JLabel("DEPARTMENT :");
add(l4);
JCheckBox cb1=new JCheckBox("CSE");
add(cb1);
JCheckBox cb2=new JCheckBox("ECE");
add(cb2);
JCheckBox cb3=new JCheckBox("CIVIL");
add(cb3);
JLabel l5=new JLabel("COLLEGE :");
add(l5);
JComboBox cb=new JComboBox();
cb.addItem("SIT");
cb.addItem("KLNCE");
cb.addItem("KLNIT");
cb.addItem("VCET");
cb.addItem("KCET");
cb.addItem("MEPCO");
add(cb);
JButton b1=new JButton("OK");
add(b1);
JButton b2=new JButton("CANCEL");
add(b2);
}
}
public class Regform
{
public static void main(String[] args)
{
simpleframe ob=new simpleframe();
}
}
Sample input and output:
Create a form with three buttons names as RED, GRREN, and BLUE. When you click on RED any
one button the background color will be changes to the appropriate color. [CO4-AP]
Program:
package swing11;
import java.awt.*;
import java.awt.Color;
import javax.swing.*;
import java.awt.event.*;
class abc extends JFrame implements ActionListener
{
JTextField tf=new JTextField();
abc()
{
getContentPane().setBackground(Color.white);
tf.setBounds(115,50,250,40);
JButton b1=new JButton("RED");
b1.setBounds(100,120,80,30);
JButton b2=new JButton("GREEN");
b2.setBounds(200,120,80,30);
JButton b3=new JButton("BLUE");
b3.setBounds(300,120,80,30);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
add(b1);
add(b2);
add(b3);
add(tf);
setSize(400,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="RED")
{
tf.setText("YOU HAVE SELECT RED COLOR");
getContentPane().setBackground(Color.red);
}
if(e.getActionCommand()=="GREEN")
{
tf.setText("YOU HAVE SELECT GREEN COLOR");
getContentPane().setBackground(Color.green);
}
if(e.getActionCommand()=="BLUE")
{
tf.setText("YOU HAVE SELECT BLUE COLOR");
getContentPane().setBackground(Color.blue);
}
}
}
public class Swing11
{
public static void main(String[] args)
{
abc ob=new abc();
}
}
Sample input and output:

Contenu connexe

Similaire à Java training materials for computer engineering.pdf

Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit Notes
BalamuruganV28
 

Similaire à Java training materials for computer engineering.pdf (20)

Letest
LetestLetest
Letest
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
basic_java.ppt
basic_java.pptbasic_java.ppt
basic_java.ppt
 
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUEITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Java notes | All Basics |
Java notes | All Basics |Java notes | All Basics |
Java notes | All Basics |
 
Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)
 
Java_notes.ppt
Java_notes.pptJava_notes.ppt
Java_notes.ppt
 
Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit Notes
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
 
Core java
Core javaCore java
Core java
 
All experiment of java
All experiment of javaAll experiment of java
All experiment of java
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Java notes jkuat it
Java notes jkuat itJava notes jkuat it
Java notes jkuat it
 
Java notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esectionJava notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esection
 
PROGRAMMING IN JAVA unit 1.pptx
PROGRAMMING IN JAVA unit 1.pptxPROGRAMMING IN JAVA unit 1.pptx
PROGRAMMING IN JAVA unit 1.pptx
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
 
Introduction To Java.
Introduction To Java.Introduction To Java.
Introduction To Java.
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 

Dernier

Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
drjose256
 
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
Madan Karki
 
Microkernel in Operating System | Operating System
Microkernel in Operating System | Operating SystemMicrokernel in Operating System | Operating System
Microkernel in Operating System | Operating System
Sampad Kar
 
Final DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manualFinal DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manual
BalamuruganV28
 

Dernier (20)

litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdflitvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
 
Raashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashid final report on Embedded Systems
Raashid final report on Embedded Systems
 
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfInstruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
 
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
 
Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...
Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...
Module-III Varried Flow.pptx GVF Definition, Water Surface Profile Dynamic Eq...
 
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
 
Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
 
Artificial Intelligence Bayesian Reasoning
Artificial Intelligence Bayesian ReasoningArtificial Intelligence Bayesian Reasoning
Artificial Intelligence Bayesian Reasoning
 
BORESCOPE INSPECTION for engins CFM56.pdf
BORESCOPE INSPECTION for engins CFM56.pdfBORESCOPE INSPECTION for engins CFM56.pdf
BORESCOPE INSPECTION for engins CFM56.pdf
 
Introduction to Arduino Programming: Features of Arduino
Introduction to Arduino Programming: Features of ArduinoIntroduction to Arduino Programming: Features of Arduino
Introduction to Arduino Programming: Features of Arduino
 
Research Methodolgy & Intellectual Property Rights Series 2
Research Methodolgy & Intellectual Property Rights Series 2Research Methodolgy & Intellectual Property Rights Series 2
Research Methodolgy & Intellectual Property Rights Series 2
 
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdfInvolute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
 
Operating System chapter 9 (Virtual Memory)
Operating System chapter 9 (Virtual Memory)Operating System chapter 9 (Virtual Memory)
Operating System chapter 9 (Virtual Memory)
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptx
 
Quiz application system project report..pdf
Quiz application system project report..pdfQuiz application system project report..pdf
Quiz application system project report..pdf
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
 
5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...
 
Software Engineering - Modelling Concepts + Class Modelling + Building the An...
Software Engineering - Modelling Concepts + Class Modelling + Building the An...Software Engineering - Modelling Concepts + Class Modelling + Building the An...
Software Engineering - Modelling Concepts + Class Modelling + Building the An...
 
Microkernel in Operating System | Operating System
Microkernel in Operating System | Operating SystemMicrokernel in Operating System | Operating System
Microkernel in Operating System | Operating System
 
Final DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manualFinal DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manual
 

Java training materials for computer engineering.pdf

  • 1. INTRODUCTION Java is − • Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the Object model. • Platform Independent − Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on. • Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master. • Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. • Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system. • Portable − Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset. • Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking. • Multithreaded − With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly. • Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process. • High Performance − With the use of Just-In-Time compilers, Java enables high performance. • Distributed − Java is designed for the distributed environment of the internet. • Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time. History of Java James Gosling initiated Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's office, also went by the name ‘Green’ and ended up later being renamed as Java, from a list of random words. Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.
  • 2. On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL). On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright. Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java supports the following fundamental concepts − • Polymorphism • Inheritance • Encapsulation • Abstraction • Classes • Objects • Instance • Method • Message Passing Object Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical. Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing details of each other's data or code, the only necessary thing is that the type of message accepted and type of response returned by the objects. Example: A dog is an object because it has states i.e. color, name, breed etc. as well as behaviors i.e. wagging the tail, barking, eating etc. Class Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint from which you can create an individual object. Class doesn’t store any space. Inheritance When one object acquires all the properties and behaviours of parent object, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
  • 3. Polymorphism When one task is performed by different ways i.e. known as polymorphism. For example: to convince the customer differently, to draw something e.g. shape or rectangle etc. In java, we use method overloading and method overriding to achieve polymorphism. Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc. Abstraction Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing. In java, we use abstract class and interface to achieve abstraction. Encapsulation Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines. A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here. SUM OF TWO NUMBERS import java.util.Scanner; class abc { int a,b,sum; public void getdata() { Scanner obj=new Scanner(System.in); System.out.println("Enter two numbers"); a=obj.nextInt();
  • 4. b=obj.nextInt(); } public void putdata() { sum=a+b; System.out.println("The sum is "+ sum); } } public class Arr { public static void main(String[] args) { abc obj=new abc(); obj.getdata(); obj.putdata(); } } _________________________________________________________________________ SIMPLE IF STATEMENT public class Ifpgm { public static void main(String[] args) { boolean a=true;
  • 5. if(a) { System.out.println("Welcome to CARE Engg College"); } } } output: Welcome to CARE Engg College ________________________________________________________________________ SIMPLE IF STATEMENT public class Ifpgm { public static void main(String[] args) { boolean a=false; if(a); { System.out.println("Welcome to CARE Engg College"); } } }
  • 6. output: Welcome to CARE Engg College __________________________________________________________________________ BIGGEST AMONG TWO NUMBERS import java.util.Scanner; public class Ifpgm { public static void main(String[] args) { int a,b; Scanner obj=new Scanner(System.in); System.out.println("Enter two numbers"); a=obj.nextInt(); b=obj.nextInt(); if(a>b) { System.out.println("A is biggest"); } else { System.out.println("B is biggest"); }
  • 7. } } __________________________________________________________________________ BIGGEST AMONG THREE NUMBERS import java.util.Scanner; public class Ifpgm { public static void main(String[] args) { int a,b,c; Scanner obj=new Scanner(System.in); System.out.println("Enter three numbers"); a=obj.nextInt(); b=obj.nextInt(); c=obj.nextInt(); if(a>b && a>c) { System.out.println("A is biggest"); } else if(b>c)
  • 8. { System.out.println("B is biggest"); } else { System.out.println("C is biggest"); } } } ________________________________________________________________________ TO GENERATE GRADE SYSTEM OF YOUR MARK import java.util.Scanner; public class Ifpgm { public static void main(String[] args) { int m; Scanner obj=new Scanner(System.in); System.out.println("Enter your mark"); m=obj.nextInt(); if(m>=50)
  • 9. { if(m>=60) { if(m>=70) { if(m>=80) { if(m>=90) { System.out.println("S GRADE"); }else System.out.println("A GRADE"); }else System.out.println("B GRADE"); }else System.out.println("C GRADE"); }else System.out.println("D GRADE"); } else { System.out.println("FAIL"); } }
  • 10. } ________________________________________________________________________ TO PRINT ASCENDING ORDER OF GIVEN LIMIT import java.util.Scanner; public class For { public static void main(String[] args) { int i,n; System.out.println("Enter the limit"); Scanner obj=new Scanner(System.in); n=obj.nextInt(); for(i=1;i<=n;i++) { System.out.println(i); } } } ________________________________________________________________________ TO PRINT DESCENDING ORDER OF GIVEN LIMIT import java.util.Scanner;
  • 11. public class For { public static void main(String[] args) { int i,n; System.out.println("Enter the limit"); Scanner obj=new Scanner(System.in); n=obj.nextInt(); for(i=n;i>0;i--) { System.out.println(i); } } } ________________________________________________________________________ TO PRINT ODD NUMBERS OF GIVEN LIMIT import java.util.Scanner; public class For { public static void main(String[] args)
  • 12. { int i,n; System.out.println("Enter the limit"); Scanner obj=new Scanner(System.in); n=obj.nextInt(); for(i=1;i<=n;i++) { System.out.println(i); i++; } } } ________________________________________________________________________ TO PRINT EVEN NUMBERS OF GIVEN LIMIT import java.util.Scanner; public class For { public static void main(String[] args) { int i,n; System.out.println("Enter the limit"); Scanner obj=new Scanner(System.in);
  • 13. n=obj.nextInt(); for(i=1;i<=n;i++) { i++; System.out.println(i); } } } ________________________________________________________________________ TO CALCULATE SUM OF SERIES OF GIVEN LIMIT import java.util.Scanner; public class For { public static void main(String[] args) { int i,n,sum=0; System.out.println("Enter the limit"); Scanner obj=new Scanner(System.in); n=obj.nextInt(); for(i=1;i<=n;i++)
  • 14. { sum=sum+i; } System.out.println("The sum of series is "+sum); } } ________________________________________________________________________ TO CALCULATE FACTORIAL OF GIVEN LIMIT import java.util.Scanner; public class For { public static void main(String[] args) { int i,n,fact=1; System.out.println("Enter the limit"); Scanner obj=new Scanner(System.in); n=obj.nextInt(); for(i=1;i<=n;i++)
  • 15. { fact=fact*i; } System.out.println("The factorial value is "+fact); } } ________________________________________________________________________ TO CHECK WHETHER THE GIVEN NUMBER IS PRIME OR NOT import java.util.Scanner; public class For { public static void main(String[] args) { int i,n; System.out.println("Enter the number"); Scanner obj=new Scanner(System.in); n=obj.nextInt(); for(i=2;i<n;i++)
  • 16. { if(n%i==0) { System.out.println("Given number is not a Prime"); System.exit(0); } } System.out.println("Given number is Prime"); } } _______________________________________________________________________ TO GENERATE FIBONACCI SERIES import java.util.Scanner; public class For { public static void main(String[] args) { int a=0,b=1,c,i,n; System.out.println("Enter the limit");
  • 18. int i,j,n; System.out.println("Enter the limit"); Scanner obj=new Scanner(System.in); n=obj.nextInt(); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { System.out.print(j+" "); } System.out.println(); } } } output: Enter the limit 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
  • 19. 1 2 3 4 5 ___________________________________________________________________________ TO PRINT THE FOLLOWING PATTERN 7 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7 import java.util.Scanner; public class Nested { public static void main(String[] args) { int i,j,n; System.out.println("Enter the limit"); Scanner obj=new Scanner(System.in);
  • 21. import java.util.Scanner; public class Nested { public static void main(String[] args) { int i,j,n,k; System.out.println("Enter the limit"); Scanner obj=new Scanner(System.in); n=obj.nextInt(); for(i=1;i<=n;i++) { for(k=1;k<=n-i;k++) { System.out.print(" "); } for(j=1;j<=i;j++) { System.out.print(j+" "); } System.out.println(); }
  • 22. } } ________________________________________________________________________________ TO PRINT THE FOLLOWING PATTERN 7 1 2 3 4 5 6 7 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 import java.util.Scanner; public class Nested { public static void main(String[] args) { int i,j,n,k; System.out.println("Enter the limit"); Scanner obj=new Scanner(System.in); n=obj.nextInt(); for(i=1;i<=n;i++) {
  • 24. 1 2 3 4 5 6 1 2 3 4 5 6 7 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 import java.util.Scanner; public class Nested { public static void main(String[] args) { int i,j,n,k; System.out.println("Enter the limit"); Scanner obj=new Scanner(System.in); n=obj.nextInt(); for(i=1;i<=n;i++) { for(k=1;k<=n-i;k++)
  • 26. } } _____________________________________________________________________________ TO PRINT THE FOLLOWING PATTERN 7 1 1 12 12 123 123 1234 1234 12345 12345 123456 123456 1234567 1234567 import java.util.Scanner; public class Nested { public static void main(String[] args) { int i,j,n,k,s,m=0; System.out.println("Enter the limit"); Scanner obj=new Scanner(System.in);
  • 28. } } __________________________________________________________________________________ SUM OF DIGITS import java.util.Scanner; public class _________ { public static void main(String[] args) { int n,r,sum=0; Scanner obj=new Scanner(System.in); n=obj.nextInt(); while(n>0) { r=n%10; sum=sum+r; n=n/10; } System.out.println(sum);
  • 29. } } ______________________________________________________________ REVERSE OF A NUMBER public class _________ { public static void main(String[] args) { int n,r,rev=0; Scanner obj=new Scanner(System.in); n=obj.nextInt(); while(n>0) { r=n%10; rev=rev*10+r; n=n/10; } System.out.println(rev); } } ____________________________________________________________ ARMSTRONG NUMBER OR NOT
  • 30. public class _________ { public static void main(String[] args) { int n,r,sum=0; Scanner obj=new Scanner(System.in); n=obj.nextInt(); m=n; while(n>0) { r=n%10; sum=sum+r*r*r; n=n/10; } if(sum==m) { System.out.println("Given number is Armstrong"); } else { System.out.println("Given number is not an Armstrong"); } }
  • 31. } ________________________________________________________________ SUM OF ARRAY public class _________ { public static void main(String[] args) { int i,sum=0; int a[]={10,20,30,40,50}; for(i=0;i<a.length;i++) { sum=sum+a[i]; } System.out.println(sum); } } __________________________________________________________________ FIND MINIMUM ELEMENT public class _________ { public static void main(String[] args)
  • 32. { int i,min; int a[]={20,30,50,40,10}; min=a[0]; for(i=1;i<a.length;i++) { if(min>a[i]) { min=a[i]; } } System.out.println("Minimum element is "+ min); } } _________________________________________________________________ BUBBLE SORTING public class _________ { public static void main(String[] args) { int i,j,n,temp; int a[]={20,30,50,40,10}; n=a.length;
  • 34. { public static void main(String[] args) { String s1="SACHIN"; String s2="TENDULKAR"; String s3="SARAVANAN"; System.out.println(s1.concat(s2));//SACHINTENDULKAR System.out.println(s1.charAt(4));//I System.out.println(s1.substring(2,4));//CH System.out.println(s2.substring(3));//DULKAR System.out.println(s1.toLowerCase());//sachin System.out.println(s1.toUpperCase());SACHIN System.out.println(s1.indexOf('A'));SACHIN System.out.println(s3.lastIndexOf('A'));//7 } } __________________________________________________________________ EQUALS() METHOD public class ________ { public static void main(String[] args) { String s1="SACHIN"; String s2="TENDULKAR";
  • 35. if(s1.equals(s2)) { System.out.println("Both strings are equal"); } else { System.out.println("Both strings are not equal"); } } } ___________________________________________________________________ STRING COMPARETO() METHOD public class Str { public static void main(String[] args) { String s1="SACHIN"; String s2="TENDULKAR"; Scanner obj=new Scanner(System.in); s1=obj.next();// s2=obj.next(); int l=s1.compareTo(s2); if(l==0)
  • 36. { System.out.println("Both strings are equal"); } else if(l>0) { System.out.println("S1 is biggest"); } else { System.out.println("S2 is biggest"); } } } _____________________________________________________________________ STRING MANIPULATIONS public class Str11 { public static void main(String[] args) { String Str = new String("Welcome to Sachin"); String SubStr1 = new String("Sachin"); String SubStr2 = new String("Tendulkar");
  • 37. System.out.print("Found Index :" ); System.out.println(Str.indexOf( 'o' )); System.out.print("Found Index :" ); System.out.println(Str.indexOf( 'o', 5 )); //After 5th character to search 'o' System.out.print("Found Index :" ); System.out.println( Str.indexOf(SubStr1 )); System.out.print("Found Index :" ); System.out.println( Str.indexOf( SubStr1, 15 )); System.out.print("Found Index :" ); System.out.println(Str.indexOf( SubStr2 )); } } __________________________________________________________________ POLYMORPHISM polymorphism means ability to take more than one form. ___________________________________________________________________ function overloading --> Function names are same. But it differ by its arguments. class fnover {
  • 38. public void area(int l, int b) { System.out.println("Area of rectangle "+l*b); } public void area(double b1, double h) { System.out.println("Area of triangle "+05*b1*h); } public void area(int a) { System.out.println("Area of square "+a*a); } } public class Str { public static void main(String[] args) { fnover obj=new fnover(); obj.area(10, 20); obj.area(10.5, 20.5); obj.area(100); } }
  • 39. Area of rectangle 200 Area of triangle 1076.25 Area of square 10000 _________________________________________________________________ CONSTRUCTOR -->Class name is same as function name is called as constructor. -->No need return type. -->It cannot be inherited. -->No need dot (.) for call the constructor methods. -->Assignment operator is used to call the constructor methods. class sample { int a,b,c; public sample()//Default Constructor { a=0; b=0; } public sample(int x, int y)//Parameterized Constructor { a=x; b=y;
  • 40. } public void display() { c=a+b; System.out.println("sum is "+c); } } public class Str { public static void main(String[] args) { sample obj1=new sample(); sample obj2=new sample(10,20); obj2.display(); } } ________________________________________________________________ INTERFACE --> It is act as only super class. --> It cannot be create any objects. --> It cannot be defined methods in interface class. interface A
  • 41. { public void getdata(); public void putdata(); } class B implements A { int a,b,c; public void getdata() { Scanner obj=new Scanner(System.in); a=obj.nextInt(); b=obj.nextInt(); } public void putdata() { c=a+b; System.out.println(c); } } public class _____
  • 42. { public static void main(String[] args) { B obj=new B(); obj.getdata(); obj.putdata(); } } _____________________________________________________________ MULTILEVEL INTERFACE interface A { public void geta(); } interface B extends A { public void getb(); } class C implements B { int a,b,c; public void geta() { System.out.println("Enter a value");
  • 43. Scanner obj=new Scanner(System.in); a=obj.nextInt(); } public void getb() { System.out.println("Enter b value"); Scanner obj=new Scanner(System.in); b=obj.nextInt(); } public void putdata() { c=a+b; System.out.println("The sum is "+ c); } } public class Inter { public static void main(String[] args) { C obj=new C(); obj.geta(); obj.getb(); obj.putdata(); }
  • 44. } ________________________________________________________________ ABSTRACT CLASS --> It is act as only super class. --> It cannot be create any objects. --> Abstract class contain normal methods and abstract methods. --> It cannot be defined abstract methods in abstract class. But normal methods can be defined inside the abstract class. abstract class abc { abstract public void sum(); abstract public void sub(); public void display() { System.out.println("This is an Abstract class"); } } class pqr extends abc { int a,b,c; public void sum()
  • 45. { Scanner obj1=new Scanner(System.in); a=obj1.nextInt(); b=obj1.nextInt(); c=a+b; System.out.println("The sum is "+c); } public void sub() { Scanner obj2=new Scanner(System.in); a=obj2.nextInt(); b=obj2.nextInt(); c=a-b; System.out.println("The sub is "+c); } } public class Xyz { public static void main(String[] args) { pqr obj=new pqr(); obj.display(); obj.sum(); obj.sub();
  • 46. } } __________________________________________________________________ SINGLE LEVEL INHERITANCE class abc { int a,b; public void getdata() { System.out.println("Enter two numbers"); Scanner obj=new Scanner(System.in); a=obj.nextInt(); b=obj.nextInt(); } } class xyz extends abc { int c; public void putdata() { c=a+b; System.out.println(c); }
  • 47. } public class Inherit { public static void main(String[] args) { xyz obj=new xyz(); obj.getdata(); obj.putdata(); } } __________________________________________________________________ MULTITHREADING -->Multiple flow of control is called as multithreading. -->It is also called as multitasking or parallel processing or multi programming. class thA extends Thread { int i; public void run() { for(i=1;i<=5;i++) { System.out.println("I= "+i); }
  • 48. } } class thB extends Thread { int j; public void run() { for(j=1;j<=5;j++) { System.out.println("J= "+j); } } } class thC extends Thread { int k; public void run() { for(k=1;k<=5;k++) { System.out.println("K= "+k); } } } public class Multi
  • 49. { public static void main(String[] args) { thA obj1=new thA(); thB obj2=new thB(); thC obj3=new thC(); obj1.start();//start() method call to thA run() method obj2.start();//start() method call to thB run() method obj3.start();//start() method call to thC run() method } } First execution I= 1 I= 2 I= 3 I= 4 I= 5 J= 1 J= 2 J= 3 J= 4 J= 5 K= 1 K= 2
  • 50. K= 3 K= 4 K= 5 Second execution I= 1 K= 1 K= 2 K= 3 J= 1 K= 4 I= 2 K= 5 J= 2 J= 3 I= 3 I= 4 I= 5 J= 4 J= 5 Third execution I= 1 K= 1 K= 2 K= 3 I= 2
  • 51. I= 3 I= 4 I= 5 J= 1 K= 4 K= 5 J= 2 J= 3 J= 4 J= 5 Fourth execution I= 1 I= 2 J= 1 J= 2 J= 3 J= 4 I= 3 J= 5 K= 1 K= 2 I= 4 K= 3 I= 5 K= 4
  • 52. K= 5 __________________________________________________________________ LIFE CYCLE OF THREAD class thA extends Thread { int i; public void run() { for(i=1;i<=5;i++) { if(i==3) { try { sleep(5000); } catch (InterruptedException ex) { Logger.getLogger(thA.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("I= "+i); } } } class thB extends Thread { int j;
  • 53. public void run() { for(j=1;j<=5;j++) { if(j==4) { stop(); } System.out.println("J= "+j); } } } class thC extends Thread { int k; public void run() { for(k=1;k<=5;k++) { System.out.println("K= "+k); } } } public class Multi {
  • 54. public static void main(String[] args) { thA obj1=new thA(); thB obj2=new thB(); thC obj3=new thC(); obj1.start(); obj2.start(); obj3.start(); } } First I= 1 I= 2 K= 1 K= 2 K= 3 K= 4 K= 5 J= 1 J= 2 J= 3 I= 3 I= 4 I= 5
  • 55. second I= 1 K= 1 J= 1 J= 2 K= 2 K= 3 K= 4 I= 2 K= 5 J= 3 __________________________________________________________________ THREAD PRIORITY class thA extends Thread { int i; public void run() { for(i=1;i<=5;i++) { if(i==3) { try { sleep(5000); } catch (InterruptedException ex) {
  • 56. Logger.getLogger(thA.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("I= "+i); } } } class thB extends Thread { int j; public void run() { for(j=1;j<=5;j++) { if(j==4) { stop(); } System.out.println("J= "+j); } } } class thC extends Thread { int k;
  • 57. public void run() { for(k=1;k<=5;k++) { System.out.println("K= "+k); } } } public class Multi { public static void main(String[] args) { thA obj1=new thA(); thB obj2=new thB(); thC obj3=new thC(); obj1.setPriority(MINPRIORITY); obj2.setPriority(MAXPRIORITY); obj3.setPriority(NORMPRIORITY); obj1.start(); obj2.start(); obj3.start(); } } EXCEPTION HANDLING Exception Handling is the mechanism to handle runtime malfunctions. We need to handle such exceptions to prevent abrupt termination of program. The term exception means exceptional
  • 58. condition, it is a problem that may arise during the execution of program. A bunch of things can lead to exceptions, including programmer error, hardware failures, files that need to be opened cannot be found, resource exhaustion etc. EXCEPTION A Java Exception is an object that describes the exception that occurs in a program. When an exceptional events occurs in java, an exception is said to be thrown. The code that's responsible for doing something about the exception is called an exception handler. EXCEPTION CLASS HIERARCHY All exception types are subclasses of class Throwable, which is at the top of exception class hierarchy. • Exception class is for exceptional conditions that program should catch. This class is extended to create user specific exception classes. • RuntimeException is a subclass of Exception. Exceptions under this class are automatically defined for programs. • Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error.
  • 59. EXCEPTION ARE CATEGORIZED INTO 3 CATEGORY. • Checked Exception The exception that can be predicted by the programmer at the compile time.Example : File that need to be opened is not found. These type of exceptions must be checked at compile time. • Unchecked Exception Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are ignored at compile time. Example : ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked exceptions are checked at runtime. • Error Errors are typically ignored in code because you can rarely do anything about an error. Example : if stack overflow occurs, an error will arise. This type of error cannot be handled in the code. UNCAUGHT EXCEPTIONS When we don't handle the exceptions, they lead to unexpected program termination. Lets take an example for better understanding. class UncaughtException { public static void main(String args[]) { int a = 0; int b = 7/a; // Divide by zero, will lead to exception } } This will lead to an exception at runtime, hence the Java run-time system will construct an exception and then throw it. As we don't have any mechanism for handling exception in the above program, hence the default handler will handle the exception and will print the details of the exception on the terminal. FILE HANDLING IN JAVA USING FILEWRITER AND FILEREADER Java FileWriter and FileReader classes are used to write and read data from text files (they are Character Stream classes). It is recommended not to use the FileInputStream and FileOutputStream classes if you have to read and write any textual information as these are Byte stream classes.
  • 60. FileWriter FileWriter is useful to create a file writing characters into it. • This class inherits from the OutputStream class. • The constructors of this class assume that the default character encoding and the default byte- buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream. • FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream. Constructors: • FileWriter(File file) – Constructs a FileWriter object given a File object. • FileWriter (File file, boolean append) – constructs a FileWriter object given a File object. • FileWriter (FileDescriptor fd) – constructs a FileWriter object associated with a file descriptor. • FileWriter (String fileName) – constructs a FileWriter object given a file name. • FileWriter (String fileName, Boolean append) – Constructs a FileWriter object given a file name with a Boolean indicating whether or not to append the data written. import java.io.FileWriter; import java.io.IOException; class CreateFile { public static void main(String[] args) throws IOException { // Accept a string String str = "File Handling in Java using "+ " FileWriter and FileReader"; // attach a file to FileWriter FileWriter fw=new FileWriter("text"); // read character wise from string and write // into FileWriter for (int i = 0; i < str.length(); i++) fw.write(str.charAt(i)); //close the file fw.close(); } } FileReader FileReader is useful to read data in the form of characters from a ‘text’ file. • This class inherit from the InputStreamReader Class.
  • 61. • The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream. • FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream. Constructors: • FileReader(File file) – Creates a FileReader , given the File to read from • FileReader(FileDescripter fd) – Creates a new FileReader , given the FileDescripter to read from • FileReader(String fileName) – Creates a new FileReader , given the name of the file to read from Methods: • public int read () throws IOException – Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached. • public int read(char[] cbuff) throws IOException – Reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached. • public abstract int read(char[] buff, int off, int len) throws IOException –Reads characters into a portion of an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached. Parameters: cbuf – Destination buffer off – Offset at which to start storing characters len – Maximum number of characters to read • public long skip(long n) throws IOException –Skips characters. This method will block until some characters are available, an I/O error occurs, or the end of the stream is reached. Parameters: n – The number of characters to skip import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; class ReadFile { public static void main(String[] args) throws IOException { // variable declaration int ch; // check if File exists or not
  • 62. FileReader fr=null; try { fr = new FileReader("text"); } catch (FileNotFoundException fe) { System.out.println("File not found"); } // read from FileReader till the end of file while ((ch=fr.read())!=-1) System.out.print((char)ch); // close the file fr.close(); } } _________________________________________________________ CREATE LOGIN FORM import java.awt.Color; import javax.swing.*; class simpleframe extends JFrame { public simpleframe() { setSize(600,300); setTitle("login"); setLocation(100,100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);
  • 63. setBackground(Color.red); simplepanel sp=new simplepanel(); add(sp); } } class simplepanel extends JPanel { public simplepanel() { JLabel l1=new JLabel("USERNAME"); add(l1); JTextField tf1=new JTextField(10); add(tf1); JLabel l2=new JLabel("PASSWORD"); add(l2); JTextField tf2=new JTextField(25); add(tf2); JButton b1=new JButton("OK"); add(b1); JButton b2=new JButton("CANCEL"); add(b2); } }
  • 64. public class Fr {public static void main(String[] args) { simpleframe obj=new simpleframe(); } } __________________________________________________________________ EVENT HANDLING import java.awt.*; import java.awt.Color; import javax.swing.*; import java.awt.event.*; class abc extends JFrame implements ActionListener { JTextField tf=new JTextField(); abc() {
  • 65. getContentPane().setBackground(Color.red); tf.setBounds(60,50,200,40); JButton b=new JButton("CLICK"); b.setBounds(100,120,80,30); JButton b1=new JButton("CLICK1"); b1.setBounds(200,120,80,30); b.addActionListener(this); b1.addActionListener(this); add(b); add(b1); add(tf); setSize(400,300); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getActionCommand()=="CLICK") { tf.setText("Welcome to CARE Engg College"); } if(e.getActionCommand()=="CLICK1") { tf.setText("Welcome to Trichy");
  • 66. } } } public class Proj1 { public static void main(String[] args) { abc obj=new abc(); } } _______________________________________________________________________ import java.awt.*; import java.awt.Color; import javax.swing.*; import java.awt.event.*; class abc extends JFrame implements ActionListener { JTextField tf=new JTextField(); abc() {
  • 67. getContentPane().setBackground(Color.red); tf.setBounds(60,50,200,40); JButton b=new JButton("CLICK"); b.setBounds(100,120,80,30); JButton b1=new JButton("CLICK1"); b1.setBounds(200,120,80,30); b.addActionListener(this); b1.addActionListener(this); add(b); add(b1); add(tf); setSize(400,300); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getActionCommand()=="CLICK") { tf.setText("Welcome to CARE Engg College"); getContentPane().setBackground(Color.yellow); } if(e.getActionCommand()=="CLICK1") {
  • 68. tf.setText("Welcome to Trichy"); getContentPane().setBackground(Color.green); } } } public class Proj1 { public static void main(String[] args) { abc obj=new abc(); } } ______________________________________________________________________ COLOR CHANGE EVENT import java.awt.*; import java.awt.Color; import javax.swing.*; import java.awt.event.*; class abc extends JFrame implements ActionListener { JTextField tf=new JTextField();
  • 69. abc() { getContentPane().setBackground(Color.white); tf.setBounds(115,50,250,40); JButton b1=new JButton("RED"); b1.setBounds(100,120,80,30); JButton b2=new JButton("GREEN"); b2.setBounds(200,120,80,30); JButton b3=new JButton("BLUE"); b3.setBounds(300,120,80,30); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); add(b1); add(b2); add(b3); add(tf); setSize(400,300); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e)
  • 70. { if(e.getActionCommand()=="RED") { tf.setText("YOU HAVE SELECT RED COLOR"); getContentPane().setBackground(Color.red); } if(e.getActionCommand()=="GREEN") { tf.setText("YOU HAVE SELECT GREEN COLOR"); getContentPane().setBackground(Color.green); } if(e.getActionCommand()=="BLUE") { tf.setText("YOU HAVE SELECT BLUE COLOR"); getContentPane().setBackground(Color.blue); } } } public class Proj1 { public static void main(String[] args) { abc obj=new abc(); }
  • 71. } _________________________________________________________________________ COLOR EVENT importjavax.swing.JButton; importjavax.swing.JFrame; importjavax.swing.JPanel; importjava.awt.Color; importjava.awt.event.ActionEvent; importjava.awt.event.ActionListener; public class ColorFrame { public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); frame.setSize(300, 200); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  • 72. finalJButtonredButton = new JButton ("Red"); finalJButtongreenButton = new JButton ("Green"); finalJButtonblueButton = new JButton ("Blue"); class Listener extends JPanel implements ActionListener { public void actionPerformed(ActionEvent event) { Color color; if (event.getSource() == redButton) { color = Color.red; } else if (event.getSource() == greenButton) { color = Color.green; } else { color = Color.blue; } setBackground(color); System.out.println(color); repaint();
  • 73. } } redButton.addActionListener(new Listener()); greenButton.addActionListener(new Listener()); blueButton.addActionListener(new Listener()); panel.add(new JButton ("Red")); panel.add(new JButton ("Green")); panel.add(new JButton ("Blue")); frame.add(panel); } } __________________________________________________ DATABASE CONNECTION importjava.sql.*; importjava.util.Scanner; public class dbconnection { public static void main(String[] args) throws ClassNotFoundException, SQLException {
  • 74. String s1; String s2; Class.forName("org.apache.derby.jdbc.ClientDriver"); Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/sac","a1","b1"); System.out.println("Connection successful"); Statement st=con.createStatement(); String query = " insert into stud (name, addr)" + " values (?, ?)"; PreparedStatementpst = con.prepareStatement(query); System.out.println("Enter the username and password"); Scanner obj=new Scanner(System.in); s1=obj.next(); s2=obj.next(); pst.setString (1, s1); pst.setString (2, s2); pst.execute(); ResultSet r = st.executeQuery("select * from stud"); System.out.println(“Display all records”); while(r.next()) { System.out.println("username is "+r.getString("uname")); System.out.println("password is "+r.getString("pwd")); } ResultSet r = st.executeQuery("select * from stud"); System.out.println("Enter the search record"); String key=obj.next();
  • 75. while(r.next()) { if(r.getString(1).compareTo(key)==0) { System.out.println("Username is "+r.getString("uname")); System.out.println("Address is "+r.getString("pwd")); } } } } ___________________________________________________________________ EXAM SOFTWARE - PROJECT import java.awt.*; import java.awt.event.*; import javax.swing.*; class OnlineTest extends JFrame implements ActionListener { JLabel l; JRadioButton jb[]=new JRadioButton[5]; JButton b1,b2; ButtonGroup bg; int count=0,current=0,x=1,y=1,now=0;
  • 76. int m[]=new int[10]; OnlineTest(String s) { super(s); l=new JLabel(); add(l); bg=new ButtonGroup(); for(int i=0;i<5;i++) { jb[i]=new JRadioButton(); add(jb[i]); bg.add(jb[i]); } b1=new JButton("Next"); b2=new JButton("Bookmark"); b1.addActionListener(this); b2.addActionListener(this); add(b1);add(b2); set(); l.setBounds(30,40,450,20); jb[0].setBounds(50,80,100,20); jb[1].setBounds(50,110,100,20); jb[2].setBounds(50,140,100,20); jb[3].setBounds(50,170,100,20); b1.setBounds(100,240,100,30);
  • 77. b2.setBounds(270,240,100,30); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(null); setLocation(250,100); setVisible(true); setSize(600,350); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b1) { if(check()) count=count+1; current++; set(); if(current==9) { b1.setEnabled(false); b2.setText("Result"); } } if(e.getActionCommand().equals("Bookmark")) { JButton bk=new JButton("Bookmark"+x); bk.setBounds(480,20+30*x,100,30);
  • 79. if(e.getActionCommand().equals("Result")) { if(check()) count=count+1; current++; //System.out.println("correct ans="+count); JOptionPane.showMessageDialog(this,"correct ans="+count); System.exit(0); } } void set() { jb[4].setSelected(true); if(current==0) { l.setText("Que1: Which one among these is not a primitive datatype?"); jb[0].setText("int");jb[1].setText("Float");jb[2].setText("boolean");jb[3].setText("char"); } if(current==1) { l.setText("Que2: Which class is available to all the class automatically?"); jb[0].setText("Swing");jb[1].setText("Applet");jb[2].setText("Object");jb[3].setText("ActionEvent"); } if(current==2) {
  • 80. l.setText("Que3: Which package is directly available to our class without importing it?"); jb[0].setText("swing");jb[1].setText("applet");jb[2].setText("net");jb[3].setText("lang"); } if(current==3) { l.setText("Que4: String class is defined in which package?"); jb[0].setText("lang");jb[1].setText("Swing");jb[2].setText("Applet");jb[3].setText("awt"); } if(current==4) { l.setText("Que5: Which institute is best for java coaching?"); jb[0].setText("Utek");jb[1].setText("Aptech");jb[2].setText("SSS IT");jb[3].setText("jtek"); } if(current==5) { l.setText("Que6: Which one among these is not a keyword?"); jb[0].setText("class");jb[1].setText("int");jb[2].setText("get");jb[3].setText("if"); } if(current==6) { l.setText("Que7: Which one among these is not a class? "); jb[0].setText("Swing");jb[1].setText("Actionperformed");jb[2].setText("ActionEvent"); jb[3].setText("Button"); } if(current==7)
  • 81. { l.setText("Que8: which one among these is not a function of Object class?"); jb[0].setText("toString");jb[1].setText("finalize");jb[2].setText("equals"); jb[3].setText("getDocumentBase"); } if(current==8) { l.setText("Que9: which function is not present in Applet class?"); jb[0].setText("init");jb[1].setText("main");jb[2].setText("start");jb[3].setText("destroy"); } if(current==9) { l.setText("Que10: Which one among these is not a valid component?"); jb[0].setText("JButton");jb[1].setText("JList");jb[2].setText("JButtonGroup"); jb[3].setText("JTextArea"); } l.setBounds(30,40,450,20); for(int i=0,j=0;i<=90;i+=30,j++) jb[j].setBounds(50,80+i,200,20); } boolean check() { if(current==0) return(jb[1].isSelected()); if(current==1)
  • 83. ______________________________________________________________________ MINI PROJECT import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import javax.swing.JFrame; import javax.swing.*; class abc extends JFrame implements ActionListener { JTextField tf=new JTextField(); public abc() { getContentPane().setBackground(Color.yellow); JLabel l1=new JLabel("Student Name: "); tf.setBounds(115,50,250,30); JLabel l2=new JLabel("Student RegNo: "); tf.setBounds(115,150,250,30);
  • 84. JLabel l3=new JLabel("Subject1: "); tf.setBounds(115,250,250,30); JLabel l4=new JLabel("Subject2: "); tf.setBounds(215,250,250,30); JLabel l5=new JLabel("Subject3: "); tf.setBounds(315,250,250,30); JLabel l6=new JLabel("Subject4: "); tf.setBounds(415,250,250,30); JLabel l7=new JLabel("Subject5: "); tf.setBounds(515,250,250,30); JLabel l8=new JLabel("Subject6: "); tf.setBounds(615,250,250,30); JButton b1=new JButton("INSERT"); b1.setBounds(100,350,80,30); JButton b2=new JButton("TOTAL"); b2.setBounds(200,350,80,30); JButton b3=new JButton("AVERAGE"); b3.setBounds(300,350,80,30); JButton b4=new JButton("RANK");
  • 85. b4.setBounds(400,350,80,30); JButton b5=new JButton("OK"); b5.setBounds(500,350,80,30); JButton b6=new JButton("CANCEL"); b6.setBounds(600,350,80,30); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); add(l1); add(l2); add(l3); add(l4); add(l5); add(l6); add(l7); add(l8); add(b1); add(b2);
  • 86. add(b3); add(b4); add(b5); add(tf); setSize(700,500); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getActionCommand()=="RED") { tf.setText("YOU HAVE SELECT RED COLOR"); getContentPane().setBackground(Color.red); } if(e.getActionCommand()=="GREEN") { tf.setText("YOU HAVE SELECT GREEN COLOR"); getContentPane().setBackground(Color.green); } if(e.getActionCommand()=="BLUE") { tf.setText("YOU HAVE SELECT BLUE COLOR"); getContentPane().setBackground(Color.blue);
  • 87. } } } public class Proj555 { public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("org.apache.derby.jdbc.ClientDriver"); Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/student", "suresh", "p"); } } _________________________________________________________________________ MINI PROJECT-STUDENT MARK DETAILS import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner;
  • 88. import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.*; class abc extends JFrame implements ActionListener { JTextField tf1=new JTextField(); JTextField tf2=new JTextField(); JTextField tf3=new JTextField(); JTextField tf4=new JTextField(); JTextField tf5=new JTextField(); JTextField tf6=new JTextField(); JTextField tf7=new JTextField(); JTextField tf8=new JTextField(); JTextArea ta=new JTextArea(); public abc() { getContentPane().setBackground(Color.yellow); JLabel l1=new JLabel("Student Name: "); l1.setBounds(50,50, 100,30); tf1.setBounds(150,50,250,30);
  • 89. JLabel l2=new JLabel("Student RegNo: "); l2.setBounds(50,150,100, 30); tf2.setBounds(150,150,250,30); JLabel l3=new JLabel("Subject1: "); l3.setBounds(50,250,100, 30); tf3.setBounds(115,250,250,30); JLabel l4=new JLabel("Subject2: "); l4.setBounds(50,250,100, 30); tf4.setBounds(115,350,250,30); JLabel l5=new JLabel("Subject3: "); l4.setBounds(50,350,100, 30); tf5.setBounds(115,450,250,30); JLabel l6=new JLabel("Subject4: "); l6.setBounds(50,450,100, 30); tf6.setBounds(115,550,250,30); JLabel l7=new JLabel("Subject5: "); l7.setBounds(50,550,100, 30); tf7.setBounds(115,650,250,30); JLabel l8=new JLabel("Subject6: ");
  • 90. l8.setBounds(50,650,100, 30); tf8.setBounds(115,750,250,30); JLabel l9=new JLabel("DISPLAY YOUR RECORDS"); l9.setBounds(600,40,100, 30); ta.setBounds(600,80,450,300); JButton b1=new JButton("INSERT"); b1.setBounds(400,400,120,30); JButton b2=new JButton("TOTAL"); b2.setBounds(400,500,120,30); JButton b3=new JButton("AVERAGE"); b3.setBounds(400,600,120,30); JButton b4=new JButton("RANK"); b4.setBounds(500,400,120,30); JButton b5=new JButton("SEARCH"); b5.setBounds(500,500,120,30); JButton b6=new JButton("OK"); b6.setBounds(500,600,80,30); JButton b7=new JButton("CANCEL"); b7.setBounds(600,400,120,30); add(l1); add(l2); add(l3);
  • 92. b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); setSize(800,900); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e) { try { Class.forName("org.apache.derby.jdbc.ClientDriver"); Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/std11", "sachin", "ten"); Statement st = con.createStatement();
  • 93. if(e.getActionCommand()=="INSERT") { getContentPane().setBackground(Color.green); String s1,s2; int m1,m2,m3,m4,m5,m6,t; double avg; s1=tf1.getText(); System.out.println(s1); s2=tf2.getText(); m1=Integer.parseInt(tf3.getText()); m2=Integer.parseInt(tf4.getText()); m3=Integer.parseInt(tf5.getText()); m4=Integer.parseInt(tf6.getText()); m5=Integer.parseInt(tf7.getText()); m6=Integer.parseInt(tf8.getText()); String query = " insert into student11 (name, regno,s1,s2,s3,s4,s5,s6)" + " values (?,?,?,?,?,?,?,?)";
  • 94. PreparedStatement pst = con.prepareStatement(query); pst.setString (1, s1); pst.setString (2, s2); pst.setInt(3, m1); pst.setInt(4, m2); pst.setInt (5, m3); pst.setInt (6, m4); pst.setInt (7, m5); pst.setInt (8, m6); pst.execute(); } if(e.getActionCommand()=="TOTAL") { int t=Integer.parseInt(tf3.getText())+Integer.parseInt(tf4.getText())+Integer.parseInt(tf5.getText())+Integer. parseInt(tf6.getText())+Integer.parseInt(tf7.getText())+Integer.parseInt(tf8.getText()); String query = " insert into student11 (tot)" + " values (?)"; PreparedStatement pst = con.prepareStatement(query); pst.setInt(9, t);
  • 95. } if(e.getActionCommand()=="AVERAGE") { int t=Integer.parseInt(tf3.getText())+Integer.parseInt(tf4.getText())+Integer.parseInt(tf5.getText())+Integer. parseInt(tf6.getText())+Integer.parseInt(tf7.getText())+Integer.parseInt(tf8.getText()); double avg=t/6; String query = " insert into student11 (avg1)" + " values (?)"; PreparedStatement pst = con.prepareStatement(query); pst.setDouble(10, avg); } if(e.getActionCommand()=="DISPLAY") { ResultSet r = null; r = st.executeQuery("select * from student11"); while(r.next()) {
  • 96. ta.setText("Your name is "+r.getString("name")+"n"); ta.setText("Your REGNO is "+r.getString("regno")+"n"); ta.setText("Your total mark is "+r.getString("tot")+"n"); ta.setText("Your average is "+r.getString("avg1")+"n"); } } if(e.getActionCommand()=="SEARCH") { getContentPane().setBackground(Color.red); ResultSet r1 = null; r1 = st.executeQuery("select * from student11"); String key=tf2.getText(); while(r1.next()) { if(r1.getString(2).compareTo(key)==0) { ta.setText("Your name is "+r1.getString("name")+"n"); ta.setText("Your REGNO is "+r1.getString("regno")+"n"); ta.setText("Your total mark is "+r1.getString("tot")+"n");
  • 97. ta.setText("Your average is "+r1.getString("avg1")+"n"); } } } if(e.getActionCommand()=="CANCEL") { getContentPane().setBackground(Color.red); ta.setText(null); tf1.setText(null); tf2.setText(null); tf3.setText(null); tf4.setText(null); tf5.setText(null); tf6.setText(null); tf7.setText(null); tf8.setText(null); } } catch (ClassNotFoundException ex) { Logger.getLogger(abc.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(abc.class.getName()).log(Level.SEVERE, null, ex); } } }
  • 98. public class Proj777 { public static void main(String[] args) { abc obj=new abc(); } } PROJECT import java.awt.Color; import java.awt.TextArea; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;
  • 99. import java.sql.Statement; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.*; class abc extends JFrame implements ActionListener { JTextField tf1=new JTextField(); JTextField tf2=new JTextField(); JTextField tf3=new JTextField(); JTextField tf4=new JTextField(); JTextField tf5=new JTextField(); JTextField tf6=new JTextField(); JTextField tf7=new JTextField(); JTextField tf8=new JTextField(); JTextArea ta=new JTextArea(); public abc() { getContentPane().setBackground(Color.red); JLabel l1=new JLabel("Student Name: "); l1.setBounds(50,50, 100,30);
  • 100. tf1.setBounds(150,50,250,30); JLabel l2=new JLabel("Student RegNo: "); l2.setBounds(50,150,100, 30); tf2.setBounds(150,150,250,30); JLabel l3=new JLabel("Subject1: "); l3.setBounds(50,250,100, 30); tf3.setBounds(115,250,250,30); JLabel l4=new JLabel("Subject2: "); l4.setBounds(50,350,100, 30); tf4.setBounds(115,350,250,30); JLabel l5=new JLabel("Subject3: "); l5.setBounds(50,450,100, 30); tf5.setBounds(115,450,250,30); JLabel l6=new JLabel("Subject4: "); l6.setBounds(50,550,100, 30); tf6.setBounds(115,550,250,30); JLabel l7=new JLabel("Subject5: "); l7.setBounds(50,650,100, 30); tf7.setBounds(115,650,250,30);
  • 101. JLabel l8=new JLabel("Subject6: "); l8.setBounds(50,750,100, 30); tf8.setBounds(115,750,250,30); JLabel l9=new JLabel("DISPLAY YOUR RECORDS"); l9.setBounds(600,40,100, 30); ta.setBounds(600,80,450,300); JButton b1=new JButton("INSERT"); b1.setBounds(400,400,120,30); JButton b2=new JButton("TOTAL"); b2.setBounds(400,500,120,30); JButton b3=new JButton("AVERAGE"); b3.setBounds(400,600,120,30); JButton b4=new JButton("RANK"); b4.setBounds(500,400,120,30); JButton b5=new JButton("SEARCH"); b5.setBounds(500,500,120,30); JButton b6=new JButton("DISPLAY"); b6.setBounds(500,600,80,30); JButton b7=new JButton("CANCEL"); b7.setBounds(600,400,120,30); add(l1);
  • 103. add(ta); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); setSize(800,900); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e) { try { Class.forName("org.apache.derby.jdbc.ClientDriver"); Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/stud11", "suresh", "p"); Statement st = con.createStatement();
  • 104. if(e.getActionCommand()=="INSERT") { getContentPane().setBackground(Color.green); String s1,s2; int m1,m2,m3,m4,m5,m6,t; double avg; s1=tf1.getText(); System.out.println(s1); s2=tf2.getText(); m1=Integer.parseInt(tf3.getText()); m2=Integer.parseInt(tf4.getText()); m3=Integer.parseInt(tf5.getText()); m4=Integer.parseInt(tf6.getText()); m5=Integer.parseInt(tf7.getText()); m6=Integer.parseInt(tf8.getText()); t=m1+m2+m3+m4+m5+m6; avg=(double)t/6;
  • 105. String query = " insert into std (name, reg,s1,s2,s3,s4,s5,s6,tot,avg1)" + " values (?,?,?,?,?,?,?,?,?,?)"; PreparedStatement pst = con.prepareStatement(query); pst.setString (1, s1); pst.setString (2, s2); pst.setInt(3, m1); pst.setInt(4, m2); pst.setInt (5, m3); pst.setInt (6, m4); pst.setInt (7, m5); pst.setInt (8, m6); pst.setInt(9, t); pst.setDouble(10, avg); pst.execute(); } if(e.getActionCommand()=="TOTAL") { getContentPane().setBackground(Color.yellow); } if(e.getActionCommand()=="AVERAGE")
  • 106. { int t=Integer.parseInt(tf3.getText())+Integer.parseInt(tf4.getText())+Integer.parseInt(tf5.getText())+Integer. parseInt(tf6.getText())+Integer.parseInt(tf7.getText())+Integer.parseInt(tf8.getText()); double avg=(double)t/6; String query = " insert into std (avg1)" + " values (?)"; PreparedStatement pst = con.prepareStatement(query); pst.setDouble(10, avg); pst.execute(); } if(e.getActionCommand()=="DISPLAY") { getContentPane().setBackground(Color.green); ResultSet r = null; r = st.executeQuery("select * from std"); String b,c=""; int i=0,l=0; while(r.next()) { b="Your name is "+r.getString("name")+"n"+"Your REGNO is "+r.getString("reg")+"n"+"Your total mark is "+r.getString("tot")+"n"+"Your average is "+r.getString("avg1")+"n";
  • 107. c=c+b; } ta.setText(c); } if(e.getActionCommand()=="SEARCH") { getContentPane().setBackground(Color.pink); ResultSet r1 = null; r1 = st.executeQuery("select * from std"); String key=tf2.getText(); while(r1.next()) { if(r1.getString(2).compareTo(key)==0) { ta.setText("Your name is "+r1.getString("name")+"n"+"Your REGNO is "+r1.getString("reg")+"n"+"Your total mark is "+r1.getString("tot")+"n"+"Your average is "+r1.getString("avg1")+"n"); }
  • 108. } } if(e.getActionCommand()=="CANCEL") { getContentPane().setBackground(Color.red); ta.setText(null); tf1.setText(null); tf2.setText(null); tf3.setText(null); tf4.setText(null); tf5.setText(null); tf6.setText(null); tf7.setText(null); tf8.setText(null); } } catch (ClassNotFoundException ex) { Logger.getLogger(abc.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(abc.class.getName()).log(Level.SEVERE, null, ex); } } }
  • 109. public class Pr1 { public static void main(String[] args) { abc obj=new abc(); } } 11. Create a student registration form using swing components. package regform; import java.awt.Color; import javax.swing.*; class simpleframe extends JFrame { public simpleframe() { setSize(600,300); setTitle("login"); setLocation(100,100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setBackground(Color.red);
  • 110. simplepanel sp=new simplepanel(); add(sp); } } class simplepanel extends JPanel { public simplepanel() { JLabel l1=new JLabel("NAME :"); add(l1); JTextField tf1=new JTextField(10); add(tf1); JLabel l2=new JLabel("ADDRESS :"); add(l2); JTextArea ta=new JTextArea(5,50); add(ta); JLabel l3=new JLabel("GENDER :"); add(l3); JRadioButton rb1=new JRadioButton("MALE"); add(rb1); JRadioButton rb2=new JRadioButton("FEMALE"); add(rb2); JLabel l4=new JLabel("DEPARTMENT :"); add(l4);
  • 111. JCheckBox cb1=new JCheckBox("CSE"); add(cb1); JCheckBox cb2=new JCheckBox("ECE"); add(cb2); JCheckBox cb3=new JCheckBox("CIVIL"); add(cb3); JLabel l5=new JLabel("COLLEGE :"); add(l5); JComboBox cb=new JComboBox(); cb.addItem("SIT"); cb.addItem("KLNCE"); cb.addItem("KLNIT"); cb.addItem("VCET"); cb.addItem("KCET"); cb.addItem("MEPCO"); add(cb); JButton b1=new JButton("OK"); add(b1); JButton b2=new JButton("CANCEL"); add(b2); } }
  • 112. public class Regform { public static void main(String[] args) { simpleframe ob=new simpleframe(); } } Sample input and output:
  • 113. Create a form with three buttons names as RED, GRREN, and BLUE. When you click on RED any one button the background color will be changes to the appropriate color. [CO4-AP] Program: package swing11; import java.awt.*; import java.awt.Color; import javax.swing.*; import java.awt.event.*; class abc extends JFrame implements ActionListener { JTextField tf=new JTextField(); abc() { getContentPane().setBackground(Color.white); tf.setBounds(115,50,250,40); JButton b1=new JButton("RED"); b1.setBounds(100,120,80,30); JButton b2=new JButton("GREEN"); b2.setBounds(200,120,80,30); JButton b3=new JButton("BLUE"); b3.setBounds(300,120,80,30); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this);
  • 114. add(b1); add(b2); add(b3); add(tf); setSize(400,300); setLayout(null); setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getActionCommand()=="RED") { tf.setText("YOU HAVE SELECT RED COLOR"); getContentPane().setBackground(Color.red); } if(e.getActionCommand()=="GREEN") { tf.setText("YOU HAVE SELECT GREEN COLOR"); getContentPane().setBackground(Color.green); } if(e.getActionCommand()=="BLUE") { tf.setText("YOU HAVE SELECT BLUE COLOR"); getContentPane().setBackground(Color.blue);
  • 115. } } } public class Swing11 { public static void main(String[] args) { abc ob=new abc(); } } Sample input and output: