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