Java
Java
5. What is the name of the root class for all objects in java?
7. If a class is declared without any access modifiers, where may the class be accessed?
10. What happens if both super class and sub class have a field with same name?
13. What is the difference between final, finally and finalize() in Java?
Ans Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent [Link] idea behind inheritance in java is that you can create new
classes that are built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of parent class, and you can add new methods and fields [Link]
we talk about inheritance, the most commonly used keyword would be extends and
implements. By using these keywords we can make one object acquire the properties of
another object. Inheritance represents the IS-A relationship, also known as parent-
child relationship.
The extends keyword indicates that you are making a new class that derives from an existing
[Link] the terminology of Java, a class that is inherited is called a super class. The new class
is called a subclass
Q2).What are the types of inheritance?
Ans: There are 5 types of inheritance.
2. Multilevel Inheritance : One class is extended by a class and that class in turn is
extended by another class thus forming a chain of inheritance.
4. Multiple Inheritance : One class extends more than one classes. (Java does not
support multiple inheritance.)
[Link]
[Link]
extends is used for developing inheritance between two classes and two interfaces.
implements keyword is used to developed inheritance between interface and class.
As shown in the figure given below, a class extends another class, an interface
extends another interface but a class implements an interface.
Ans : All the classes written in JAVA make use of inheritance. If a root class is not specified
for a class then it means it is derived from a root class name "Object".
Object is the base class for all the classes, by default. That means if parent class is not
provided then the object class will be its parent class.
Q6). Define the term sub class? What You Can Do in a Subclass?
Ans :A subclass inherits all of the public and protected members of its parent, no matter what
package the subclass is in. If the subclass is in the same package as its parent, it also inherits
the package-private members of the parent. You can use the inherited members as is, replace
them, hide them, or supplement them with new members:
1. The inherited fields can be used directly, just like any other fields.
2. You can declare a field in the subclass with the same name as the one in the
superclass, thus hiding it (not recommended).
3. You can declare new fields in the subclass that are not in the superclass.
4. The inherited methods can be used directly as they are.
5. You can write a new instance method in the subclass that has the same signature as
the one in the superclass, thus overriding it.
6. You can write a new static method in the subclass that has the same signature as the
one in the superclass, thus hiding it.
7. You can declare new methods in the subclass that are not in the superclass.
8. You can write a subclass constructor that invokes the constructor of the superclass,
either implicitly or by using the keyword super.
Q7) .If a class is decared without any access modifiers, where may the class be accessed?
Ans : A class that is declared without any access modifies is said to have a package or
friendly access. This means that the class can only be accessed by other classes and interfaces
that are defined within the same package.
For example:
class MyPrivate
string key="12345";
Ans :The super keyword is similar to this keyword following are the scenarios where the
super keyword is used.
Q10). What happens if both super class and sub class have a field with same name?
Ans :Super class field will be hidden in the sub class. You can access hidden super class field
in sub class using super key word If a class is inheriting the properties of another class. And
if the members of the super class have the names same as the sub class, to differentiate these
variables we use super keyword as shown below.
[Link]
[Link]();
Ans : Yes. A private field or method or inner class belongs to its declared class and hides
from its subclasses. there is no way for private stuff to have a runtime overloading or
overriding (polymorphism) features.
Ans: Overridden methods must have the same name, argument list, and return type. The
overriding method may not limit the access of the method it overrides. The overriding
method may not throw any exceptions that may not be thrown by the overridden method.
Q13) .What is the difference between final, finally and finalize() in Java?
Finally - handles exception. The finally block is optional and provides a mechanism to clean
up regardless of what happens within the try block (except [Link](0) call). Use the
finally block to close files or to release other system resources like database connections,
statements etc.
finalize() - method helps in garbage collection. A method that is invoked before an object is
discarded by the garbage collector, allowing it to clean up its state. Should not be used to
release non-memory resources like file handles, sockets, database connections etc
because Java has only a finite number of these resources and you do not know when the
garbage collection is going to kick in to release these non-memory resources through the
finalize() method.
Abstract classes may or may not contain abstract methods ie., methods with out body
( public void get(); )
But, if a class have at least one abstract method, then the class must be declared
abstract.
To use an abstract class you have to inherit it from another class, provide
implementations to the abstract methods in it.
If you inherit an abstract class you have to provide implementations to all the abstract
methods in it.
Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation of
that method to be determined by child classes, you can declare the method in the parent class
as abstract.
You have to place the abstract keyword before the method name in the method
declaration.
class XX extends X {
// implements the remaining method in Y
}
In this case, class X must be abstract because it does not fully implement Y, but class XX
does, in fact, implement Y.
LONG ANSWER QUESTIONS
Disadvantages: Since inheritance inherits everything from the super class and interface it
may make the subclass to clustering and sometimes error prone when dynamic overriding or
dynamic overloading in some situation. In addition the inheritance may make peers hardly
understand your code if they don't know how your super class acts and add learning curve to
the process of development.
Usually when you want to use a functionality of a class you may use subclass to inherits such
function or use an instance of this class in your class. Which is better depends on your
specification.
1) Single Inheritance
Single inheritance is damn easy to understand. When a class extends another one class only
then we call it a single inheritance. The below flow diagram shows that class B extends only
one class which is A. Here A is a parent class of B and B would be a child class of A.
Class A
{
public void methodA()
{
[Link]("Base class method");
}
}
Class B extends A
{
public void methodB()
{
[Link]("Child class method");
}
public static void main(String args[])
{
B obj = new B();
[Link](); //calling super class method
[Link](); //calling local method
}
}
2) Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than
one base class. The inheritance we learnt earlier had the concept of one base class or parent.
The problem with “multiple inheritance” is that the derived class will have to manage the
dependency on two base classes.
Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple
inheritance often leads to problems in the hierarchy. This results in unwanted complexity
when further extending the class.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritance is supported in C++.
3) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a
derived class, thereby making this derived class the base class for the new class. As you can
see in below flow diagram C is subclass or child class of B and B is a child class of A.
Class X{
public void methodX()
{
[Link]("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
[Link]("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
[Link]("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
[Link](); //calling grand parent class method
[Link](); //calling parent class method
[Link](); //calling local method
}
}
4) Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below example class
B,C and D inherits the same class A. A is parent class (or base class) of B,C & D.
5) Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination of Single and Multiple
inheritance. A typical flow diagram would look like below. A hybrid inheritance can be
achieved in the java in a same way as multiple inheritance can be!! Using interfaces. yes you
heard it right. By using interfaces you can have multiple as well as hybrid inheritance in Java.
Q3). Explain briefly member access rules? Where are they used?
Ans :The basic Accessibility Modifiers are of 4 types in Java. They are
1. public
2. protected
3. package/default
4. private
1. static
2. abstract
3. final
4. synchronized
5. transient
6. native
7. volatile
public keyword
If class member is “public” then it can be accessed from anywhere. The member
variable or method is accessed globally. This is simplest way to provide access to
class members. Usually class variables are kept as private and getter-setter methods
are provided to work with them.
private keyword
If class member is “private” then it will be accessible only inside the same class. This is the
most restricted access and the class member will not be visible to the outer world. Usually we
keep class variables as private and methods that are intended to be used only inside the class
as private.
protected keyword
If class member is “protected” then it will be accessible only to the classes in the same
package and to the subclasses. This modifier is less restricted from private but more restricted
from public access. Usually we use this keyword to make sure the class variables are
accessible only to the subclasses.
y: accessible
n: not accessible
Only 2 basic access modifiers are applicable for Top-level Classes & Interfaces. They are
Public and Package/Default modifiers.
Public: If top level class or interface within a package is declared as Public, then it is
accessible both inside and outside of the package.
Default: If no access modifier is specified in the declaration of the top level class or
interface, then it is accessible only within package level. It is not accessible in other
packages or sub packages.
Access Modifiers is the way of specifying the accessibility of a class and its members with
respective to other classes and members.
Access Modifiers for Top-level Classes & Interfaces: public, default, abstract, final
Access Modifiers for Members: public Members, protected Members, default Members,
private Members, static Members, final Members, abstract Methods, synchronized Methods,
native Methods, transientFields,volatileFields.
Access Modifiers for Nested Classes & Interfaces: Nested Interfaces, Nested Classes, Static
member classes, Non-Static member classes, Local classes, Anonymous classes.
Ans :Polymorphism is the capability of a method to do different things based on the object
that it is acting upon. In other words, polymorphism allows you define one interface and have
multiple implementations. I know it sounds confusing. Don’t worry we will discuss this in
detail.
It is a feature that allows one interface to be used for a general class of actions.
An operation may exhibit different behaviour in different instances.
The behaviour depends on the types of data used in the operation.
It plays an important role in allowing objects having different internal structures to
share the same external interface.
Polymorphism is extensively used in implementing inheritance.
Polymorphism could be static and dynamic both. Overloading is static polymorphism while,
overriding is dynamic polymorphism.
Overloading in simple words means two methods having same method name but takes
different input parameters. This called static because, which method to be invoked
will be decided at the time of compilation
Overriding means a derived class is implementing a method of its super class.
There are two types of polymorphism in java- Runtime polymorphism( Dynamic
polymorphism) and Compile time polymorphism (static polymorphism).
In a class hierarchy, when a method in a subclass has the same name and type signature as
a method in its superclass, then the method in the subclass is said to override the method in
the superclass. When an overridden method is called from within its subclass, it will always
refer to the version of that method defined by the subclass. The version of the method
defined by the superclass will be hiddenExample:
Output:
1
Gokaraju Rangaraju Institute of Engineering and Technology
Department of Computer Science and Engineering
Year/Semester: II / II Academic year: 2015-16
Tutorial Sheet: III-2 Question & Answers
SHORT ANSWER QUESTIONS
Process Thread
A process has separate virtual Threads are entities within a process. All threads
address space. Two processes of a process share its virtual address space and
running on the same system at the system resources but they have their own stack
same time do not overlap each created.
other.
Child process creation within from Threads can be created quite easily and no
a parent process requires duplication of resources is required.
duplication of the resources of
parent process
2. What is multithreading?
Ans: Multithreading is a concept in which a program is divided into two or more subprograms,
which can be executed at the same time. The part of a program or subprogram is called a thread
2
and each thread executes separately. Multithreading is a powerful programming tool that enables
towrite efficient programs by making maximum use of the CPU because the CPU idle time can
be reduced. Multithreading in java is a process of executing multiple threads simultaneously. The
aim of multithreading is to achieve the concurrent execution.
3. What the differences between multicasting and multithreading?
Ans:
Multitasking
The ability to run several programs simultaneously, potentially by utilizing several
processors, but predominantly, by time-sharing their resource requirements.
An example is right on your desktop, where you may have a web browser, e-mail client,
audio player, word processor, spreadsheet and who knows what else on the air at the same
time. They can dance in and out of having the processor to themselves many times per
second, because neither of them needs all of it for very long at a time.
Multithreading
The ability to run several functions of a single program simultaneously, predominantly by
utilizing several processors, but potentially, by time-sharing their resource requirements.
An example would be a web server, where the responses to all the incoming requests need
much of the same program logic and state, but different handles on a few things (network
socket, id of caller, whatever else). Sharing the greater bunch of the data pertaining to the
program, but having dedicated copies of a small amount of private things, lets threads be
spawned and destroyed very quickly, and permits an increase in available processing power
to increase the number of requests answered without requiring an additional copies of the
server program to be running.
4. List some imported methods defined by a thread class?
Ans: Methods of Thread class are:
getPriority(), setPriority(), getName(), setName(), isDeamon(), run(), start() , sleep(),
suspend(), resume(), stop(), isAlive(), currentThread(), join(), getState(), yield()
5. Explain thread life cycle?
Ans: Life cycle of thread: State of a thread are classified into five types they are:
1. New State
2. Ready State
3. Running State
4. Waiting State
5. Halted or dead State
3
In new state thread is created and about to enter into main memory. No memory is available if
the thread is in new state. In ready state thread will be entered into main memory, memory
space is allocated for the thread and 1st time waiting for the CPU. Whenever the thread is
under execution it is known as running state. If the thread execution is stopped permanently
than it comes under dead state, no memory is available for the thread if it comes to dead state.
1. Create any user defined class and make that one as a derived class of thread class.
2. Override run() method of Thread class (It contains the logic of perform any operation)
3. Create an object for user-defined thread class and attached that object to predefined
thread class object.
Class_Name obj=new Class_Name Thread t=new Thread(obj);
4. Call start() method of thread class to execute run() method.
5. Save the program with [Link]
4
By implementing Runnable interface:
Runnable is one of the predefined interface in [Link] package, which is containing only
one method and whose prototype is " Public abstract void run ". The run() method of thread
class defined with null body and run() method of Runnable interface belongs to abstract.
Industry is highly recommended to override abstract run() method of Runnable interface but
not recommended to override null body run() method of thread class.
In some of the circumstance if one derived class is extending some type of predefined class
along with thread class which is not possible because java programming never supports
multiple inheritance. To avoid this multiple inheritance problem, rather than extending thread
class we implement Runnable interface.
Create any user defined class and implements runnable interface within that
5
........
}
}
Class_Name obj=new Class_name();
Thread t=new Thread();
[Link]();
Note: While implementing runnable interface it is very mandatory to attach user defined
thread class object reference to predefined thread class object reference. It is optional while
creating thread by extending Thread class.
Synchronized method
Whenever we want to allow only one thread at a time among multiple thread for execution of
a method than that should be declared as synchronized method.
7
Assume that a thread holds a lock on the synchronized object 1 and it is waiting to get a lock on
object 2. Also assume that another thread holds a lock on object 2 and it is waiting to get a lock
on object 1. From this situation it is clear that both threads are waiting for each other to release a
lock. But first thread can’t release the lock until it gets a lock on object 2. And second thread
cant release lock until it gets a lock on object1. Hence both of them cant proceed to success. This
situation is called as deadlock.
The deadlock can be resolved by synchronizing the threads using semaphores.
Semaphores are used for signaling between two threads. They coordinate two threads and resolve
the deadlock condition.
9. What is the use of isAlive() and join() methods?
Ans: isAlive(): Which is return true if the thread is in ready or running or waiting state and
return false if the thread is in new or dead state.
join(): Which can be used to combined more than one thread into a single group signature is
public final void join()throws InterruptedException
try
{
[Link]();
[Link]();
.....
.....
}
Ans: The [Link] class represents a set of threads. It can also include other
thread groups. The thread groups form a tree in which every thread group except the initial
thread group has a parent. This class inherits methods from the [Link] classes.
Class constructors:
S.N. Constructor & Description
1 ThreadGroup(String name)
This constructs a new thread group.
Class methods:
S.N. Method & Description
1 int activeCount()
This method returns an estimate of the number of active threads in this thread
group.
2 int activeGroupCount()
This method returns an estimate of the number of active groups in this thread group.
3 void checkAccess()
This method determines if the currently running thread has permission to modify
this thread group.
9
12. Write a java program to create a simple thread by extending thread class?
10
[Link](5001);
}
catch(InterruptedException ie)
{
[Link]("problem in thread execution");
}
[Link]("Execution status of t1 after completation="+[Link]());
}
}
public MyRunnableThread(){ }
11
[Link](100);
} } }}
[Link]();
[Link](100);
} }
} }
Example Output
Starting Main Thread...
Main Thread: 1
Expl Thread: 2
Main Thread: 3
Expl Thread: 4
Main Thread: 5
Expl Thread: 6
Main Thread: 7
Expl Thread: 8
Main Thread: 9
Expl Thread: 10
Main Thread: 11
End of Main Thread...
12
14. Explain inter-thread communication?
Ans: If you are aware of inter-process communication then it will be easy for you to understand
inter thread communication. Inter thread communication is important when you develop an
application where two or more threads exchange some information.
There are simply three methods and a little trick which makes thread communication possible.
First let's see all the three methods listed below:
These methods have been implemented as final methods in Object, so they are available in all
the classes. All three methods can be called only from within a synchronized context.
MIN-PRIORITY
Which represents the minimum priority that a thread can have.
NORM-PRIORITY
Which represent the default priority that is assigned to a thread.
13
DESCRIPTIVE QUESTIONS/PROGRAMS/EXPERIMENTS
1. Define multithreading? Explain in detail with an example?
Ans: Multithreading is a concept in which a program is divided into two or more subprograms,
which can be executed at the same time. The part of a program or subprogram is called a thread
and each thread executes separately. Multithreading is a powerful programming tool that
enables to write efficient programs by making maximum use of the CPU because the CPU idle
time can be reduced to minimum.
Multithreading is useful in a number of ways. It enables the programmers to do multiple things
at a time. They can divide a large program into threads (subprograms) and execute them in
parallel. Multithreading is very much important in a networked environment in which Java
operates.
Multithreading means running more than one thread at the same time concurrently. The
processor switches between the threads and execute them parallel. The processor execute each
thread so fast that it appears as if they are being done simultaneously.
Multithreading is asynchronous i.e. , any thread can access any resources at any time. If two
threads try to access a shard resource at the same time then there will be no problem. To
prevent this, there is a synchronization concept in java. This synchronization is achieved by
using ‘synchronized’ keyword. While a thread is inside a synchronized method, all the other
threads are made to wait until the thread exit the monitor and release the resource to the next
waiting thread.
For example:
1. New State
2. Ready State
3. Running State
4. Waiting State
5. Halted or dead State
14
New State
If any new thread class is created that represent new state of a thread, In new state thread is
created and about to enter into main memory. No memory is available if the thread is in new
state.
Ready State
In ready state thread will be entered into main memory, memory space is allocated for the
thread and 1st time waiting for the CPU.
Running State
Whenever the thread is under execution known as running state.
Halted or dead State
If the thread execution is stopped permanently than it comes under dead state, no memory is
available for the thread if it comes to dead state.
Note: If the thread is in new or dead state no memory is available but sufficient memory is
available if that is in ready or running or waiting state.
Ans: When we start two or more threads within a program, there may be a situation when
multiple threads try to access the same resource and finally they can produce unforeseen result
due to concurrency issue. For example if multiple threads try to write within a same file then
they may corrupt the data because one of the threads can override data or while one thread is
opening the same file at the same time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one
thread can access the resource at a given point in time. This is implemented using a concept
called monitors. Each object in Java is associated with a monitor, which a thread can lock or
unlock. Only one thread at a time may hold a lock on a monitor.
15
Java programming language provides a very handy way of creating threads and synchronizing
their task by using synchronized blocks. You keep shared resources within this block.
Following is the general form of the synchronized statement:
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the monitor
that the synchronized statement represents. Now we are going to see two examples where we
will print a counter using two different threads. When threads are not synchronized, they print
counter value which is not in sequence, but when we print counter by putting inside
synchronized() block, then it prints counter very much in sequence for both the threads.
class PrintDemo {
public void printCount(){
try {
for(int i = 5; i > 0; i--)
[Link]("Counter --- " + i );
}
catch (Exception e) {
[Link]("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo( String name, PrintDemo pd){
threadName = name;
16
PD = pd;
}
public void run() {
[Link]();
[Link]("Thread " + threadName + " exiting.");
}
public void start ()
{ [Link]("Starting " + threadName );
if (t == null){
t = new Thread (this, threadName);
[Link] (); }
}
}
public class TestThread {
public static void main(String args[])
{ PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
[Link]();
[Link]();
// wait for threads to end
try {
[Link]();
[Link]();
} catch( Exception e) {
[Link]("Interrupted");
}
}
}
This produces different result every time you run this program:
Starting Thread - 1
17
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 5
Counter --- 2
Counter --- 1
Counter --- 4
Thread Thread - 1 exiting.
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
class PrintDemo {
public void printCount()
{ try {
for(int i = 5; i > 0; i--)
[Link]("Counter --- " + i );
}
catch (Exception e) {
[Link]("Thread interrupted."); }
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
18
ThreadDemo( String name, PrintDemo pd)
{ threadName = name;
PD = pd; }
public void run()
{ synchronized(PD) {
[Link]();
}
[Link]("Thread " + threadName + " exiting.");
}
public void start ()
{[Link]("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
[Link] ();
}
}
}
public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
[Link]();
[Link]();
// wait for threads to end
try {
[Link]();
[Link]();
} catch( Exception e) {
[Link]("Interrupted");
}
19
}
}
This produces same result every time you run this program:
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
Ans: Daemon threads in Java are like a service providers for other threads or objects running in
the same process as the daemon thread. Daemon threads are used for background supporting
tasks and are only needed while normal threads are executing. If normal threads are not running
and remaining threads are daemon threads then the interpreter exits.
When a new thread is created it inherits the daemon status of its parent. Normal thread and
daemon threads differ in what happens when they exit. When the JVM halts any remaining
daemon threads are abandoned: finally blocks are not executed, stacks are not unwound – JVM
just exits. Due to this reason daemon threads should be used sparingly and it is dangerous to use
them for tasks that might perform any sort of I/O.
20
Daemon thread is a low priority thread (in context of JVM) that runs in background to
perform tasks such as garbage collection (gc) etc., they do not prevent the JVM from exiting
(even if the daemon thread itself is running) when all the user threads (non-daemon threads)
finish their execution. JVM terminates itself when all user threads (non-daemon threads) finish
their execution, JVM does not care whether Daemon thread is running or not, if JVM finds
running daemon thread (upon completion of user threads), it terminates the thread and after that
shutdown itself.
Properties of Daemon threads:
1. A newly created thread inherits the daemon status of its parent. That’s the reason all
threads created inside main method (child threads of main thread) are non-daemon by
default, because main thread is non-daemon. However you can make a user thread to
Daemon by using setDaemon() methodof thread class.
Just a quick note on main thread: When the JVM starts, it creates a thread called
“Main”. Your program will run on this thread, unless you create additional threads
yourself. The first thing the “Main” thread does is to look for your static void main
(String args[]) method and invoke it. That is the entry-point to your program. If you
create additional threads in the main method those threads would be the child threads of
main thread.
2. Methods of Thread class that are related to Daemon threads:
public void setDaemon(boolean status): This method is used for making a user thread
to Daemon thread or vice versa. For example if I have a user thread t then
[Link](true) would make it Daemon thread. On the other hand if I have a Daemon
thread td then by calling [Link](false) would make it normal thread(user
thread/non-daemon thread).
public boolean isDaemon(): This method is used for checking the status of a thread. It
returns true if the thread is Daemon else it returns false.
3. setDaemon() method can only be called before starting the thread. This method would
throw IllegalThreadStateException if you call this method after [Link]() method.
(refer the example)
Daemon thread example:
Ex:[Link]
This example is to demonstrate the usage of setDaemon() and isDaemon() method.
public class DaemonThreadExample1 extends Thread{
public void run(){
// Checking whether the thread is Daemon or not
21
if([Link]().isDaemon()){
[Link]("Daemon thread executing");
}
else{
[Link]("user(normal) thread executing");
}
}
public static void main(String[] args){
/* Creating two threads: by default they are
* user threads (non-daemon threads)
*/
DaemonThreadExample1 t1=new DaemonThreadExample1();
DaemonThreadExample1 t2=new DaemonThreadExample1();
//Making user thread t1 to Daemon
[Link](true);
//starting both the threads
[Link]();
[Link]();
}
}
Output:
Daemon thread executing
User (normal) thread executing
5. Explain thread group class, methods defined by it? Explain any three of them?
Ans: The [Link] class represents a set of threads. It can also include other
thread groups. The thread groups form a tree in which every thread group except the initial
thread group has a parent.
Class declaration
Following is the declaration for [Link] class:
public class ThreadGroup
extends Object
implements [Link]
Class constructors
S.N. Constructor & Description
22
1 ThreadGroup(String name)
This constructs a new thread group.
Class methods
S.N. Method & Description
1 int activeCount()
This method returns an estimate of the number of active threads in this thread group.
2 int activeGroupCount()
This method returns an estimate of the number of active groups in this thread group.
3 void checkAccess()
This method determines if the currently running thread has permission to modify this
thread group.
4 void destroy()
This method Destroys this thread group and all of its subgroups.
9 int getMaxPriority()
This method returns the maximum priority of this thread group.
10 String getName()
23
This method returns the name of this thread group.
11 ThreadGroup getParent()
This method returns the parent of this thread group.
12 void interrupt()
This method interrupts all threads in this thread group.
13 boolean isDaemon()
This method Tests if this thread group is a daemon thread group.
14 boolean isDestroyed()
This method tests if this thread group has been destroyed.
15 void list()
This method prints information about this thread group to the standard output.
16 boolean parentOf(ThreadGroup g)
This method tests if this thread group is either the thread group argument or one of its
ancestor thread groups.
19 String toString()
This method returns a string representation of this Thread group.
Methods inherited
This class inherits methods from the following classes:
[Link]
24
Gokaraju Rangaraju Institute of Engineering and Technology
Department of Computer Science and Engineering
Year/Semester: II / II Academic year: 2015-16
SUB: OOP THROUGH JAVA
Tutorial Sheet: UNIT 1I-II
PACKAGES & INTERFACES
SHORT ANSWER QUESTIONS:
1) What is a java package?
2) What are the advantages of java packages?
3) Explain the processes of defining a package with example?
4) Explain how to create and access a java package with example?
5) Which package is always imported by default?
6) Can I import same package/class twice? Will the JVM load the package twice at
runtime?
7) Does importing a package imports the sub packages as well? E.g. Does importing
[Link].* also import [Link]?
8) Which package has light weight components?
9) How do we add a class or interface to package with example?
10) What do you know about the Java garbage collector? When does the garbage
collection occur?
11) Does garbage collection guarantee that a program will not run out of memory? What
is the purpose of garbage collection?
12) How does a class implement an interface?
13) How is an abstract class different from interface?-
14) Show to achieve multiple inheritance in Java using interfaces?
15) Why are the interfaces more flexible than abstract classes?
Long answer questions:
1) What are packages? types of packages? what are they used for?
2) How do we import a package?
3) Write short notes on [Link]?
4) Explain the processes of defining an interface?
5) What is a class path?
Ans To create a package is quite easy: simply include a package command as the first
statement
in a Java source file. Any classes declared within that file will belong to the
specifiedpackage. The package statement defines a name space in which classes are stored. If
youomit the package statement, the class names are put into the default package, which has
no name. (This is why you haven’t had to worry about packages before now.) While the
default package is fine for short, sample programs, it is inadequate for real applications. Most
of the time, you will define a package for your code.
This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a
package called MyPackage:
package MyPackage;.
: It helps resolve naming conflicts when different packages have classes with the same
names. This also helps you organize files within your project. For example: [Link]
package do something related to I/O and [Link] package do something to do with
network and so on. If we tend to put all .java files into a single package, as the project
gets bigger, then it would become a nightmare to manage all your files.
We can create a package as follows with package keyword, which is the first keyword
in any Java program followed by import statements. The [Link] package is
imported implicitly by default and all the other packages must be explicitly imported.
package [Link] ;
import [Link];
import [Link];
Example:
package tools;
public class Hammer
{
public void id ()
{
[Link] ("Hammer");
}
}
Points to remember:
1. At most one package declaration can appear in a source file.
2. The package declaration must be the first statement in the unit.
Naming conventions:
A global naming scheme has been proposed to use the internet domain names to uniquely
identify packages. Companies use their reversed Internet domain name in their package
names, like this:
[Link]
Q4).Explain how to create and access a java package with example?
Ans:
The package keyword is used to create a package in java.
1. //save as [Link]
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. [Link]("Welcome to package");
6. }
7. }
Compile java package
If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename
For example
1. javac -d . [Link]
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
Run java package program
You need to use fully qualified name e.g. [Link] etc to run the class.
To Compile: javac -d .
[Link]
To Run: java [Link]
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
Q5).Which package is always imported by default?
Ans: The [Link] package is always imported by default. It is by default loaded internally
by the JVM.
The [Link] class instance represent classes and interfaces in a running Java
[Link] has no public constructor.
The [Link] class wraps a value of the primitive type boolean in an object. An
object of type Boolean contains a single field whose type is boolean.
The [Link] class wraps a value of the primitive type char in an object. An
object of type Character contains a single field whose type is char.
The [Link] class wraps a value of the primitive type int in an object. An object of
type Integer contains a single field whose type is int.
Q6).Can I import same package/class twice? Will the JVM load the package twice at
runtime?
Ans: One can import the same package or same class multiple times. Neither compiler nor
JVM complains anything about it. And the JVM will internally load the class only once no
matter how many times you import the same class.
Q7).Does importing a package imports the sub packages as well? E.g. Does importing
[Link].* also import [Link].*?
Ans: No you will have to import the sub packages explicitly. Importing [Link].* will
import classes in the package bob only. It will not import any class in any of its sub
package’s.
Adds enhancements
JWindowapi to [Link].
package s1;
public class B
{
}
1. Store this [Link] file under the directory s1.
2. Compile [Link] [Link] creation a [Link] file and place it in the directory S1.
Using the same procedure we can also add a non public class to a [Link] the package
S1 contains both the classes A and [Link] below statement is used for importing both the
classes
import s1.*;
Q10). What do you know about the Java garbage collector? When does the garbage
collection occur?
Ans: Each time an object is created in Java, it goes into the area of memory known as heap.
The Java heap is called the garbage collectable heap. The garbage collection cannot be
forced. The garbage collector runs in low memory situations. When it runs, it releases the
memory allocated by an unreachable object. The garbage collector runs on a low priority
daemon (background) thread. We can nicely ask the garbage collector to collect garbage by
calling [Link]() but we can’t force it.
Q11).Does garbage collection guarantee that a program will not run out of memory?
What is the purpose of garbage collection?
Ans: No, it doesn't .it is possible for programs to use up memory resources faster than they
are garbage collected. it is also possible for programs to create objects that are not subject to
garbage collection.
The purpose of garbage collection is to identify and discard objects that are no longer needed
by a program so that their resources may be reclaimed and reused.
Output:
implementation of method1
Ans:
However this method is very time consuming. So normally we use the second method.
import com.myPackage1.myPackage2;
class myClass {
myPackage2 myNewClass= new myPackage2 ();
…
…
…
}
Q2).How do we import a package?
import com.myPackage1.*;
import [Link].* ;
Also, when we use *, only the classes in the package referred are imported, and not the
classes in the sub package.
Points to remember:
1. Sometimes class name conflict may occur. For example:
There are two packages myPackage1 and [Link] of these packages contains a
class with the same name, let it be [Link]. Now both this packages are imported by
some other class.
import myPackage1.*;
import myPackage2.*;
This will cause compiler error. To avoid these naming conflicts in such a situation, we have
to be more specific and use the member’s qualified name to indicate exactly which
[Link] class we want:
2. While creating a package, which needs some other packages to be imported, the package
statement should be the first statement of the program, followed by the import statement.
extends FilterInputStream
extends FilterOutputStream
[Link] :The [Link] class reads text from a character-
input stream, buffering characters so as to provide for the efficient reading of characters,
arrays, and [Link] are the important points about BufferedReader:
The buffer size may be specified, or the default size may be used.
Each read request made of a Reader causes a corresponding read request to be
made of the underlying character or byte stream.
Class declaration
Following is the declaration for [Link] class:
public class BufferedReader
extends Reader
Introduction
[Link] :The [Link] class writes text to a character-
output stream, buffering characters so as to provide for the efficient writing of single
characters, arrays, and [Link] are the important points about BufferedWriter:
The buffer size may be specified, or the default size may be used.
A Writer sends its output immediately to the underlying character or byte
stream.
Class declaration
Following is the declaration for [Link] class:
public class BufferedWriter
extends Writer
extends Object
extends Object
implements Closeable
extends Reader
extends Object
extends Writer
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:
Example:
Let us look at an example that depicts encapsulation:
/* File name : [Link] */
import [Link].*;
//Any number of import statements
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the
specific behaviors of the interface. If a class does not perform all the behaviors of the
interface, the class must
declare itself as abstract.
Aclass uses the implements keyword to implement an interface. The implements keyword
appears in the class
To display the current CLASSPATH variable, use the following commands in Windows
and UNIX (Bourne shell):
• In Windows -> C:\> set CLASSPATHAt the time of compilation, the compiler creates a
different output file for each class, interface and enumeration
defined in it. The base name of the output file is the name of the type, and its extension
[Link]
For example:
// File Name: [Link]
package [Link];
public class Dell
{
}
classUps
{
}
Now, compile this file as follows using -d option:
$javac -d .[Link]
This would put compiled files as follows:
.\com\apple\computers\[Link]
.\com\apple\computers\[Link]
You can import all the classes or interfaces defined in \com\apple\computers\ as follows:
import [Link].*;
Like the .java source files, the compiled .class files should be in a series of directories that
reflect the package name. However, the path to the .class files does not have to be the same as
the path to the .java source files. You can arrange your source and class directories
separately, as:
<path-one>\sources\com\apple\computers\[Link]
<path-two>\classes\com\apple\computers\[Link]
By doing this, it is possible to give the classes directory to other programmers without
revealing your sources. You also need to manage source and class files in this manner so that
the compiler and the Java Virtual Machine (JVM) can find all the types your program uses.
The full path to the classes directory, <path-two>\classes, is called the class path, and is set
with the CLASSPATH system variable. Both the compiler and the JVM construct the path to
your .class files by adding the package name to the class path.
Say <path-two>\classes is the class path, and the package name is [Link], then
the compiler and JVM will look for .class files in <path-two>\classes\com\apple\compters.
A class path may include several paths. Multiple paths should be separated by a semicolon
(Windows) or colon (UNIX). By default, the compiler and the JVM search the current
directory and the JAR file containing the Java platform classes so that these directories are
automatically in the class path.
In UNIX -> % echo $CLASSPATH
To delete the current contents of the CLASSPATH variable, use:
• In Windows -> C:\> set CLASSPATH=
• In UNIX -> % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable:
• In Windows -> set CLASSPATH=C:\users\jack\java\classes
• In UNIX -> % CLASSPATH=/home/jack/java/classes; export CLASSPATH
Gokaraju Rangaraju Institute of Engineering and Technology
Department of Computer Science and Engineering
Year/Semester: II / II Academic year: 2015-16
SUB: OOPS THROUGH JAVA
Tutorial Sheet: UNIT III-1
EXCEPTION HANDLING
Short answer questions
1. What is an Exception
2. What is Exception Handling
3. What are the different types of exceptions
4. What is checked exception list any 3 checked exceptions
5. What is Unchecked exception list any 3 Unchecked exceptions
6. Draw and Explain Exception Hierarchy
7. List the clauses used in java to handle exceptions along with syntax of each clause
8. Explain syntax and differences between throw and throws clauses with examples
9. What is a built-in exception
10. Explain the syntax of multiple catch block with necessary example
11. Write a short note on the following a) FileNotFoundException b) IOException
12. Explain about compile time errors and runtime errors and list out various compile time
and runtime errors
13. How do you create your own exception classes
14. Explain about re-throwing an exception
15. Discuss about the nested try statement with syntax
Descriptive questions/Programs/Experiment
1. Define and explain exception handling?
2. Explain java’s built-in exception?
3. What is exception? What are the different types of exceptions?
4. Explain in detail about checked and unchecked exception with examples?
5. Explain in detail about the usage of try, catch, throw, throws and finally with examples?
1. What is an Exception
Ans: An Exception is an event, which occurs during the execution of a program, that disrupts the
normal flow of the program's Instructions.
Unexpected events (End of File)
Erroneous events (Subscript out of bounds)
When an exception occurs, the method currently executing creates an exception object and passes
it to the runtime system, which looks for a special block of code, called an exception handler, that
deals with the exception
2. What is Exception Handling
Ans: The process of converting system error messages into user friendly error message is known
as Exception handling. This is one of the powerful features of Java to handle run time error and
maintain normal flow of java application.
Handling the exception is nothing but converting system error generated message into user
friendly error message. Whenever an exception occurs in the java application, JVM will create an
object of appropriate exception of sub class and generates system error message, these system
generated messages are not understandable by user so need to convert it into user friendly error
message. You can convert system error message into user friendly error message by using
exception handling feature of java. For Example: when you divide any number by zero then
system generate / by zero so this is not understandable by user so you can convert this message
into user friendly error message like Don't enter zero for denominator.
3. What are the different types of Exceptions
Ans: Type of Exception
1. Checked Exception
2. Un-Checked Exception
2
Checked Exception are the exception which checked at compile-time. These exception are
directly sub-class of [Link] class.
Un-Checked Exception are the exception both identifies or raised at run time. These exceptions
are directly sub-classed of [Link] class.
3
6. Draw the hierarchy of Exception classes
Ans:
7. List the clauses used in java to handle exceptions along with syntax for each clause
Ans: Use Five keywords/clauses for Handling the Exception
try
catch
finally
throws
throw
4
Syntax for handling the exception
try
{
// statements causes problem at run time
}
catch(type of exception-1 object-1)
{
// statements provides user friendly error message
}
catch(type of exception-2 object-2)
{
// statements provides user friendly error message
}
finally
{
// statements which will execute compulsory
}
Syntax of throw
class className
{
returntype method(...) throws Exception_class
{
throw(Exception obj)
}
}
Syntax of throws
5
8. Explain syntax and differences between throw and throws clauses with examples
Ans: throw and throws
Throw: throw is a keyword in java language which is used to throw any user defined exception to
the same signature of method in which the exception is raised.
Note: throw keyword always should exist within method body. whenever method body contain
throw keyword than the call method should be followed by throws keyword.
Syntax
class className
{
returntype method(...) throws Exception_class
{
throw(Exception obj)
}
}
Throws: throws is a keyword in java language which is used to throw the exception which is
raised in the called method to it's calling method throws keyword always followed by method
signature.
Syntax
Throw throws
throws is a keyword which gives an indication
throw is a keyword used for hitting and to the specific method to place the common
1 generating the exception which are exception methods as a part of try and catch
occurring as a part of method body block for generating user friendly error
messages
The place of using throw keyword is The place of using throws is a keyword is
2
always as a part of method body. always as a part of method heading
6
When we use throw keyword as a part of When we write throws keyword as a part of
method body, it is mandatory to the java method heading, it is optional to the java
3
programmer to write throws keyword as programmer to write throw keyword as a part of
a part of method heading method body.
// save by [Link]
package pack;
7
10. Explain the syntax of multiple catch block with necessary example
You can write multiple catch blocks for generating multiple user friendly error messages to make
Example
import [Link].*;
class ExceptionDemo
{
public static void main(String[] args)
{
int a, b, ans=0;
Scanner s=new Scanner([Link]);
[Link]("Enter any two numbers: ");
try
{
a=[Link]();
b=[Link]();
ans=a/b;
[Link]("Result: "+ans);
}
catch(ArithmeticException ae)
{
[Link]("Denominator not be zero");
}
catch(Exception e)
{
[Link]("Enter valid number");
}
}
}
Output
8
11. Write a short note on the following a) FileNotFoundException b) IOException
Ans: a) FileNotFoundException:
If the given filename is not available in a specific location ( in file handling concept) then
This exception is thrown during a failed attempt to open the file denoted by a specified
pathname. Also, this exception can be thrown when an application tries to open a file for writing,
but the file is read only, or the permissions of the file do not allow the file to be read by any
application. This exception extends the IOException class, which is the general class of
exceptions produced by failed or interrupted I/O operations. Also, it implements
the Serializableinterface and finally, the FileNotFoundException exists since the first version of
Java (1.0).
b) IOException:
This is exception is raised whenever problem occurred while writing and reading the data in the
When try to transfer more data but less data are present.
An IOException can occur in a variety of ways when you try to access the local filesystem. In the
following Java code segment an IOException can be thrown by the [Link]() method, so a
try/catch wrapper is used around that portion of code to trap (and arguably deal with) the potential
problem:
9
catch (IOException e)
{
// deal with the error here ...
[Link]();
}
12. Explain about compile time errors and runtime errors and list out various compile time
and runtime errors
Ans: At compile time, when the code does not comply with the Java syntactic and semantics
rules as described in Java Language Specification (JLS), compile-time errors will occurs. The
goal of the compiler is to ensure the code is compliant with these rules. Any rule-violations
detected at this stage are reported as compilation errors.
The best way to get to know those rules is to go through all the sections in the JLS containing
the key words "compile-time error". In general, these rules include syntax checking:
declarations, expressions, lexical parsing, file-naming conventions etc; exception handling: for
checked exceptions; accessibility, type-compatibility, name resolution: checking to see all
named entities - variables, classes, method calls etc. are reachable through at least one of the
declared path; etc.
When the code compiles without any error, there is still chance that the code will fail at run
time. The errors only occurs at run time are call run time errors. Run time errors are those that
passed compiler's checking, but fails when the code gets executed. There are a lot of causes may
result in runtime errors, such as incompatible type-casting, referencing an invalid index in an
array, using an null-object, resource problems like unavailable file-handles, out of memory
situations, thread dead-locks, infinite loops(not detected!), etc.
10
The following are some common runtime errors:
11
14. Explain about re-throwing an exception
Ans: When you catch an exception, it's possible to rethrow it. This is just the same as if you hadn't
caught it in the first place - the exception will continue to bubble up through the layers until it reaches
some other code that catches it (or it reaches the top of the stack and the program exits).
So why would you do this? Well, it means you have temporary access to the exception at the point
where you caught it. One situation I've used this in is where I want to log the fact that an error has
occurred, but the real error handling is happening at a higher level. You'd only do this, though, if this
local logging could add something useful that the higher level error handling doesn't know about.
1
...
2 try {
3 riskyOperationThatCanThrowAnException(target);
4 }
7 throw ex;
}
8
If any exception occurs in try block then CPU controls comes out to the try block
and executes appropriate catch block.
After executing appropriate catch block, even through we use run time statement,
CPU control never goes to try block to execute the rest of the statements.
Each and every try block must be immediately followed by catch block that is no
intermediate statements are allowed between try and catch block.
Syntax
try
{
.....
12
}
/* Here no other statements are allowed
between try and catch block */
catch()
{
....
}
Each and every try block must contains at least one catch block. But it is highly
recommended to write multiple catch blocks for generating multiple user friendly
error messages.
One try block can contains another try block that is nested or inner try block can be
possible.
Syntax
try
{
.......
try
{
.......
}
}
DESCRIPTIVE QUESTIONS/PROGRAMS/EXPERIMENTS
1. Define and explain exception handling?
Ans: Exception Handling
The process of converting system error messages into user friendly error message is known as
Exception handling. This is one of the powerful features of Java to handle run time error and
maintain normal flow of java application.
Type of Exception
Checked Exception
Un-Checked Exception
Checked Exception are the exception which checked at compile-time. These exception are
directly sub-class of [Link] class.
Only for remember: Checked means checked by compiler so checked exception are checked at
compile-time.
14
Un-Checked Exception are the exception both identifies or raised at run time. These
exceptions are directly sub-classed of [Link] class.
Note: In real time application mostly we can handle un-checked exception.
Only for remember: Un-checked means not checked by compiler so un-checked exceptions
are checked at run-time not compile time.
15
Syntax
try
{
// statements causes problem at run time
}
catch(type of exception-1 object-1)
{
// statements provides user friendly error message
}
catch(type of exception-2 object-2)
{
// statements provides user friendly error message
}
finally
{
// statements which will execute compulsory
}
Java defines several other types of exceptions that relate to its various class libraries. Following
is the list of Java Unchecked RuntimeException.
Exception Description
16
method.
17
3. What is exception? What are the different types of exceptions?
Ans: An Exception is a runtime error that indicates that a problem occurred during programs
execution. A Java exception is an instance of a class derived from throwable. This throwable class
is stored in the [Link] package and subclasses of throwable are contained in different packages.
import [Link];
import [Link];
18
FileReader fr = new FileReader(file);
If you try to compile the above program you will get exceptions as shown below.
C:\>javac FilenotFound_Demo.java
1 error
Note: Since the methods read() and close() of FileReader class throws IOException, you can
observe that compiler notifies to handle IOException, along with FileNotFoundException.
Unchecked exceptions: An Unchecked exception is an exception that occurs at the time
of execution, these are also called as Runtime Exceptions, these include programming
bugs, such as logic errors or improper use of an API. runtime exceptions are ignored at
the time of compilation. For example, if you have declared an array of size 5 in your
program, and trying to call the 6th element of the array then
an ArrayIndexOutOfBoundsExceptionexceptionoccurs.
public class Unchecked_Demo {
int num[]={1,2,3,4};
[Link](num[5]);
If you compile and execute the above program you will get exception as shown below.
Exception in thread "main" [Link]: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
5. Explain in detail about the usage of try, catch, throw, throws and finally with examples?
Ans: try block: Java try block is used to enclose the code that might throw an exception. It must
be used within the method. Java try block must be followed by either catch or finally block.
19
Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Catch block: Java catch block is used to handle the Exception. It must be used after the try block
only. You can use multiple catch block with a single try.
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){[Link](e);}
[Link]("rest of the code...");
}
}
Output:
Exception in thread main [Link]:/ by zero rest of the code. Now, as
displayed in the above example, rest of the code is executed i.e. rest of the code statement is
printed.
throw Keyword
throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub
classes can be thrown. Program execution stops on encountering throw statement, and the closest
catch statement is checked for matching type of exception.
Syntax :
throw ThrowableInstance
Creating Instance of Throwable class
20
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
[Link]("Exception caught");
}
}
public static void main(String args[])
{
avg();
}
}
In the above example the avg() method throw an instance of ArithmeticException, which is
successfully handled using the catch statement.
throws Keyword
Any method capable of causing exceptions must list all the exceptions possible during its
execution, so that anyone calling that method gets a prior knowledge about which exceptions to
handle. A method can do so by using the throws keyword.
Syntax :
type method_name(parameter_list) throws exception_list
{
//definition of method
}
NOTE : It is necessary for all exceptions, except the exceptions of
type Error and RuntimeException, or any of their subclass.
finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of
code always executes whether or not exception has occurred. Using a finally block, lets you run
any cleanup type statements that you want to execute, no matter what happens in the protected
code. A finally block appears at the end of catch block.
Example demonstrating finally Clause
Class ExceptionTest
{
public static void main(String[] args)
{
int a[]= new int[2];
[Link]("out of try");
try
22
{
[Link]("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
[Link]("finally is always executed.");
}
}
}
Output:
Out of try
finally is always executed.
Exception in thread main java. Lang. exception array Index out of bound exception.
You can see in above example even if exception is thrown by the program, which is not handled
by catch block, still finally block will get executed.
23
Gokaraju Rangaraju Institute of Engineering and Technology
Department of Computer Science and Engineering
Year/Semester : II / II Academic year: 2015-16
SUB:OOPS THROUGH JAVA
Tutorial Sheet: UNIT V-1
SWING
Short answer questions
1. Explain the steps ivolved In Jtextfield
2. Write a java program to illustrate Jtextfield
3. Explain about JLabel and constructor of JLable
4. Explain about Jbutton and constructor of jbutton
5. Write a java program using four push buttons and a label. Each button displays an icon
that represents the flag of a country. When a button is pressed, the name of that country is
displayed in the label.
6. Explain about JCheckBox and constructors in it?
7. Write a java program to illustrate JCheckBox
8. Explain about JToggleButton and constructors in it
9. Write a java program to illustrate JtoggleButton
10. Explain about radio buttons and constructors in it
11. Write a java program to illustrate Radio Buttons
Descriptive questions/programs/experiments
[Link] about JComboBox
[Link] in detail about Trees
[Link] in detail about Tables.
4. Explain about Jscrollpane
[Link] about Jtabbedpane
Tutor Faculty HOD
17
Gokaraju Rangaraju Institute of Engineering and Technology
Department of Computer Science and Engineering
19
[Link] about JLabel and constructor of JLable
Ans:JLabel is Swing’s easiest-to-use component. It creates a label and was introduced in the
preceding chapter. Here, we will look at JLabel a bit more closely. JLabel can be used to display
text and/or an icon. It is a passive component in that it does not respond to user input. JLabel
defines several constructors. Here are three of them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
Here, str and icon are the text and icon used for the label. The align argument specifies the
horizontal alignment of the text and/or icon within the dimensions of the label. It must be
one of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING. These
constants are defined in the SwingConstants interface, along with several others used by the
Swing classes.
[Link] about Jbutton and constructor of jbutton
The JButton class provides the functionality of a push button. You have already seen a
simple form of it in the preceding chapter. JButton allows an icon, a string, or both to be
associated with the push button. Three of its constructors are shown here:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the [Link] the button is pressed, an
ActionEvent is generated. Using the ActionEvent object passed to the actionPerformed( ) method
of the registered ActionListener, you can obtain the action command string associated with the
button. By default, this is the string [Link] the button. However, you can set the action
command by calling setActionCommand( ) on the button. You can obtain the action command
by calling getActionCommand( ) on the event object. It is declared like this:
String getActionCommand( ) The action command identifies the button. Thus, when using two
or more buttons within the same application, the action command gives you an easy way to
determine which button was pressed.
20
[Link] a java program using four push buttons and a label. Each button displays an icon
that represents the flag of a country. When a button is pressed, the name of that country is
displayed in the label.
Ans: // Demonstrate an icon-based JButton.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JButtonDemo" width=250 height=450>
</applet>
*/
public class JButtonDemo extends JApplet
implements ActionListener {
JLabel jlab;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add buttons to content pane.
ImageIcon france = new ImageIcon("[Link]");
JButton jb = new JButton(france);
[Link]("France");
[Link](this);
21
add(jb);
ImageIcon germany = new ImageIcon("[Link]");
jb = new JButton(germany);
[Link]("Germany");
[Link](this);
add(jb);
ImageIcon italy = new ImageIcon("[Link]");
jb = new JButton(italy);
[Link]("Italy");
[Link](this);
add(jb);Part III
ImageIcon japan = new ImageIcon("[Link]");
jb = new JButton(japan);
[Link]("Japan");
[Link](this);
add(jb);
// Create and add the label to content pane.
jlab = new JLabel("Choose a Flag");
add(jlab);}
// Handle button events.
public void actionPerformed(ActionEvent ae) {
[Link]("You selected " + [Link]());}}
Output from the button example is shown here:.
22
[Link] about JCheckBox and constructors in it?
Ans: The JCheckBox class provides the functionality of a check box. Its immediate superclass is
JToggleButton, which provides support for two-state buttons, as just described. JCheckBox
defines several constructors. The one used here is
JCheckBox(String str)
It creates a check box that has the text specified by str as a label. Other constructors let you
specify the initial selection state of the button and specify an [Link] the user selects or
deselects a check box, an ItemEvent is generated. You can obtain a reference to the JCheckBox
that generated the event by calling getItem( ) on the ItemEvent passed to the itemStateChanged(
23
) method defined by ItemListener. The easiest way to determine the selected state of a check box
is to call isSelected( ) on the JCheckBox instance.
[Link] a java program to illustrate JCheckBox
// Demonstrate JCheckbox.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JCheckBoxDemo" width=270 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet
implements ItemListener {
JLabel jlab;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add check boxes to the content pane.
JCheckBox cb = new JCheckBox("C");
[Link](this);
add(cb);
cb = new JCheckBox("C++");
24
[Link](this);
add(cb);
cb = new JCheckBox("Java");
[Link](this);
add(cb);
cb = new JCheckBox("Perl");
[Link](this);
add(cb);
// Create the label and add it to the content pane.
add(jlab);}
// Handle item events for the check boxes.
public void itemStateChanged(ItemEvent ie) {
JCheckBox cb = (JCheckBox)[Link]();
if([Link]())
[Link]([Link]() + " is selected");
else
[Link]([Link]() + " is cleared");}}
Output from this example is shown here:
26
<applet code="JToggleButtonDemo" width=200 height=80>
</applet>
*/
public class JToggleButtonDemo extends JApplet {
JLabel jlab;
JToggleButton jtbn;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create a label.
jlab = new JLabel("Button is off.");
// Make a toggle button.
jtbn = new JToggleButton("On/Off");
// Add an item listener for the toggle button.
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if([Link]())
[Link]("Button is on.");
else
[Link]("Button is off.");}
});
// Add the toggle button and label to the content pane.
27
add(jtbn);
add(jlab);}}
The output from the toggle button example is shown here
.
[Link] about radio buttons and constructors in it
Ans: Radio buttons are a group of mutually exclusive buttons, in which only one button can be
selected at any one time. They are supported by the JRadioButton class, which extends
JToggleButton. JRadioButton provides several constructors. The one used in the example is
shown here:
JRadioButton(String str)
Here, str is the label for the button. Other constructors let you specify the initial selection
state of the button and specify an [Link] order for their mutually exclusive nature to be
activated, radio buttons must be configured into a group. Only one of the buttons in the group
can be selected at any [Link] example, if a user presses a radio button that is in a group, any
previously selected button in that group is automatically deselected. A button group is created by
the ButtonGroup class. Its default constructor is invoked for this purpose. Elements are then
added to the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.A JRadioButton generates action
events, item events, and change events each time the button selection changes. Most often, it is
the action event that is handled, which means that you will normally implement the
ActionListener interface. Recall that the only method defined by ActionListener is
actionPerformed( ). Inside this method, you can use a number of different ways to determine
which button was selected. First, you can check its action command by calling
28
getActionCommand( ). By default, the action command is the same as the button label, but you
can set the action command to something else by calling setActionCommand( ) on the radio
button. Second, you can call getSource( ) on the ActionEvent object and check that reference
against the buttons. Finally, you can simply check each radio button to find out which one is
currently selected by calling isSelected( ) on each button. Remember, each time an action event
occurs, it means that the button being selected has changed and that one and only one button will
be selected.
[Link] a java program to illustrate Radio Buttons
Ans: // Demonstrate JRadioButton
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet
implements ActionListener {
JLabel jlab;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
29
// Create radio buttons and add them to content pane.
JRadioButton b1 = new JRadioButton("A");
[Link](this);
add(b1);
JRadioButton b2 = new JRadioButton("B");
[Link](this);
add(b2);
JRadioButton b3 = new JRadioButton("C");
[Link](this);
add(b3);
// Define a button group.
ButtonGroup bg = new ButtonGroup();
[Link](b1);
[Link](b2);
[Link](b3);
// Create a label and add it to the content pane.
jlab = new JLabel("Select One");
add(jlab);}
// Handle button selection.
public void actionPerformed(ActionEvent ae) {
[Link]("You selected " + [Link]());}}
Output from the radio button example is shown here:
30
LONG ANSWER QUESTIONS
32
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);}}
class FlavorsPanel extends JPanel {
public FlavorsPanel() {
JComboBox<String> jcb = new JComboBox<String>();
[Link]("Vanilla");
[Link]("Chocolate");
[Link]("Strawberry");
add(jcb);}}
Output from the tabbed pane example is shown in the following three illustrations:
33
[Link] about JScrollPane?
Ans:JScrollPane is a lightweight container that automatically handles the scrolling of another
component. The component being scrolled can be either an individual component, such as a
table, or a group of components contained within another lightweight container, such as a JPanel.
In either case, if the object being scrolled is larger than the viewable area, horizontal and/or
vertical scroll bars are automatically provided, and the component can be scrolled through the
pane. Because JScrollPane automates scrolling, it usually eliminates the need to manage
individual scroll bars.
The viewable area of a scroll pane is called the viewport. It is a window in which the component
being scrolled is displayed. Thus, the viewport displays the visible portion of the component
being scrolled. The scroll bars scroll the component through the [Link] its default behavior,
a JScrollPane will dynamically add or remove a scroll bar as [Link] example, if the
component is taller than the viewport, a vertical scroll bar is added. If the component will
completely fit within the viewport, the scroll bars are [Link] defines several
constructors. The one used in this chapter is shown here:
JScrollPane(Component comp)
The component to be scrolled is specified by comp. Scroll bars are automatically displayed
when the content of the pane exceeds the dimensions of the [Link] are the steps to follow
to use a scroll pane:
1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.
3. Add the scroll pane to the content pane.
The following example illustrates a scroll pane. First, a JPanel object is created, and 400 buttons
are added to it, arranged into 20 columns. This panel is then added to a scroll pane, and the
34
scroll pane is added to the content pane. Because the panel is larger than the viewport, vertical
and horizontal scroll bars appear automatically. You can use the scroll bars to scroll the buttons
into view.
// Demonstrate JScrollPane.
import [Link].*;
import [Link].*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo extends JApplet {
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {art III
// Add 400 buttons to a panel.
JPanel jp = new JPanel();
[Link](new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
[Link](new JButton("Button " + b));
++b;}}
// Create the scroll pane.
JScrollPane jsp = new JScrollPane(jp);
35
// Add the scroll pane to the content pane.
// Because the default border layout is used,
// the scroll pane will be added to the center.
add(jsp, [Link]);}}
Output from the scroll pane example is shown here:
37
1. Create an instance of JTree.
2. Create a JScrollPane and specify the tree as the object to be scrolled.
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane.
The following example illustrates how to create a tree and handle selections. The program
creates a DefaultMutableTreeNode instance labeled "Options". This is the top node of the tree
hierarchy. Additional tree nodes are then created, and the add( ) method is called to connect these
nodes to the tree. A reference to the top node in the tree is provided as the argument to the JTree
constructor. The tree is then provided as the argument to the JScrollPane constructor. This scroll
pane is then added to the content pane. Next, a label is created and added to the content pane.
The tree selection is displayed in this label. To receive selection events from the tree, a
TreeSelectionListener is registered for the tree. Inside the valueChanged( ) method, the path to
the current selection is obtained and displayed.
// Demonstrate JTree.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JTreeDemo" width=400 height=200>
</applet>
*/
public class JTreeDemo extends JApplet {
JTree tree;
JLabel jlab;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
38
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Create top node of tree.
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
// Create subtree of "A".
DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
[Link](a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
[Link](a1);rt III
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
[Link](a2);
// Create subtree of "B"
DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
[Link](b);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
[Link](b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
[Link](b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
[Link](b3);
// Create the tree.
tree = new JTree(top);
// Add the tree to a scroll pane.
JScrollPane jsp = new JScrollPane(tree);
// Add the scroll pane to the content pane.
add(jsp);
// Add the label to the content pane.
jlab = new JLabel();
39
add(jlab, [Link]);
// Handle tree selection events.
[Link](new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent tse) {
[Link]("Selection is " + [Link]());}});}}
Output from the tree example is shown here:
40
column, the heading also provides the mechanism by which the user can change the size of a
column or change the location of a column within the table. JTable does not provide any
scrolling capabilities of its own. Instead, you will normally wrap a JTable inside a JScrollPane.
JTable supplies several constructors. The one used here is JTable(Object data[ ][ ], Object
colHeads[ ]) Here, data is a two-dimensional array of the information to be presented, and
colHeads is a one-dimensional array with the column [Link] relies on three models.
The first is the table model, which is defined by the TableModel interface. This model defines
those things related to displaying data in a two-dimensional format. The second is the table
column model, which is represented by TableColumnModel. JTable is defined in terms of
columns, and it is TableColumnModel that specifies the characteristics of a column. These two
models are packaged in [Link]. The third model determines how items are selected,
and it is specified by the ListSelectionModel, which was described when JList was discussed.
A JTable can generate several different events. The two most fundamental to a table’s operation
are ListSelectionEvent and TableModelEvent. A ListSelectionEvent is generated when the user
selects something in the table. By default, JTable allows you to select one or more complete
rows, but you can change this behavior to allow one or more columns, or one or more individual
cells to be selected. A TableModelEvent is fired when that table’s data changes in some way.
Handling these events requires a bit more work than it does to handle the events generated by the
previously described components and is beyond the scope of this book. However, if you simply
want to use JTable to display data (as the following example does), then you don’t need to
handle any [Link] are the steps required to set up a simple JTable that can be used to
display data:
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content [Link] III
The following example illustrates how to create and use a simple table. A one-dimensional array
of strings called colHeads is created for the column headings. A two-dimensional array of strings
called data is created for the table cells. You can see that each element in the array is an array of
three strings. These arrays are passed to the JTable constructor. The table is added to a scroll
41
pane, and then the scroll pane is added to the content pane. The table displays the data in the data
array. The default table configuration also allows the contents of a cell to be edited. Changes
affect the underlying array, which is data in this case.
// Demonstrate JTable.
import [Link].*;
import [Link].*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
public class JTableDemo extends JApplet {
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Initialize column headings.
String[] colHeads = { "Name", "Extension", "ID#" };
// Initialize data.
Object[][] data = {
{ "Gail", "4567", "865" },
{ "Ken", "7566", "555" },
{ "Viviane", "5634", "587" },
{ "Melanie", "7345", "922" },
{ "Anne", "1237", "333" },
{ "John", "5656", "314" },
42
{ "Matt", "5672", "217" },
{ "Claire", "6741", "444" },
{ "Erwin", "9023", "519" },
{ "Ellen", "1134", "532" },
{ "Jennifer", "5689", "112" },
{ "Ed", "9030", "133" },
{ "Helen", "6751", "145" }
};
// Create the table.
JTable table = new JTable(data, colHeads);
// Add the table to a scroll pane.
JScrollPane jsp = new JScrollPane(table);
// Add the scroll pane to the content pane.
add(jsp);}}
Output from this example is shown here:
43
of the JToggleButton [Link] implements AbstractButton. In addition to creating
standard toggle buttons, JToggleButton is a superclass for two other Swing components that also
represent two-state [Link], JToggleButton defines the basic functionality of all two-state
components. JToggleButton defines several constructors. The one used by the example in this
section is shown here:
JToggleButton(String str)
To handle item events, you must implement the ItemListener interface. Each time an item event
is generated, it is passed to the itemStateChanged( ) method defined by ItemListener. Inside
itemStateChanged( ), the getItem( ) method can be called on the ItemEvent object to obtain a
reference to the JToggleButton instance that generated the event. It is shown here:
Object getItem( )
A reference to the button is returned. You will need to cast this reference to JToggleButton.
The easiest way to determine a toggle button’s state is by calling the isSelected( ) method
(inherited from AbstractButton) on the button that generated the event. It is shown here:
boolean isSelected( )
It returns true if the button is selected and false otherwise.
Here is an example that uses a toggle button. Notice how the item listener works. It
simply calls isSelected( ) to determine the button’s state.
// Demonstrate JToggleButton.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JToggleButtonDemo" width=200 height=80>
</applet>
*/
public class JToggleButtonDemo extends JApplet {
JLabel jlab;
JToggleButton jtbn;
public void init() {
try {
44
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());Part III
// Create a label.
jlab = new JLabel("Button is off.");
// Make a toggle button.
jtbn = new JToggleButton("On/Off");
// Add an item listener for the toggle button.
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if([Link]())
[Link]("Button is on.");
else
[Link]("Button is off.");});
// Add the toggle button and label to the content pane.
add(jtbn);
add(jlab);}}
The output from the toggle button example is shown here
45
46
Gokaraju Rangaraju Institute of Engineering and Technology
Department of Computer Science and Engineering
Year/Semester : II / II Academic year: 2015-16
SUB:OOPS THROUGH JAVA
Tutorial Sheet: UNIT V-2
SWING
Short answer questions
1. Explain the steps ivolved In Jtextfield
2. Write a java program to illustrate Jtextfield
3. Explain about JLabel and constructor of JLable
4. Explain about Jbutton and constructor of jbutton
5. Write a java program using four push buttons and a label. Each button displays an icon
that represents the flag of a country. When a button is pressed, the name of that country is
displayed in the label.
6. Explain about JCheckBox and constructors in it?
7. Write a java program to illustrate JCheckBox
8. Explain about JToggleButton and constructors in it
9. Write a java program to illustrate JtoggleButton
10. Explain about radio buttons and constructors in it
11. Write a java program to illustrate Radio Buttons
Descriptive questions/programs/experiments
[Link] about JComboBox
[Link] in detail about Trees
[Link] in detail about Tables.
4. Explain about Jscrollpane
[Link] about Jtabbedpane
Tutor Faculty HOD
17
Gokaraju Rangaraju Institute of Engineering and Technology
Department of Computer Science and Engineering
19
[Link] about JLabel and constructor of JLable
Ans:JLabel is Swing’s easiest-to-use component. It creates a label and was introduced in the
preceding chapter. Here, we will look at JLabel a bit more closely. JLabel can be used to display
text and/or an icon. It is a passive component in that it does not respond to user input. JLabel
defines several constructors. Here are three of them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
Here, str and icon are the text and icon used for the label. The align argument specifies the
horizontal alignment of the text and/or icon within the dimensions of the label. It must be
one of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING. These
constants are defined in the SwingConstants interface, along with several others used by the
Swing classes.
[Link] about Jbutton and constructor of jbutton
The JButton class provides the functionality of a push button. You have already seen a
simple form of it in the preceding chapter. JButton allows an icon, a string, or both to be
associated with the push button. Three of its constructors are shown here:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the [Link] the button is pressed, an
ActionEvent is generated. Using the ActionEvent object passed to the actionPerformed( ) method
of the registered ActionListener, you can obtain the action command string associated with the
button. By default, this is the string [Link] the button. However, you can set the action
command by calling setActionCommand( ) on the button. You can obtain the action command
by calling getActionCommand( ) on the event object. It is declared like this:
String getActionCommand( ) The action command identifies the button. Thus, when using two
or more buttons within the same application, the action command gives you an easy way to
determine which button was pressed.
20
[Link] a java program using four push buttons and a label. Each button displays an icon
that represents the flag of a country. When a button is pressed, the name of that country is
displayed in the label.
Ans: // Demonstrate an icon-based JButton.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JButtonDemo" width=250 height=450>
</applet>
*/
public class JButtonDemo extends JApplet
implements ActionListener {
JLabel jlab;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add buttons to content pane.
ImageIcon france = new ImageIcon("[Link]");
JButton jb = new JButton(france);
[Link]("France");
[Link](this);
21
add(jb);
ImageIcon germany = new ImageIcon("[Link]");
jb = new JButton(germany);
[Link]("Germany");
[Link](this);
add(jb);
ImageIcon italy = new ImageIcon("[Link]");
jb = new JButton(italy);
[Link]("Italy");
[Link](this);
add(jb);Part III
ImageIcon japan = new ImageIcon("[Link]");
jb = new JButton(japan);
[Link]("Japan");
[Link](this);
add(jb);
// Create and add the label to content pane.
jlab = new JLabel("Choose a Flag");
add(jlab);}
// Handle button events.
public void actionPerformed(ActionEvent ae) {
[Link]("You selected " + [Link]());}}
Output from the button example is shown here:.
22
[Link] about JCheckBox and constructors in it?
Ans: The JCheckBox class provides the functionality of a check box. Its immediate superclass is
JToggleButton, which provides support for two-state buttons, as just described. JCheckBox
defines several constructors. The one used here is
JCheckBox(String str)
It creates a check box that has the text specified by str as a label. Other constructors let you
specify the initial selection state of the button and specify an [Link] the user selects or
deselects a check box, an ItemEvent is generated. You can obtain a reference to the JCheckBox
that generated the event by calling getItem( ) on the ItemEvent passed to the itemStateChanged(
23
) method defined by ItemListener. The easiest way to determine the selected state of a check box
is to call isSelected( ) on the JCheckBox instance.
[Link] a java program to illustrate JCheckBox
// Demonstrate JCheckbox.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JCheckBoxDemo" width=270 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet
implements ItemListener {
JLabel jlab;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add check boxes to the content pane.
JCheckBox cb = new JCheckBox("C");
[Link](this);
add(cb);
cb = new JCheckBox("C++");
24
[Link](this);
add(cb);
cb = new JCheckBox("Java");
[Link](this);
add(cb);
cb = new JCheckBox("Perl");
[Link](this);
add(cb);
// Create the label and add it to the content pane.
add(jlab);}
// Handle item events for the check boxes.
public void itemStateChanged(ItemEvent ie) {
JCheckBox cb = (JCheckBox)[Link]();
if([Link]())
[Link]([Link]() + " is selected");
else
[Link]([Link]() + " is cleared");}}
Output from this example is shown here:
26
<applet code="JToggleButtonDemo" width=200 height=80>
</applet>
*/
public class JToggleButtonDemo extends JApplet {
JLabel jlab;
JToggleButton jtbn;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create a label.
jlab = new JLabel("Button is off.");
// Make a toggle button.
jtbn = new JToggleButton("On/Off");
// Add an item listener for the toggle button.
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if([Link]())
[Link]("Button is on.");
else
[Link]("Button is off.");}
});
// Add the toggle button and label to the content pane.
27
add(jtbn);
add(jlab);}}
The output from the toggle button example is shown here
.
[Link] about radio buttons and constructors in it
Ans: Radio buttons are a group of mutually exclusive buttons, in which only one button can be
selected at any one time. They are supported by the JRadioButton class, which extends
JToggleButton. JRadioButton provides several constructors. The one used in the example is
shown here:
JRadioButton(String str)
Here, str is the label for the button. Other constructors let you specify the initial selection
state of the button and specify an [Link] order for their mutually exclusive nature to be
activated, radio buttons must be configured into a group. Only one of the buttons in the group
can be selected at any [Link] example, if a user presses a radio button that is in a group, any
previously selected button in that group is automatically deselected. A button group is created by
the ButtonGroup class. Its default constructor is invoked for this purpose. Elements are then
added to the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.A JRadioButton generates action
events, item events, and change events each time the button selection changes. Most often, it is
the action event that is handled, which means that you will normally implement the
ActionListener interface. Recall that the only method defined by ActionListener is
actionPerformed( ). Inside this method, you can use a number of different ways to determine
which button was selected. First, you can check its action command by calling
28
getActionCommand( ). By default, the action command is the same as the button label, but you
can set the action command to something else by calling setActionCommand( ) on the radio
button. Second, you can call getSource( ) on the ActionEvent object and check that reference
against the buttons. Finally, you can simply check each radio button to find out which one is
currently selected by calling isSelected( ) on each button. Remember, each time an action event
occurs, it means that the button being selected has changed and that one and only one button will
be selected.
[Link] a java program to illustrate Radio Buttons
Ans: // Demonstrate JRadioButton
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet
implements ActionListener {
JLabel jlab;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
29
// Create radio buttons and add them to content pane.
JRadioButton b1 = new JRadioButton("A");
[Link](this);
add(b1);
JRadioButton b2 = new JRadioButton("B");
[Link](this);
add(b2);
JRadioButton b3 = new JRadioButton("C");
[Link](this);
add(b3);
// Define a button group.
ButtonGroup bg = new ButtonGroup();
[Link](b1);
[Link](b2);
[Link](b3);
// Create a label and add it to the content pane.
jlab = new JLabel("Select One");
add(jlab);}
// Handle button selection.
public void actionPerformed(ActionEvent ae) {
[Link]("You selected " + [Link]());}}
Output from the radio button example is shown here:
30
LONG ANSWER QUESTIONS
32
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);}}
class FlavorsPanel extends JPanel {
public FlavorsPanel() {
JComboBox<String> jcb = new JComboBox<String>();
[Link]("Vanilla");
[Link]("Chocolate");
[Link]("Strawberry");
add(jcb);}}
Output from the tabbed pane example is shown in the following three illustrations:
33
[Link] about JScrollPane?
Ans:JScrollPane is a lightweight container that automatically handles the scrolling of another
component. The component being scrolled can be either an individual component, such as a
table, or a group of components contained within another lightweight container, such as a JPanel.
In either case, if the object being scrolled is larger than the viewable area, horizontal and/or
vertical scroll bars are automatically provided, and the component can be scrolled through the
pane. Because JScrollPane automates scrolling, it usually eliminates the need to manage
individual scroll bars.
The viewable area of a scroll pane is called the viewport. It is a window in which the component
being scrolled is displayed. Thus, the viewport displays the visible portion of the component
being scrolled. The scroll bars scroll the component through the [Link] its default behavior,
a JScrollPane will dynamically add or remove a scroll bar as [Link] example, if the
component is taller than the viewport, a vertical scroll bar is added. If the component will
completely fit within the viewport, the scroll bars are [Link] defines several
constructors. The one used in this chapter is shown here:
JScrollPane(Component comp)
The component to be scrolled is specified by comp. Scroll bars are automatically displayed
when the content of the pane exceeds the dimensions of the [Link] are the steps to follow
to use a scroll pane:
1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.
3. Add the scroll pane to the content pane.
The following example illustrates a scroll pane. First, a JPanel object is created, and 400 buttons
are added to it, arranged into 20 columns. This panel is then added to a scroll pane, and the
34
scroll pane is added to the content pane. Because the panel is larger than the viewport, vertical
and horizontal scroll bars appear automatically. You can use the scroll bars to scroll the buttons
into view.
// Demonstrate JScrollPane.
import [Link].*;
import [Link].*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo extends JApplet {
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {art III
// Add 400 buttons to a panel.
JPanel jp = new JPanel();
[Link](new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
[Link](new JButton("Button " + b));
++b;}}
// Create the scroll pane.
JScrollPane jsp = new JScrollPane(jp);
35
// Add the scroll pane to the content pane.
// Because the default border layout is used,
// the scroll pane will be added to the center.
add(jsp, [Link]);}}
Output from the scroll pane example is shown here:
37
1. Create an instance of JTree.
2. Create a JScrollPane and specify the tree as the object to be scrolled.
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane.
The following example illustrates how to create a tree and handle selections. The program
creates a DefaultMutableTreeNode instance labeled "Options". This is the top node of the tree
hierarchy. Additional tree nodes are then created, and the add( ) method is called to connect these
nodes to the tree. A reference to the top node in the tree is provided as the argument to the JTree
constructor. The tree is then provided as the argument to the JScrollPane constructor. This scroll
pane is then added to the content pane. Next, a label is created and added to the content pane.
The tree selection is displayed in this label. To receive selection events from the tree, a
TreeSelectionListener is registered for the tree. Inside the valueChanged( ) method, the path to
the current selection is obtained and displayed.
// Demonstrate JTree.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JTreeDemo" width=400 height=200>
</applet>
*/
public class JTreeDemo extends JApplet {
JTree tree;
JLabel jlab;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
38
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Create top node of tree.
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
// Create subtree of "A".
DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
[Link](a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
[Link](a1);rt III
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
[Link](a2);
// Create subtree of "B"
DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
[Link](b);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
[Link](b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
[Link](b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
[Link](b3);
// Create the tree.
tree = new JTree(top);
// Add the tree to a scroll pane.
JScrollPane jsp = new JScrollPane(tree);
// Add the scroll pane to the content pane.
add(jsp);
// Add the label to the content pane.
jlab = new JLabel();
39
add(jlab, [Link]);
// Handle tree selection events.
[Link](new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent tse) {
[Link]("Selection is " + [Link]());}});}}
Output from the tree example is shown here:
40
column, the heading also provides the mechanism by which the user can change the size of a
column or change the location of a column within the table. JTable does not provide any
scrolling capabilities of its own. Instead, you will normally wrap a JTable inside a JScrollPane.
JTable supplies several constructors. The one used here is JTable(Object data[ ][ ], Object
colHeads[ ]) Here, data is a two-dimensional array of the information to be presented, and
colHeads is a one-dimensional array with the column [Link] relies on three models.
The first is the table model, which is defined by the TableModel interface. This model defines
those things related to displaying data in a two-dimensional format. The second is the table
column model, which is represented by TableColumnModel. JTable is defined in terms of
columns, and it is TableColumnModel that specifies the characteristics of a column. These two
models are packaged in [Link]. The third model determines how items are selected,
and it is specified by the ListSelectionModel, which was described when JList was discussed.
A JTable can generate several different events. The two most fundamental to a table’s operation
are ListSelectionEvent and TableModelEvent. A ListSelectionEvent is generated when the user
selects something in the table. By default, JTable allows you to select one or more complete
rows, but you can change this behavior to allow one or more columns, or one or more individual
cells to be selected. A TableModelEvent is fired when that table’s data changes in some way.
Handling these events requires a bit more work than it does to handle the events generated by the
previously described components and is beyond the scope of this book. However, if you simply
want to use JTable to display data (as the following example does), then you don’t need to
handle any [Link] are the steps required to set up a simple JTable that can be used to
display data:
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content [Link] III
The following example illustrates how to create and use a simple table. A one-dimensional array
of strings called colHeads is created for the column headings. A two-dimensional array of strings
called data is created for the table cells. You can see that each element in the array is an array of
three strings. These arrays are passed to the JTable constructor. The table is added to a scroll
41
pane, and then the scroll pane is added to the content pane. The table displays the data in the data
array. The default table configuration also allows the contents of a cell to be edited. Changes
affect the underlying array, which is data in this case.
// Demonstrate JTable.
import [Link].*;
import [Link].*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
public class JTableDemo extends JApplet {
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Initialize column headings.
String[] colHeads = { "Name", "Extension", "ID#" };
// Initialize data.
Object[][] data = {
{ "Gail", "4567", "865" },
{ "Ken", "7566", "555" },
{ "Viviane", "5634", "587" },
{ "Melanie", "7345", "922" },
{ "Anne", "1237", "333" },
{ "John", "5656", "314" },
42
{ "Matt", "5672", "217" },
{ "Claire", "6741", "444" },
{ "Erwin", "9023", "519" },
{ "Ellen", "1134", "532" },
{ "Jennifer", "5689", "112" },
{ "Ed", "9030", "133" },
{ "Helen", "6751", "145" }
};
// Create the table.
JTable table = new JTable(data, colHeads);
// Add the table to a scroll pane.
JScrollPane jsp = new JScrollPane(table);
// Add the scroll pane to the content pane.
add(jsp);}}
Output from this example is shown here:
43
of the JToggleButton [Link] implements AbstractButton. In addition to creating
standard toggle buttons, JToggleButton is a superclass for two other Swing components that also
represent two-state [Link], JToggleButton defines the basic functionality of all two-state
components. JToggleButton defines several constructors. The one used by the example in this
section is shown here:
JToggleButton(String str)
To handle item events, you must implement the ItemListener interface. Each time an item event
is generated, it is passed to the itemStateChanged( ) method defined by ItemListener. Inside
itemStateChanged( ), the getItem( ) method can be called on the ItemEvent object to obtain a
reference to the JToggleButton instance that generated the event. It is shown here:
Object getItem( )
A reference to the button is returned. You will need to cast this reference to JToggleButton.
The easiest way to determine a toggle button’s state is by calling the isSelected( ) method
(inherited from AbstractButton) on the button that generated the event. It is shown here:
boolean isSelected( )
It returns true if the button is selected and false otherwise.
Here is an example that uses a toggle button. Notice how the item listener works. It
simply calls isSelected( ) to determine the button’s state.
// Demonstrate JToggleButton.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JToggleButtonDemo" width=200 height=80>
</applet>
*/
public class JToggleButtonDemo extends JApplet {
JLabel jlab;
JToggleButton jtbn;
public void init() {
try {
44
[Link](
new Runnable() {
public void run() {
makeGUI();}});
} catch (Exception exc) {
[Link]("Can't create because of " + exc);}}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());Part III
// Create a label.
jlab = new JLabel("Button is off.");
// Make a toggle button.
jtbn = new JToggleButton("On/Off");
// Add an item listener for the toggle button.
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if([Link]())
[Link]("Button is on.");
else
[Link]("Button is off.");});
// Add the toggle button and label to the content pane.
add(jtbn);
add(jlab);}}
The output from the toggle button example is shown here
45
46
Gokaraju Rangaraju Institute of Engineering and Technology
Department of Computer Science and Engineering
Year/Semester: II / I I Academic year: 2015-16
SUB: OOP THROUGH JAVA
Tutorial Sheet: UNIT I-I
INTRODUCTION
Short answer questions
1. Explain about history of java?
2. What is JVM?What it does?
3. Describe types of Java Applications?
4. List out java buzzwords?
5. Define variables in java?
6. Types of variables in java?
7. Define Array in java with Syntax?
8. What are the operators in java?
9. Define Expressions?
10. What are the control statements in java?
11. Illustrate Type casting with example?
12. Illustrate Type conversion with example?
13. Explain Scope and lifetime of variables briefly?
14. What is native code and byte code?
15. What are the differences between c++,java?
Descriptive questions/programs/experiments
1. Explain in detail about basic Oops concepts?
2. Define Array? And Explain bout types of Arrays with example?
3. Explain about Control statements in java with example?
4. Explain about operators in java?
5. Explain about Data types and variables?
ANS:Java history is interesting to know. The history of java starts from Green Team. Java team
members (also known as Green Team), initiated a revolutionary task to develop a language for
digital devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was suited for
internet programming. Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc.
There are given the major point that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
JVMs are available for many hardware and software platforms ([Link] is plateform dependent).
Loads code
Verifies code
Executes code
Provides runtime environment
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
2) Web Application
An application that runs on the server side and creates dynamic page, is called web application.
Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the advantage
of high level security, load balancing and clustering. In java, EJB is used for creating enterprise
applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.
4. List out java buzzwords?
ANS:Following are the features or buzzwords of Java language which made it popular:
[Link]
[Link]
[Link]
[Link]-Oriented
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
5. Define variables in java?
ANS:Data type variable [ = value][, variable [= value] ...] ;
Here data type is one of Java's datatypes and variable is the name of the variable. To declare
more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java:
char a = 'a'; // the char variable a iis initialized with value 'a'
1. Local Variables
Local variables: Variables defined inside methods, constructors or blocks are called local
variables. Thevariable will be declared and initialized within the method and the variable will be
destroyed when the methodhas completed.
Instance variables: Instance variables are variables within a class but outside any method. These
variablesare instantiated when the class is loaded. Instance variables can be accessed from inside
any method,constructor or blocks of that particular class.
Class variables: Class variables are variables declared within a class, outside any method, with
the static keyword.
ANS: Array
Normally, array is a collection of similar type of elements that have contiguous memory location.
Java array is an object that contains the elements of similar data type. It is a data structure
where we store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based; first element of the array is stored at 0 indexes.
1. dataType[]arr;(or)
2. dataType[]arr;(or)
3. dataType arr[];
Example:
int a[]=new int[5];//declarationandinstantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
• Arithmetic Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Misc Operators
9. Describe operator precedence?
ANS:Operators Precedence
Multiplicative */%
Additive +-
Equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ?:
ANS:Expressions:
An expression is a construct made up of variables, operators, and method invocations, which are
constructed according to the syntax of the language, that evaluates to a single value. You've
already seen examples of expressions, illustrated in bold below:
int cadence = 0;
anArray[0] = 100;
[Link]("Element 1 at index 0: " + anArray[0]);
int result = 1 + 2; // result is now 3
if (value1 == value2)
[Link]("value1 == value2");
ANS:A program executes from top to bottom except when we use control statements, we can
control the order of execution of the program, based on logic and values.
In Java, control statements can be divided into the following three categories:
Selection Statements
Iteration Statements
Jump Statements
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,
Widening Casting(Implicit)
Narrowing Casting(Explicitly done)
Widening Casting(Implicit)
Example :
Example:
public class Main {
public static void main(String args[]) {
int x; // known within main
x = 10;
if (x == 10) { // start new scope
int y = 20; // y is known only to this block
// x and y both known here.
[Link]("x and y: " + x + " " + y);
x = y + 2;
}
[Link]("x is " + x);
}
}
The output:
x and y: 10 20
x is 22
15. What is native code and byte code?
ANS: The native code is code that after you compile it, the compiled code runs on a
specific hardware platform. Byte code is the compiled format for Java programs. Once a
Java program has been converted to byte code, it can be transferred across a network and
executed by Java Virtual Machine (JVM). Byte code files generally have a .class
extension.
16. What are the differences between c++,java?
ANS:Java C++
Java does not support pointers, templates, unions, operator C++ supports structures, unions,
overloading, structures etc. templates, operator overloading,
pointers and pointer arithmetic.
DESCRIPTIVE QUESTIONS
ANS:Normally, array is a collection of similar type of elements that have contiguous memory
location.
Java array is an object the contains elements of similar data type. It is a data structure where we
store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based; first element of the array is stored at 0 index.
Code Optimization: It makes the code optimized; we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size
at runtime. To solve this problem, collection framework is used in java.
Types of Array in java
There are two types of array.
arrayRefVar=new datatype[size];
Class Testarray{
publicstatic void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}
Output: 10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
Class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}
Output: 3 4 5
Passing Array to method in java
We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get minimum number of an array using method.
class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<[Link];i++)
if(min>arr[i])
min=arr[i];
[Link](min);
}
public static void main(String args[]){
int a[]={33,3,4,5};
min(a);//passing array to method
}}
Output:3
1. class Testarray3{
2. public static void main(String args[]){
3. //declaring and initializing 2D array
4. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
5. //printing 2D array
6. for(int i=0;i<3;i++){
7. for(int j=0;j<3;j++){
8. [Link](arr[i][j]+" ");
9. }
10. [Link]();
11. }
12. }}
Output:1 2 3
245
445
Output:caffein
Classes
Abstraction
Encapsulation
Inheritance
Overloading
Exception Handling
Objects: Objects are the basic unit of OOP. They are instances of class, which have data
members and use various member functions to perform tasks.
Class: It is similar to structures in C language. Class can also be defined as user defined data
type but it also contains functions in it. So, class is basically a blueprint for object. It declare &
defines what data variables the object will have and what operations can be performed on the
class's object.
Abstraction: Abstraction refers to showing only the essential features of the application and
hiding the details. In C++, classes provide methods to the outside world to access & use the data
variables, but the variables are hidden from direct access
Encapsulation: It can also be said data binding. Encapsulation is all about binding the data
variables and functions together in class.
Inheritance: Inheritance is a way to reuse once written code again and again. The class which is
inherited is called base calls & the class which inherits is called derived class. So when, a
derived class inherits a base class, the derived class can use all the functions which are defined in
base class, hence making code reusable.
Polymorphism: Polymorphion makes the code more readable. It is a features, which lets is
create functions with same name but different arguments, which will perform differently. That is
function with same name, functioning in different
Iteration Statements
Jump Statements
Selection Statements
Selection statements allow you to control the flow of program execution on the basis of the
outcome of an expression or state of a variable known during runtime.
Selection statements can be divided into the following categories:
The if statements
The first contained statement (that can be a block) of an if statement only executes when the
specified condition is true. If the condition is false and there is not else keyword then the first
contained statement will be skipped and execution continues with the rest of the program. The
condition is an expression that returns a boolean value.
Example
1. package [Link];
2. import [Link];
4. {
6. int age;
9. age = [Link]();
12. }
13. }
Output:
Please enter age:19
Above 18
The if-else statements
In if-else statements, if the specified condition in the if statement is false, then the statemet after
the else keyword (that can be a block) will execute.
Example
1. package [Link];
2. import [Link];
4. {
6. {
7. int age;
13. else
15. }
16. }
Output
Enter age:11
Below 18
The if-else-if statements
This statement following the else keyword can be another if or if-else statement.
That would looks like this:
if(condition)
statements;
else if (condition)
statements;
else if(condition)
statement;
else
statements;
Whenever the condition is true, the associated statement will be executed and the remaining
conditions will be bypassed. If none of the conditions are true then the else block will execute.
Example
1. package [Link];
2. import [Link];
3. public class IfElseIfDemo
4. {
6. {
7. int age;
15. else
17. }
18. }
Output
Enter age:55
Between 36-60
The Switch Statements
The switch statement is a multi-way branch statement. The switch statement of Java is another
selection statement that defines multiple paths of execution of a program. It provides a better
alternative than a large series of if-else-if statements.
Example
1. package [Link];
2. import [Link];
6. {
7. int age;
12. {
15. break;
18. break;
19. default:
21. break;
22. }
23. }
24. }
Output
Please enter age:19
Age:19
An expression must be of a type of byte, short, int or char. Each of the values specified in the
case statement must be of a type compatible with the expression. Duplicate case values are not
allowed. The break statement is used inside the switch to terminate a statement sequence. The
break statement is optional in the switch statement.
Iteration Statements
Repeating the same code fragment several times until a specified condition is satisfied is called
iteration. Iteration statements execute the same set of instructions until a termination condition is
met.
Java provides the following loop for iteration statements:
1. package [Link];
3. {
5. {
6. int i = 0;
7. while ( i < 5 )
8. {
10. i++;
11. }
12. }
13. }
Output
value : : 0
value : : 1
value : : 2
value : : 3
value : : 4
The do-while loop
The only difference between a while and a do-while loop is that do-while evaluates its
expression at the bottom of the loop instead of the top. The do-while loop executes at least one
time then it will check the expression prior to the next iteration.
Example
1. package [Link];
3. {
5. {
6. int i = 0;
7. do
8. {
10. i++;
11. }
13. }
14. }
Output
value : : 0
value : : 1
value : : 2
value : : 3
value : : 4
The for loop
A for loop executes a statement (that is usually a block) as long as the boolean condition
evaluates to true. A for loop is a combination of the three elements initialization statement,
boolean expression and increment or decrement statement.
Syntax:
for(<initialization>;<condition>;<increment or decrement statement>){
<block of code>
}
The initialization block executes first before the loop starts. It is used to initialize the loop
variable.
The condition statement evaluates every time prior to when the statement (that is usually be a
block) executes, if the condition is true then only the statement (that is usually a block) will
execute.
The increment or decrement statement executes every time after the statement (that is usually a
block).
Example
1. package [Link];
3. {
5. {
6. int i = 0;
7. while ( i < 5 )
8. {
10. i++;
11. }
12. }
13. }
Output
value : : 0
value : : 1
value : : 2
value : : 3
value : : 4
The For each loop
This was introduced in Java 5. This loop is basically used to traverse the array or collection
elements.
Example
1. package [Link];
3. {
5. {
6. int[] i =
7. { 1, 2, 3, 4, 5 };
8. for ( int j : i )
9. {
11. }
12. }
13. }
Jump Statements
Jump statements are used to unconditionally transfer the program control to another part of the
program.
Java provides the following jump statements:
break statement
continue statement
return statement
Break Statement
The break statement immediately quits the current iteration and goes to the first statement
following the loop. Another form of break is used in the switch statement.
The break statement has the following two forms:
Unlabeled Break Statement: This is used to jump program control out of the specific loop on the
specific condition.
Example
1. package [Link];
3. {
5. {
7. {
9. if ( var == 3 )
10. break;
11. }
12. }
13. }
Output
var is : : 0
var is : : 1
var is : : 2
var is : : 3
Labeled Break Statement: This is used for when we want to jump the program control out of
nested loops or multiple loops.
Example
1. package [Link];
3. {
5. {
7. {
9. {
11. if ( var1 == 3 )
13. }
14. }
15. }
16. }
Continue Statement
The continue statement is used when you want to continue running the loop with the next
iteration and want to skip the rest of the statements of the body for the current iteration.
The continue statement has the following two forms:
Unlabeled Continue Statement: This statement skips the current iteration of the innermost for,
while and do-while loop.
Example
1. package [Link];
3. {
5. {
7. {
9. {
10. if ( var2 == 2 )
11. continue;
13. }
14. }
15. }
16. }
Labeled Continue Statement: This statement skips the current iteration of the loop with the
specified label.
Example
1. package [Link];
3. {
5. {
7. {
9. {
10. if ( var2 == 2 )
13. }
14. }
15. }
16. }
Return Statement
The return statement is used to immediately quit the current method and return to the calling
method. It is mandatory to use a return statement for non-void methods to return a value.
Example
1. package [Link];
3. {
8. }
9. int returnCall()
10. {
11. return 5;
12. }
13. }
Output
No:5
ANS:Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Show Examples
Relational operators:
There are following relational operators supported by Java language
Show Examples
1 == (equal to)
Checks if the values of two operands are equal or not, if yes then condition becomes
true.
Checks if the values of two operands are equal or not, if values are not equal then
2
condition becomes true.
Example: (A != B) is true.
Checks if the value of left operand is greater than the value of right operand, if yes then
3
condition becomes true.
Checks if the value of left operand is less than the value of right operand, if yes then
4
condition becomes true.
Checks if the value of left operand is greater than or equal to the value of right operand,
5
if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the value of right operand, if
6
yes then condition becomes true.
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
Show Examples
Assume Boolean variables A holds true and variable B holds false, then:
Show Examples
Operator Description
Example: C |= 2 is same as C = C | 2
Miscellaneous Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide
which value should be assigned to the variable. The operator is written as:
variable x = (expression) ? value if true : value if false
Following is the example:
public class Test {
Value of b is : 30
Value of b is : 20
instance of Operator:
This operator is used only for object reference variables. The operator checks whether the object
is of a particular type (class type or interface type). instanceof operator is wriiten as:
( Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side, then the result will be true. Following is the example:
public class Test {
public static void main(String args[]){
String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;
[Link]( result );
}}This would produce the following result:
true
5. Explain about Data types and variables?
ANS:Java Is a Strongly Typed Language
It is important to state at the outset that Java is a strongly typed language. Indeed, part of Java’s
safety and robustness comes from this fact. Let’s see what this means. First, every variable has a
type, every expression has a type, and every type is strictly defined. Second, all assignments,
whether explicit or via parameter passing in method calls, are checked for type compatibility.
There are no automatic coercions or conversions of conflicting types as in some languages. The
Java compiler checks all expressions and parameters to ensure that the types are compatible. Any
type mismatches are errors that must be corrected before the compiler will finish compiling the
class.
The Primitive Types
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. The primitive types are also commonly referred to as simple types, and both terms will
be used in this book. These can be put in four groups:
• Integers This group includes byte, short, int, and long, which are for whole-valued signed
numbers.
• Floating-point numbers This group includes float and double, which represent numbers with
fractional precision.
• Characters This group includes char, which represents symbols in a character set, like letters
and numbers.
• Boolean This group includes boolean, which is a special type for representingtrue/false values.
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and
negative values. Java does not support unsigned, positive-only integers. Many other computer
languages support both signed and unsigned integers. However, Java’s designers felt that
unsigned integers were unnecessary. Specifically, they felt that the concept of unsigned was used
mostly to specify the behavior of the high-order bit, which defines the sign of an integer value.
As you will see in Chapter 4, Java manages the meaning of the highorder bit differently, by
adding a special “unsigned right shift” operator. Thus, the need for an unsigned integer type was
eliminated. The width of an integer type should not be thought of as the amount of storage it
consumes, but rather as the behavior it defines for variables and expressions of that type. The
Java run-time environment is free to use whatever size it wants, as long as the types behave as
you declared them. The width and ranges of these integer types vary widely, as shown in this
table:
Name Width Range
long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127
Let’s look at each type of integer.
byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127.
Variables of type byte are especially useful when you’re working with a stream of data from a
network or file. They are also useful when you’re working with raw binary data that may not be
directly compatible with Java’s other built-in types. Byte variables are declared by use of the
byte keyword.
For example, the following declares two byte variables called b and c:
byte b, c;
short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the leastused
Java type. Here are some examples of short variable declarations:
short s;
short t;
int
The most commonly used integer type is int. It is a signed 32-bit type that has a range from –
2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly
employed to control loops and to index arrays. Although you might think that using a byte or
short would be more efficient than using an int in situations in which the larger range of an int
is not needed, this may not be the case. The reason is that when byte and short values are used in
an expression they are promoted to int when the expression is evaluated. (Type promotion is
described later in this chapter.) Therefore, int is often the best choice when an integer is needed.
long
long is a signed 64-bit type and is useful for those occasions where an int type is not large
enough to hold the desired value. The range of a long is quite large. This makes it useful when
big, whole numbers are needed. For example, here is a program that computes the number of
miles that light will travel in a specified number of days:
// Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
[Link]("In " + days);
[Link](" days light will travel about ");
[Link](distance + " miles.");
}
}
This program generates the following output:
In 1000 days light will travel about 16070400000000 miles.
Clearly, the result could not have been held in an int variable.
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractional precision. For example, calculations such as square root, or transcendentals
such as sine and cosine, result in a value whose precision requires a floatingpoint type. Java
implements the standard (IEEE–754) set of floating-point types and operators. There are two
kinds of floating-point types, float and double, which represent single- and double-precision
numbers, respectively. Their width and ranges are shown here:
Name Width in Bits Approximate Range
double 64 4.9e–324 to 1.8e+308
float 32 1.4e–045 to 3.4e+038
Each of these floating-point types is examined next.
float
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is
faster on some processors and takes half as much space as double precision, but will become
imprecise when the values are either very large or very small. Variables of type float are useful
when you need a fractional component, but don’t require a large degree of precision. For
example, float can be useful when representing dollars and cents. Here are some example float
variable declarations: float hightemp, lowtemp;
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double
precision is actually faster than single precision on some modern processors that have been
optimized for high-speed mathematical calculations. All transcendental math functions, such as
sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many
iterative calculations, or are manipulating large-valued numbers, double is the best choice.
Here is a short program that uses double variables to compute the area of a circle:
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
[Link]("Area of circle is " + a);
}
}
Characters
In Java, the data type used to store characters is char. However, C/C++ programmers beware:
char in Java is not the same as char in C or C++. In C/C++, char is 8 bits wide. This is not the
case in Java. Instead, Java uses Unicode to represent characters. Unicode defines a fully
international character set that can represent all of the characters found in all human languages. It
is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew,
Katakana, Hangul, and many more. For this purpose, it requires 16 bits. Thus, in Java char is a
16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of
characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit character
set, ISO-Latin-1, ranges from 0 to 255. Since Java is designed to allow programs to be written
for worldwide use, it makes sense that it would use Unicode to represent characters. Of course,
the use of Unicode is somewhat inefficient for languages such as English, German, Spanish, or
French, whose characters can easily be contained within 8 bits. But such is the price that must be
paid for global portability. Here is a program that demonstrates char variables:
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
[Link]("ch1 and ch2: ");
[Link](ch1 + " " + ch2);
}
}
This program displays the following output:
ch1 and ch2: X Y
Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that
corresponds to the letter X. As mentioned, the ASCII character set occupies the first 127 values
in the Unicode character set. For this reason, all the “old tricks” that you may have used with
characters in other languages will work in Java, too. Although char is designed to hold Unicode
characters, it can also be used as an integer type on which you can perform arithmetic operations.
For example, you can add two characters together, or increment the value of a character variable.
Consider the following
program:
// char variables behave like integers.
class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
[Link]("ch1 contains " + ch1);
ch1++; // increment ch1
[Link]("ch1 is now " + ch1);
}
}
The output generated by this program is shown here:
ch1 contains X
ch1 is now Y
In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1
containing Y, the next character in the ASCII (and Unicode) sequence
Booleans:
Java has a primitive type, called boolean, for logical values. It can have only one of two possible
values, true or false. This is the type returned by all relational operators, as in the case of a < b.
boolean is also the type required by the conditional expressions that govern the control
statements such as if and for.
Here is a program that demonstrates the boolean type:
// Demonstrate boolean values.
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
[Link]("b is " + b);
b = true;
[Link]("b is " + b);
// a boolean value can control the if statement
if(b) [Link]("This is executed.");
b = false;
if(b) [Link]("This is not executed.");
Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be
changed. For example, Employee, Puppy etc.
Class objects, and various type of array variables come under reference data type.
A reference variable can be used to refer to any object of the declared type or any
compatible type.
Example: Animal animal = new Animal("giraffe");
Java Literals:
A literal is a source code representation of a fixed value. They are represented directly in the
code without any computation.
Literals can be assigned to any primitive type variable. For example:
byte a = 68;
char a = 'A'
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or
octal(base 8) number systems as well.
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number
systems for literals. For example:
String literals in Java are specified like they are in most other languages by enclosing a sequence
of characters between a pair of double quotes. Examples of string literals are:
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For example:
char a = '\u0001';
String a = "\u0001";
Java language supports few special escape sequences for String and char literals as well. They
are:
Character represented
Notation
\n Newline (0x0a)
\r Carriage return (0x0d)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t Tab
\\ Backslash
Here data type is one of Java's datatypes and variable is the name of the variable. To declare
more than one variable of the specified type, you can use a comma-separated list.
char a = 'a'; // the char variable a iis initialized with value 'a'
Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime. These elements are examined next.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
type identifier [ = value ][, identifier [= value ] …];
The type is one of Java’s atomic types, or the name of a class or interface. (Class and interface
types are discussed later in Part I of this book.) The identifier is the name of the variable. You
can initialize the variable by specifying an equal sign and a value. Keep in mind that the
initialization expression must result in a value of the same (or compatible) type as that specified
for the variable. To declare more than one variable of the specified type, use a comma-separated
list. Here are several examples of variable declarations of various types. Note that some
include an initialization
[Link] Variables
Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable will be
destroyed when the methodhas completed.
Instance variables: Instance variables are variables within a class but outside any method.
These variables
are instantiated when the class is loaded. Instance variables can be accessed from inside any
method,constructor or blocks of that particular class.
Class variables: Class variables are variables declared within a class, outside any method, with
the static keyword.s
Gokaraju Rangaraju Institute of Engineering and Technology
Department of Computer Science and Engineering
Year/Semester: II / II Academic year: 2015-16
SUB: OOP THROUGH JAVA
Tutorial Sheet: UNIT I-II
Classes and objects
Short answer questions
1. Explain about public,static,void,main,string[],[Link]()?
2. Define objects in java?
3. Define Classes in Java?
4. Write a Simple Example of class and object?
5. What are the types of constructors?
6. Can constructor perform other tasks instead of initialization?
7. Difference between constructor and method in java?
8. Define “this” keyword in java?
9. Explain about Java Garbage Collection?
10. Illustrate Method Overloading in Java?
11. Can main () method be overloaded?
12. If Java uses the pass-by reference, why won't a swap function work?
13. Why string objects are immutable in java?
14. Define String and String Buffer?
15. Define Immutable string in java?
Descriptive questions/programs/experiments
1. Explain about Method Overloading in java?
2. Explain about Constructor overloading in java?
3. Explain about Parameter passing? Does Java pass parameters by value or by
reference?
4. Explain about String Buffer in java?
void is the return type of the method, it means it doesn't return any value.
String[] args is used for command line argument. We will learn it later.
[Link]() is used print statement. We will learn about the internal working
of [Link] statement later.
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table,
car etc. It can be physical or logical (tengible and intengible). The example of integible object
is banking system.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It
is used to write, so writing is its behavior.
A class is a group of objects that has common properties. It is a template or blueprint from
which objects are created.
data member
method
constructor
block
1. Class <class_name>{
2. data member;
3. method;
4. }
Ans: In this example, we have created a Student class that have two data members id and
name. We are creating the object of the Student class by new keyword and printing the
objects value.
1. Class Student1{
6. [Link]([Link]);
7. [Link]([Link]);
8. }
9. }
Output:0 null
Ans: Constructor in java is a special type of method that is used to initialize the object. Java
constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
2. Parameterized constructor
Syntax: <class_name>(){}
Example of constructor:
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
1. Class Bike1{
2. Bike1(){[Link]("Bike iscreated");}
5. }}
Output:
Bike is created
Ans: There are many differences between constructors and methods. They are given below.
Constructor must not have return type. Method must have return type.
The java compiler provides a default constructor if you Method is not provided by compiler
don't have any constructor. in any case.
Ans: There can be a lot of usage of java this keyword. In java, this is a reference variable
that refers to the current object.
6. this keyword can also be used to return the current class instance.
2. int id;
3. String name;
5. [Link]=id;
6. [Link]=name;
7. }
12. [Link]();
13. [Link]();
14. }
Output111 Karan
222 Aryan
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
2. publicvoidfinalize(){[Link]("object isgarbagecollected");}
6. s1=null;
7. s2=null;
8. [Link]();
9. }
10. }
Output:
object is garbage collected
object is garbage collected
Ans: If a class have multiple methods by same name but different parameters, it is known as
Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behaviour of the method because its name differs. So, we perform method overloading to
figure out the program quickly.
Ans: Yes. the main() method is a special method for a program entry. You can overload
main() method in any ways. But if you change the signature of the main method, the entry
point for the program will be gone.
12. If Java uses the pass-by reference, why won't a swap function work?
Ans: Java does manipulate objects by reference, and all object variables are references.
However, Java doesn't pass method arguments by reference; it passes them by value.
Ans: Because java uses the concept of string [Link] there are 5 reference
variables,all referes to one object "sachin".If one reference variable changes the value of the
object, it will be affected to all the reference variables. That is why string objects are
immutable in java.
Ans: There are many differences between String and StringBuffer. A list of differences
between String and StringBuffer are given below:
String StringBuffer
1) String class is immutable. StringBuffer class is mutable.
String is slow and consumes more memory when you StringBuffer is fast and consumes
2) concat too many strings because every time it creates less memory when you cancat
new instance. strings.
String class overrides the equals() method of Object StringBuffer class doesn't override
3) class. So you can compare the contents of two strings the equals() method of Object
by equals() method. class.
[Link] Immutable String in Java?
Let's try to understand the immutability concept by the example given below:
1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. [Link](" Tendulkar");//concat() method appends the string at the end
5. [Link](s);//will print Sachin because strings are immutable objects
6. }
7. }
Output:Sachin
Ans: If a class have multiple methods by same name but different parameters, it is known as
Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behaviour of the method because its name differs. So, we perform method overloading to
figure out the program quickly.
In this example, we have created two overloaded methods, first sum method performs
addition of two numbers and second sum method performs addition of three numbers.
1. Class Calculation{
2. void sum(int a,int b){[Link](a+b);}
3. void sum(int a,int b,int c){[Link](a+b+c);}
4. public static void main(String args[]){
5. Calculation obj=new Calculation();
6. [Link](10,10,10);
7. [Link](20,20);
8. }
9. }
Output:30
40
In this example, we have created two overloaded methods that differs in data type. The first
sum method receives two integer arguments and second sum method receives two double
arguments.
1. class Calculation2{
2. void sum(int a,int b){[Link](a+b);}
3. void sum(double a,double b){[Link](a+b);}
4. public static void main(String args[]){
5. Calculation2 obj=new Calculation2();
6. [Link](10.5,10.5);
7. [Link](20,20);
8. }
9. }
Output:21.0
40
2. Explain about Constructor methods in java?
Ans: Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
<class_name>(){}
class Bike1{
Bike1(){[Link]("Bike is created");}
Output:
Bike is created
Java parameterized constructor
In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.
class Student4{
int id;
String name;
id = i;
name = n;
[Link]();
[Link]();}}
Output:
Ans: The answer to this question can be a little controversial, as there is some
misunderstanding around how Java works this out. A lot of developers have the wrong idea
that Java treats primitives and objects differently, so you often hear things like “Java passes
primitives by value and object by reference”. Although, this is not entirely true. The reality is
that Java always passes parameters by value
There is only call by value in java, not call by reference. If we call a method passing a value,
it is known as call by value. The changes being done in the called method, is not affected in
the calling method.
In case of call by value original value is not changed. Let's take a simple example
1. class Operation{
2. int data=50;
3. void change(int data){
4. data=data+100;//changes will be in the local variable only
5. }
6. public static void main(String args[]){
7. Operation op=new Operation();
8.
9. [Link]("before change "+[Link]);
10. [Link](500);
11. [Link]("after change "+[Link]);
12. }
13. }
Output:
Before change:50
After change:50
In case of call by reference original value is changed if we made changes in the called
method. If we pass object in place of any primitive value, original value will be changed. In
this example we are passing object as a value. Let's take a simple example:
1. class Operation2{
2. int data=50;
3. void change(Operation2 op){
4. [Link]=[Link]+100;//changes will be in the instance variable
5. }
6. public static void main(String args[]){
7. Operation2 op=new Operation2();
8. [Link]("before change "+[Link]);
9. [Link](op);//passing object
10. [Link]("after change "+[Link]);
11. }
12. }
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity
as length.
Mutable string:
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
The append() method concatenates the given argument with this string.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. [Link]("Java");//now original string is changed
5. [Link](sb);//prints Hello Java
6. }
7. }
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. [Link](1,"Java");//now original string is changed
5. [Link](sb);//prints HJavaello
6. }
7. }
The replace() method replaces the given string from the specified beginIndex and endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. [Link](1,3,"Java");
5. [Link](sb);//prints HJavalo
6. }
7. }
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. [Link](1,3);
5. [Link](sb);//prints Hlo
6. }
7. }
5) StringBuffer reverse() method
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. [Link]();
5. [Link](sb);//prints olleH
6. }
7. }
The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity
is 16, it will be (16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. [Link]([Link]());//default 16
5. [Link]("Hello");
6. [Link]([Link]());//now 16
7. [Link]("java is my favourite language");
8. [Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }
The ensureCapacity() method of StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. [Link]([Link]());//default 16
5. [Link]("Hello");
6. [Link]([Link]());//now 16
7. [Link]("java is my favourite language");
8. [Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. [Link](10);//now no change
10. [Link]([Link]());//now 34
11. [Link](50);//now (34*2)+2
12. [Link]([Link]());//now 70
13. }
14. }
Constructor Description
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
Let's see the simple example of StringTokenizer class that tokenizes a string "my name is
khan" on the basis of whitespace.
1. import [Link];
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while ([Link]()) {
6. [Link]([Link]());
7. }
8. }
9. }
Output:my
Name
Is
khan
Example of nextToken(String delim) method of StringTokenizer class
1. import [Link].*;
2. public class Test {
3. public static void main(String[] args) {
4. StringTokenizer st = new StringTokenizer("my,name,is,khan");
5. s // printing next token
6. [Link]("Next token is : " + [Link](","));
7. }
8. }
Output:Next token is : my
s
Gokaraju Rangaraju Institute of Engineering and Technology
Department of Computer Science and Engineering
Year/Semester: II / II Academic year: 2015-16
SUB: Object-Oriented Programming through JAVA
Tutorial Sheet: UNIT IV-1
Applets
Short answer questions
1. Write short notes on JAVA applet:
2. Write the advantages and drawbacks of applet.
3. Who is responsible to manage the life cycle of an applet?
4. How to run an Applet?
5. What are the two types of Applets:
6. What are two important packages you need to import during applet creation?
7. What is the difference between an Applet and an Application?
8. What are the Applet’s Life Cycle methods? Explain them?
9. What are the Applet’s information methods?
10. What is AppletStub Interface?
11. How to display Image in Applet.
12. How to get the object of Image:
13. What are the other required methods of Applet class to display image:
14. What are the interfaces defined by [Link]?
15. Show the Hierarchy of Applet classes
Descriptive Questions:
1. Explain about Applet Class.
2. How do you invoke an applet?
3. Write the steps for converting a JAVA application into an applet.
4. How to Display Graphics in Applet.
5. Show an Example of using parameter in Applet:
6. What are two important packages you need to import during applet creation?
These import statements bring the classes into the scope of our applet class:
[Link].
[Link].
Without those import statements, the Java compiler would not recognize the classes Applet
and Graphics, which the applet class refers to.
7. What is the difference between an Applet and an Application?
1. Applets can be embedded in HTML pages and downloaded over the Internet
whereas Applications have no special support in HTML for embedding or downloading.
2. Applets can only be executed inside a java compatible container, such as a browser
or appletviewer whereas Applications are executed at command line by [Link] or [Link].
3. Applets execute under strict security limitations that disallow certain
operations(sandbox model security) whereas Applications have no inherent security
restrictions.
4. Applets don't have the main() method as in applications. Instead they operate on an
entirely different mechanism where they are initialized by init(),started by start(),stopped by
stop() or destroyed by destroy().
[Link] are the other required methods of Applet class to display image:
1. public URL getDocumentBase(): is used to return the URL of the document in
which applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.
Descriptive Questions:
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="[Link]" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Note: You can refer to HTML Applet Tag to understand more about calling applet from
HTML.
The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width
and height are also required to specify the initial size of the panel in which an applet runs.
The applet directive must be closed with a </applet> tag.
If an applet takes parameters, values may be passed for the parameters by adding <param>
tags between <applet> and </applet>. The browser ignores text and other tags between the
applet tags.
Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that
appears between the tags, not related to the applet, is visible in non-Java-enabled browsers.
The viewer or browser looks for the compiled Java code at the location of the document. To
specify otherwise, use the codebase attribute of the <applet> tag as shown:
<applet codebase="[Link]
code="[Link]" width="320" height="120">
If an applet resides in a package other than the default, the holding package must be
specified in the code attribute using the period character (.) to separate package/class
components. For example:
<applet code="[Link]"
width="320" height="120">
Ans: It is easy to convert a graphical Java application (that is, an application that uses the
AWT and that you can start with the java program launcher) into an applet that you can
embed in a web page.
Syntax:
public String getParameter(String parameterName)
Example:
import [Link];
import [Link];
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
[Link](str,50, 50);
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
Descriptive Questions:
1. Discuss about some commonly used properties of lists and combo boxes.
2. Write code for event handler of each of the buttons in following application:
3. What major events are associated with the following?
(i) Text Field ii)Password Field iii)Check Box
(iv)Radio Button (v)Scroll Bar (vi) Slider
4. List the Event classes and Listener interfaces
5. How to register an event handler for the object
Foreground Events - Those events which require the direct interaction of [Link]
are generated as consequences of a person interacting with the graphical components
in Graphical User Interface. For example, clicking on a button, moving the mouse,
entering a character through keyboard,selecting an item from list, scrolling the page
etc.
Background Events - Those events that require the interaction of end user are
known as background events. Operating system interrupts, hardware or software
failure, timer expires, an operation completion are the example of background
events.
3. What is the advantage of the event-delegation model over the earlier event-
inheritance model?
The event-delegation model has two advantages over the event-inheritance model. First, it
enables event handling to be handled by objects other than the ones that generate the events
(or their containers). This allows a clean separation between a component's design and its
use. The other advantage of the event delegation model is that it performs much better in
applications where many events are generated. This performance improvement is due to the
fact that the event-delegation model does not have to repeatedly process unhandled events, as
is the case of the event-inheritance model.
List boxes and combo boxes In a list, the user must select items
present a list of choices to the directly from the list whereas in a
user. combo box user can edit it if he/she
whishes.
List allow us to select more than one
item but a combobox allows only
single item selection.
10. What method obtain the current selection of a combo box? Give a code-
example.
getSelectedItem()
Example
private void jComboBox1ActionPerformed([Link] evt)
{
String dur=(String)[Link]();
[Link](dur);
}
11. Write code for the Item event handler of a checkbox (namely incCB) that
increments a variable total and displays it on a label (namely count) if the checkbox is
selected.
Ans:
private void jCheckBox1ActionPerformed([Link] evt)
{
int total=5;
if [Link]()==true)
{
total=total+1;
[Link](Inte
[Link](total));
}
else
{
[Link]([Link](total));
}
}
12. Write code for the event handler of a radio button so that when it is
selected/unselected, its text changes to “ I am selected” or “I am unselected”).
Ans: private void
jRadioButton1ActionPerformed([Link]
onEvent evt) { if([Link]()==true)
{
[Link]("i am selected");
}
else
{
[Link]("i am unselected");
}
}
13. Show the Java AWT Hierarchy
[Link] code for event handler of each of the buttons in following application:
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
[Link](this)
3. Define the methods of the listener interface:
[Link] a java run on any machine? what is needed to run java on a computer?
[Link] compiler and JVM can differentiate constructor and method definitions of both have
same class name?
12. How compiler and JVM can differentiate constructor and method invocations of both
have same class name?
13. Is java Pass by value or pass by reference?
14. How do compiler differentiate overloaded methods from duplicate methods?
15. ) Can we declare one overloaded method as static and another one as non-static?
[Link] about operator precedence?
17. Explain about narrowing conversion?
[Link] a program to print all permutation of string?
19. Which methos is used to perform comparision between the strings that ignores case
difference?
[Link] between string and string tokenizer?
1. What is inheritance? What are the types of inheritances? Discuss the advantages &
disadvantages of inheritance?
2. What is multiple inheritance? How can multiple inheritance be implemented in JAVA?
Explain with example?
3. What is the name of the root class for all objects in JAVA?
4. How can you prevent a method for overriding(Final)?
5. Define abstract class & interface and what is the difference between them?
6. What is an abstract class? What is it importance? How is it designed in JAVA?
Explain with suitable example?
7. What is package? Explain the procedure to create/Define and accessing a package
with the help of an example?
8. Example briefly member access rules? Where are they used?
9. What is the super key word? Where they are used?
10. What is meant by polymorphism? Explain types of polymorphism?
11. What is meant by method signature?
12. Define the term subclass? Why super class members are available to subclass?
13. What does it mean to override a method?
14. How can you call the garbage collector? Explain with example?
15. Explain usage of import statement? Explain with suitable example?
16. Explain any three packages with their classes?
17. Explain briefly [Link]?
18. Explain in detail the various forms of interface implements?
19. How does package resolve name space problems?
20. What is a class path? How the class path is set?
Gokaraju Rangaraju Institute of Engineering and Technology
Department of Computer Science and Engineering
Year/Semester: II / II Academic year: 2015-16
SUB: OOPS THROUGH JAVA
Tutorial Sheet: UNIT III
EXCEPTION HANDLING AND MULTITHREDDING
Short answer questions
1. What is Exception Handling and list different types of exceptions
2. What is Unchecked and checked exception list any 3 in each exception.
3. Draw and Explain Exception Hierarchy
4. List and explain the clauses in exception handling along with syntax of each clause
5. Describe built-in exception in detail
6. Explain the syntax of multiple catch block with necessary example
7. Explain and list out about compile time errors and runtime errors
8. Explain about re-throwing an exception and how to create own exception classes
9. Explain about process and thread in detail?
10. What the differences between multicasting and multithreading?
11. List and explain the imported methods defined by a thread class
12. Explain thread life cycle?
13. Write a short notes on creation of thread
14. What is synchronization?
15. What is deadlock? How is it resolved
16. Explain ThreadGroup class. List some methods defined by it?
17. Explain inter-thread communication?
18. Describe about thread priorities?
19. Explain in detail about creating threads and synchronizing threads?
20. Explain in detail about Daemon threads?
Descriptive questions/Programs/Experiments
1. Write an applet which displays multiple lines of text in the applet window?
2. What is meant by AWT? How will you create User Interfaces for applets?
3. Design an application having interface as shown below:
4. Develop a simple integer calculator. It has two text fields, a label that displays the
result, and 4 radio buttons (+, -, *, /). Here is how it works:
Input numbers in the text fields, e.g. 10 .. 10
Choose the operation by selecting one of the radio buttons, e.g. +
The label will display the result based on the selected operation, e.g. 20
SUB: JAVA
39
[Link] the Swing Action architecture?
[Link] layout managers?
[Link] the Swing delegation event model?
[Link] will you go about building a Swing GUI client?
40