CS8392-UnivKey (NOVl18)
CS8392-UnivKey (NOVl18)
CS8392-UnivKey (NOVl18)
PART-A
1 Define Objects and Classes in Java
Each class is a collection of data and the function that manipulate the data.The data
components of the class are called data fields and the function components of the class are
called member functions or methods. The class that contains main function is called main
class.
Object is an instance of a class. The objects represent real world entity. The
objects are used to provide a practical basis for the real world. Objects are used
to understand the real world. The object can be declared by specifying the name
of the class.
2 Define Access Specifier.
Java Access Specifiers (also known as Visibility Specifiers) regulate access to classes, fields and
methods in java. These specifiers determine whether a field or method in c lass, can be used or
invoked by another method in another class or sub-class. Access Specifiers can be used to restrict
access.There are 4 types of java access modifiers: Private, Default, Protected and Public
3 What is object cloning?
It is the process of duplicating an object so that two identical objects will exist in the memory at the
same time.
4 What is Class Hierarchy? Give example?
The class hierarchy defines the inheritance relationship between the classes. The root of the class
hierarchy is the class Object. Every class in Java directly or indirectly extends (inherits from) this
class. In single inheritance, a class is derived from one direct superclass. In Java, multiple inheritance
is not supported; a class can only have one direct superclass.
5 Define Runtime Exceptions.
Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions are
unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the
programmers to be civilized, and specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else
under throwable is checked.
6 What is the use of assert keyword?
An assert statement is used to declare an expected boolean condition in a program. If the program is
running with assertions enabled, then the condition is checked at runtime. If the condition is false,
the Java runtime system throws an AssertionError .
7 What is Multithreading?
Multithreading is a conceptual programming concept where a program(process) is divided into two
or more subprograms(process), which can be implemented at the same time in parallel. A
multithreaded program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution.
8 What is the need for generic code?
Code that uses generics has many benefits over non-generic code: Stronger type checks at compile
time. A Java compiler applies strong type checking to generic code and issues errors if the code
violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be
difficult to find.
9 What is meant by window adapter classes?
The class WindowAdapter is an abstract (adapter) class for receiving window events. All methods of
this class are empty. This class is convenience class for creating listener objects.
10 Enumerate the features of AWT in Java.
A collection of graphical user interface (GUI) components that were implemented using native-
platform versions of the components. These components provide that subset of functionality which is
common to all native platforms. Largely supplanted by the Project Swing component set.
PART B –(5*13=65 marks)
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 1 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
11 a
Explain the Characteristics of OOPs
(i)
Encapsulation – Encapsulation is capturing data and keeping it safely and securely from
outside interfaces.
Inheritance- This is the process by which a class can be derived from a base class with all
features of base class and some of its own. This increases code reusability.
Polymorphism- This is the ability to exist in various forms. For example an operator can be
overloaded so as to add two integer numbers and two floats.
Abstraction- The ability to represent data at a very conceptual level without any details.
Some key features of the Object Oriented programming are:
- Emphasis on data rather than procedure
- Programs are divided into entities known as objects
- Data Structures are designed such that they characterize objects
- Functions that operate on data of an object are tied together in data structures
- Data is hidden and cannot be accessed by external functions
- Objects communicate with each other through functions
- New data and functions can be easily added whenever necessary
- Follows bottom up design in program design
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 2 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which
is used to load Java classes into the Java Virtual Machine dynamically. It adds security
by separating the package for the classes of the local file system from those that are
imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access
right to objects.
o Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
Robust simply means strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32
and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode
is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java
is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
Distributed
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 3 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
Here, the name of the method is addNumbers. When the method addNumbers is called, the
code within the method is executed, and the variable z is printed.
Parameters of a Method
When following the method to make cake, the ingredients like sugar and butter are combined
and processed to make the final product. Similarly, Java methods have parameters (like
ingredients) or data that are inputted or passed into the method. The method uses these
parameter values to do the necessary data manipulation and processing. The method then
usually returns the final value after all the necessary data processing is successfully
performed.
In this example, m and n are parameters. The Java method subtractNumbers finds the
difference between m and n and saves the result in a new variable p. The values of the
parameters m and n are used to generate the new variable p that is printed out on the
computer screen.
The parameters of a method are declared within parentheses following the method name. If
there is more than one parameter, they are separated by commas. Both the data type and the
variable name (int m, int n) are specified for the parameters.
11b State the purpose of finalize() method in java? With an example explain how finalize()
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 4 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
(ii) method can be used in java program.
finalize() method is a protected and non-static method of java.lang.Object class. This method
will be available in all objects you create in java. This method is used to perform some final
operations or clean up operations on an object before it is removed from the memory. you can
override the finalize() method to keep those operations you want to perform before an object
is destroyed. Here is the general form of finalize() method.
// finalize cal
System.out.println("Finalizing...");
cal.finalize();
System.out.println("Finalized.");
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 5 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
In above diagram, Class B extends only Class A. Class A is a super class and Class B is a
Sub-class.
2. Multiple Inheritance:
In Multiple Inheritance, one class extending more than one class. Java does not support
multiple inheritance.
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 6 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
As per above example, all the public and protected members of Class A are inherited into
Class D, first via Class B and secondly via Class C.
Java Inheritance Example
class Doctor {
void Doctor_Details() {
System.out.println("Doctor Details...");
}
}
int max = 0;
int min = 100;
int sum = 0;
int avg ;
int counter =0;
boolean repeat ;
while (repeat =true)
{
System.out.println("Enter Name : ");
name = input.next();
System.out.println("Enter Grade : ");
grade = input.nextInt();
if (grade == -1 )
{
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 8 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
avg = sum / counter;
System.out.println(" result = :");
System.out.println(exellent +"\n"+ veryGgood +"\n"+ good +"\n"+
pass +"\n"+fail);
System.out.println("maximum = "+ max +"\t");
System.out.println("minimum = "+ min +"\t");
System.out.println("\tAverage = " +avg);
System.exit(0);
}
switch (grade/10)
{
case 100:
case 9 :
exellent += "\n"+ name + "\t" +grade+"\n";
break;
case 8 :
veryGgood += "\n" + name + "\t" +grade +"\n";
break ;
case 7 :
good += "\n" + name + "\t" +grade +"\n";
break;
case 6:
case 5:
pass += "\n" + name + "\t" +grade +"\n";
break;
default:
fail +="\n" + name + "\t" +grade +"\n";
break;
}
}
}
13a Explain the different types of Exceptions and the exception hierarchy in java with
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 9 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
appropriate examples.
Java being an object oriented programming language, whenever an error occurs while
executing a statement, creates an exception object and then the normal flow of the program
halts and JRE tries to find someone that can handle the raised exception. The exception object
contains a lot of debugging information such as method hierarchy, line number where the
exception occurred, type of exception etc. When the exception occurs in a method, the process
of creating the exception object and handing it over to runtime environment is
called “throwing the exception”. Once runtime receives the exception object, it tries to find
the handler for the exception. Exception Handler is the block of code that can process the
exception object. The logic to find the exception handler is simple – starting the search in the
method where error occurred, if no appropriate handler found, then move to the caller
method and so on. So if methods call stack is A->B->C and exception is raised in method C,
then the search for appropriate handler will move from C->B->A. If appropriate exception
handler is found, exception object is passed to the handler to process it. The handler is said to
be “catching the exception”. If there are no appropriate exception handler found then
program terminates printing information about the exception.Note that Java Exception
handling is a framework that is used to handle runtime errors only, compile time errors are
not handled by exception handling in java.
Java Exception Handling Keywords
Java provides specific keywords for exception handling purposes, we will look after them first
and then we will write a simple program showing how to use them for exception handling.
1. throw – We know that if any exception occurs, an exception object is getting created and
then Java runtime starts processing to handle them. Sometime we might want to
generate exception explicitly in our code, for example in a user authentication program
we should throw exception to client if the password is null. throw keyword is used to
throw exception to the runtime to handle it.
2. throws – When we are throwing any exception in a method and not handling it, then we
need to use throws keyword in method signature to let caller program know the
exceptions that might be thrown by the method. The caller method might handle these
exceptions or propagate it to it’s caller method using throws keyword. We can provide
multiple exceptions in the throws clause and it can be used with main() method also.
3. try-catch – We use try-catch block for exception handling in our code. try is the start of
the block and catch is at the end of try block to handle the exceptions. We can have
multiple catch blocks with a try and try-catch block can be nested also. catch block
requires a parameter that should be of type Exception.
4. finally – finally block is optional and can be used only with try-catch block. Since
exception halts the process of execution, we might have some resources open that will
not get closed, so we can use finally block. finally block gets executed always, whether
exception occurred or not.
Exception Hierarchy
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 10 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
Example:
class JavaException {
public static void main(String args[]) {
int d = 0;
int n = 20;
try {
int fraction = n / d;
System.out.println("This line will not be Executed");
} catch (ArithmeticException e) {
System.out.println("In the catch Block due to Exception = " + e);
}
System.out.println("End Of Main");
}
}
13 What are input and output streams?Explain them with illustrations.
b Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
InPutStream − The InputStream is used to read data from a source.
OutPutStream − The OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to files and networks but this
tutorial covers very basic functionality related to streams and I/O. We will see the most
commonly used examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are
many classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of
these two classes to copy an input file into an output file −
Example
import java.io.*;
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 11 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
FileInputStream in = null;
try {
in = new FileInputStream("input.txt");
int c;
out.write(c);
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close();
}
Now let's have a file input.txt with the following content –
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put the above code in
CopyFile.java file and do the following –
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 12 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
Java Character streams are used to perform input and output for 16-bit unicode. Though
there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an
input file (having unicode characters) into an output file −
Example
import java.io.*;
FileReader in = null;
try {
in = new FileReader("input.txt");
int c;
out.write(c);
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close();
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 13 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
}
Now let's have a file input.txt with the following content –
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put the above code in
CopyFile.java file and do the following –
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program
can take input from a keyboard and then produce an output on the computer screen. If you
are aware of C or C++ programming languages, then you must be aware of three standard
devices STDIN, STDOUT and STDERR. Similarly, Java provides the following three standard
streams −
Standard Input − This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
Standard Output − This is used to output the data produced by the user's program
and usually a computer screen is used for standard output stream and represented
as System.out.
Standard Error − This is used to output the error data produced by the user's program
and usually a computer screen is used for standard error stream and represented
as System.err.
Following is a simple program, which creates InputStreamReader to read standard input
stream until the user types a "q" −
Example
import java.io.*;
try {
char c;
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 14 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
Let's keep the above code in ReadConsole.java file and try to compile and execute it as shown
in the following program. This program continues to read and output the same character
until we press 'q' –
$javac ReadConsole.java
$java ReadConsole
q
Reading and Writing Files
As described earlier, a stream can be defined as a sequence of data. The InputStream is used
to read data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 15 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
The two important streams are FileInputStream and FileOutputStream, which would be
discussed in this tutorial.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First
we create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.
Sr.No. Method & Description
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 16 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
4 public int read(byte[] r) throws IOException{}
This method reads r.length bytes from the input stream into an array.
Returns the total number of bytes read. If it is the end of the file, -1 will
be returned.
Example
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 17 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
Following is the example to demonstrate InputStream and OutputStream –
import java.io.*;
try {
os.close();
is.close();
} catch (IOException e) {
System.out.print("Exception");
}
The above code would create file test.txt and would write given numbers in binary format.
Same would be the output on the stdout screen.
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 18 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
File Navigation and I/O
There are several other classes that we would be going through to get to know the basics of
File Navigation and I/O.
File Class
FileReader Class
FileWriter Class
Directories in Java
A directory is a File which can contain a list of other files and directories. You use File object
to create directories, to list down files available in a directory. For complete detail, check a list
of all the methods which you can call on File object and what are related to directories.
Creating Directories
There are two useful File utility methods, which can be used to create directories −
The mkdir( ) method creates a directory, returning true on success and false on failure.
Failure indicates that the path specified in the File object already exists, or that the
directory cannot be created because the entire path does not exist yet.
The mkdirs() method creates both a directory and all the parents of the directory.
Following example creates "/tmp/user/java/bin" directory −
Example
import java.io.File;
d.mkdirs();
}
Compile and execute the above code to create "/tmp/user/java/bin".
Note − Java automatically takes care of path separators on UNIX and Windows as per
conventions. If you use a forward slash (/) on a Windows version of Java, the path will still
resolve correctly.
Listing Directories
You can use list( ) method provided by File object to list down all the files and directories
available in a directory as follows –
Example
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 19 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
import java.io.File;
String[] paths;
try {
paths = file.list();
for(String path:paths) {
System.out.println(path);
} catch (Exception e) {
e.printStackTrace();
}
This will produce the following result based on the directories and files available in
your /tmp directory −
Output
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 20 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
test1.txt
test2.txt
ReadDir.java
ReadDir.class
14 a Explain in detail the different states of a thread?
Lifecycle and States of a Thread in Java
A thread in Java at any point of time exists in any one of the following states. A thread lies
only in one of the shown states at any instant:
1. New
2. Runnable
3. Blocked
4. Waiting
5. Timed Waiting
6. Terminated
The diagram shown below represent various states of a thread at any instant of time.
Image source: Core Java Vol 1, 9th Edition, Horstmann, Cay S. & Cornell, Gary_2013
Life Cycle of a thread
1. New Thread: When a new thread is created, it is in the new state. The thread has not yet
started to run when thread is in this state. When a thread lies in the new state, it’s code is
yet to be run and hasn’t started to execute.
2. Runnable State: A thread that is ready to run is moved to runnable state. In this state, a
thread might actually be running or it might be ready run at any instant of time. It is the
responsibility of the thread scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to each individual thread.
Each and every thread runs for a short while and then pauses and relinquishes the CPU
to another thread, so that other threads can get a chance to run. When this happens, all
such threads that are ready to run, waiting for the CPU and the currently running thread
lies in runnable state.
3. Blocked/Waiting state:When a thread is temporarily inactive, then it’s in one of the
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 21 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
following states:
Blocked
Waiting
For example, when a thread is waiting for I/O to complete, it lies in the blocked state. It’s
the responsibility of the thread scheduler to reactivate and schedule a blocked/waiting
thread. A thread in this state cannot continue its execution any further until it is moved
to runnable state. Any thread in these states do not consume any CPU cycle.
A thread is in the blocked state when it tries to access a protected section of code that is
currently locked by some other thread. When the protected section is unlocked, the
schedule picks one of the thread which is blocked for that section and moves it to the
runnable state. Whereas, a thread is in the waiting state when it waits for another thread
on a condition. When this condition is fulfilled, the scheduler is notified and the waiting
thread is moved to runnable state.
If a currently running thread is moved to blocked/waiting state, another thread in the
runnable state is scheduled by the thread scheduler to run. It is the responsibility of
thread scheduler to determine which thread to run.
4. Timed Waiting: A thread lies in timed waiting state when it calls a method with a time
out parameter. A thread lies in this state until the timeout is completed or until a
notification is received. For example, when a thread calls sleep or a conditional wait, it is
moved to timed waiting state.
5. Terminated State: A thread terminates because of either of the following reasons:
Because it exists normally. This happens when the code of thread has entirely
executed by the program.
Because there occurred some unusual erroneous event, like segmentation fault or an
unhandled exception.
A thread that lies in terminated state does no longer consumes any cycles of CPU.
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed..."); }
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
} }
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}
start();
new Thread(){
public void run(){c.deposit(10000);}
}start();
}}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 23 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
15 State and explain the basic of AWT Event handling in detail.
a Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The java.awt.event package provides many event classes and
Listener interfaces for event handling.
Java Event classes and Listener interfaces
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
o Button - public void addActionListener(ActionListener a){}
o MenuItem - public void addActionListener(ActionListener a){}
o TextField - public void addActionListener(ActionListener a){}, public void
addTextListener(TextListener a){}
o TextArea - public void addTextListener(TextListener a){}
o Checkbox - public void addItemListener(ItemListener a){}
o Choice - public void addItemListener(ItemListener a){}
o List - public void addActionListener(ActionListener a){}, public void
addItemListener(ItemListener a){}
15 Describe in detail about the different layout in Java GUI.Which layout is the default one?
b Java LayoutManagers
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west
and center. Each region (area) may contain one component only. It is the default layout of
frame or window. The BorderLayout provides five constants for each region:
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 25 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");;
12. JButton b4=new JButton("WEST");;
13. JButton b5=new JButton("CENTER");;
14.
15. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.CENTER);
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23. }
24. public static void main(String[] args) {
25. new Border();
26. }
27. }
download this example
Part C – (1*15=15)
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 26 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 27 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
} else {
System.out
.println(client.getName()
+""
+ "doesn't have enough money for withdraw from account "
+ number);
}
System.out.println(client.getName() + " withdrawal value: "
+ balance + " from account " + number);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return "Account " + number + " balance: " + balance;
}
}
Client Class
public class Client {
private String name;
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 28 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
}
Main Class
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
public Main(Client c) {
client = c;
}
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 29 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
@Override
public void run() {
for (int i = 0; i < CLIENT_ITERATIONS; i++) {
Account acc = bank.getRandomAccount();
clientWork();
acc.withdraw(client, randAmount());
clientWork();
acc.deposit(client, randAmount());
}
System.out.println("#Account balance: " + Account.getBalance());
}
}
16 Code a java program to implement the following:Create four checkboxes.The initial state
b of the first box should be in the checked state.The status of each check box should be
displayed.when we change the state of a check box,status should be display is updated.
import java.awt.*;
import java.awt.event.*;
public AwtControlDemo(){
prepareGUI();
}
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 30 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
chkApple.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Apple Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
chkMango.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Mango Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
chkPeer.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Peer Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
chkgrape.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Grape Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 31 of 32
CS8392-Object Oriented Programming Department of CSE Nov/Dec 18
controlPanel.add(chkApple);
controlPanel.add(chkMango);
controlPanel.add(chkPeer);
controlPanel.add(chkgrape);
mainFrame.setVisible(true);
}
}
St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 32 of 32