IT2301 Java
IT2301 Java
UNIT-I
PART-A
1.What is a class?
A class is a blueprint, or prototype, that defines the variables and the methods common to
all objects of a certain kind.
2.What is a object?
3.What is a method?
Encapsulation is the term given to the process of hiding the implementation details of the
object. Once an object is encapsulated, its implementation details are not immediately
accessible any more. Instead they are packaged and are only indirectly accessible via the
interface of the object
Inheritance in object oriented programming means that a class of objects can inherit
properties and methods from another class of objects.
The Java interpreter along with the runtime environment required to run the Java
application in called as Java virtual machine(JVM)
There are access modifiers and there are other identifiers. Access modifiers are public,
protected and private. Other are final and static.
There are 3 access modifiers. Public, protected and private, and the default one if no
identifier is specified is called friendly, but programmer cannot specify the friendly
identifier explicitly.
They are classes that wrap a primitive data type so it can be used as a object
12.What is a static variable and static method? What\'s the difference between two?
The modifier static can be used with a variable and method. When declared as static
variable, there is only one variable no matter how instances are created, this variable is
initialized when the class is loaded. Static method do not need a class to be instantiated to
be called, also a non-static method cannot be called from static method.
Garbage Collection is a thread that runs to reclaim the memory by destroying the objects
that cannot be referenced anymore.
Abstract class is a class that needs to be extended and its methods implemented, a class
has to be declared abstract if it has one or more abstract methods.
This modifier can be applied to class, method and variable. When declared as final class
the class cannot be extended. When declared as final variable, its value cannot be
changed if is primitive value, if it is a reference to the object it will always refer to the
same object, internal attributes of the object can be changed.
16.What is interface?
Interface is a contact that can be implemented by a class , it has method that need
implementation.
Overloading is declaring multiple methods with the same name, but with different
argument list.
Singleton class means that any given time only one instance of the class is present, in one
JVM.
Number of elements in an array are fixed at the construction time, whereas the number of
elements in vector can grow dynamically.
21.What is a constructor?
In Java, the class designer can guarantee initialization of every object by providing a
special method called a constructor. If a class has a constructor, Java automatically calls
that constructor when an object is created, before users can even get their hands on it. So
initialization is guaranteed.
22.What is casting?
Conversion of one type of data to another when appropriate. Casting makes explicitly
converting of data.
The modifier final is used on class variable and methods to specify certain behaviors
explained above. And finally is used as one of the loop in the try catch blocks, It is used
to hold code that needs to be executed whether or not the exception occurs in the try
catch block. Java provides a method called finalize( ) that can be defined in the class.
When the garbage collector is ready to release the storage ed for your object, it will first
call finalize( ), and only on the next garbage-collection pass will it reclaim the objects
memory. So finalize( ), gives you the ability to perform some important cleanup at the
time of garbage collection.
PART-B
1. Explain in detail about Java Buzzwords (or) Java features (or) characteristics.
2. Explain in detail about Control Structures available in java.
3. Explain method overloading with an example program
4. Explain in detail about constructor overloading with an example
5. Explain about String class, String constructor, and different String methods using
a program.
6. Explain about StringBuffer class, StringBuffer constructor, and different
StringBuffer methods using a program.
7. Explain in detail about explicitly invoking garbage collector and finalize()
method?
8. Explain method overloading and method overriding with give suitable example.
9. Explain vectors and their types.
10. Explain classes and objects of java classes.
UNIT-II
PART-A
1. What is are packages? A package is a collection of related classes and interfaces
providing access protection and namespace management.
2. What is a super class and how can you call a super class? When a class is
extended that is derived from another class there is a relationship is created, the
parent class is referred to as the super class by the derived class that is the child.
The derived class can make a call to the super class using the keyword super. If
used in the constructor of the
3. What is meant by Binding?
Binding denotes association of a name with a class.
String str1=\"Hello\";
String str2=\"Hello\";
9. How many objects are in the memory after the exection of following code
segment?
String str1 = \"ABC\";
String str2 = \"XYZ\";
String str1 = str1 + str2;
There are 3 Objects.
1.
o Method overloading
o Method overriding through inheritance
o Method overriding through the Java interface \\
25. What are Access Specifiers available in Java?
Access specifiers are keywords that determines the type of access to the member of a
class. These are:
1.
o Public
o Protected
o Private
o Defaults \\
26.How is it possible for two String objects with identical values not to be equal
under the == operator?
The == operator compares two objects to determine if they are the same object in
memory i.e. present in the same memory location. It is possible for two String objects to
have the same value, but located in different areas of memory.
== compares references while .equals compares contents. The method public boolean
equals(Object obj) is provided by the Object class and can be overridden. The default
implementation returns true only if the object is compared with itself, which is equivalent
to the equality operator == being used to compare aliases to the object. String, BitSet,
Date, and File override the equals() method. For two String objects, value equality means
that they contain the same character sequence. For the Wrapper classes, value equality
means that the primitive values are equal.
String s1 = “abc”;
String s2 = s1;
String s5 = “abc”;
String s3 = new String(”abc”);
String s4 = new String(”abc”);
System.out.println(”== comparison : ” +
(s1 == s5));
System.out.println(”== comparison : ” +
(s1 == s2));
System.out.println(”Using equals method :
” + s1.equals(s2));
System.out.println(”== comparison : ” +
s3 == s4);
System.out.println(”Using equals method :
” + s3.equals(s4));
}
}
Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true
PART-B
UNIT-III
PART-A
Member classes - Member inner classes are just like other member methods and member
variables and access to the member class is restricted, just like methods and variables.
This means a public member class acts similarly to a nested top-level class. The primary
difference between member classes and nested top-level classes is that member classes
have access to the specific instance of the enclosing class.
Local classes - Local classes are like local variables, specific to a block of code. Their
visibility is only within the block of their declaration. In order for the class to be useful
beyond the declaration block, it would need to implement a
more publicly available interface.Because local classes are not members, the modifiers
public, protected, private, and static are not usable.
Anonymous classes - Anonymous inner classes extend local inner classes one level
further. As anonymous classes have no name, you cannot provide a constructor.
2. What is the common usage of serialization?
An abstract class may contain code in method bodies, which is not allowed in an
interface. With abstract classes, you have to inherit your class from it and Java does not
allow multiple inheritance. On the other hand, you can implement multiple interfaces in
your class.
4.What is reflection?
The ability to examine and manipulate a Java class from within itself may not sound like
very much, but in other programming languages this feature simply doesn\'t exist. For
example, there is no way in a Pascal, C, or C++ program to obtain information about the
functions defined within that program.
import java.lang.reflect.*;
Abstract classes are often used to provide methods that will be common to a range of
similar subclasses, to avoid duplicating the same code in each case. Each subclass adds
its own features on top of the common abstract methods.
Yes, classes can be declared inside interfaces. This technique is sometimes used where
the class is a constant type, return value or method argument in the interface. When a
class is closely associated with the use of an interface it is convenient to declare it in the
same compilation unit. This proximity also helps ensure that implementation changes to
either are mutually compatible.
A class defined inside an interface is implicitly public static and operates as a top
level class. The static modifier does not have the same effect on a nested class as it
does with class variables and methods. The example below shows the definition of a
StoreProcessor interface with nested StorageUnit class which is used in the two
interface methods.
In Java an interface cannot extend an abstract class. An interface may only extend a
super-interface. And an abstract class may implement an interface. It may help to think of
interfaces and classes as separate lines of inheritance that only come together when a
class implements an interface, the relationship cannot be reversed.
Yes, the most common scenario is to create an object implementation for an interface,
although they can be used as a pure reference type. Interfaces cannot be instantiated in
their own right, so it is usual to write a class that implements the interface and fulfils the
methods defined in it.
...
}
Marker interfaces are those which do not declare any required methods, but signify their
compatibility with certain operations. The java.io.Serializable interface is a typical
marker interface. It does not contain any methods, but classes must implement this
interface in order to be serialized and de-serialized.
The shallow copy is done for obj and new object obj1 is created but contained objects of
obj are not copied.
It can be seen that no new objects are created for obj1 and it is referring to the same old
contained objects. If either of the containedObj contain any other object no new reference
is created
• Shallow copying is default cloning in Java which can be achieved using clone()
method of Object class. For deep copying some extra logic need to be provided.
If we do a = clone(b)
1) Then b.equals(a)
2) No method of a can modify the value of b.
16.What are the disadvantages of deep cloning?
In Java streams are used to process input and output data as a sequence of bytes, which
does not assume a specific character content or encoding. Byte content can be read from
network sources, files and other sources, and bytes copied between multiple inputs and
outputs.
Streams types can be sub-classed to add filtering, to mark a point in the stream and re-
read those bytes, or to skip a number of bytes. Streams also enable serlializable objects to
stored and re-constructed using ObjectInputStream and ObjectOutputStream types.
A pipe is an input/output link between two programs, commonly where you use the
output from one program as the input for another program. A broken pipe means that the
linkage between the output and input is interrupted, the reasons vary. For example, the
feeder program may throw an error and terminate unexpectedly, intermediate source or
output files may not be created successfully, or key resources become unavailable during
the process. You may also get problems with the amount of swap file storage or overall
memory usage approaches its limits.
19.What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream class hierarchy?
The File class is used to create objects that provide access to the files and directories of a
local file system.
An I/O filter is an object that reads from one stream and writes to another, usually
altering the data in some way as it is passed from one stream to another.
A transient variable is a variable that may not be serialized. If you don\'t want some field
to be serialized, you can mark that field transient or static.
Objects that subclass the Observable class maintain a list of observers. When an
Observable object is updated it invokes the update() method of each of its observers to
notify the observers that it has changed state. The Observer interface is implemented by
objects that observe Observable objects.
PART-B
UNIT-IV
PART-A
The Panel and Applet classes use the FlowLayout as their default layout.
java.lang.Throwable
1. Exception and Error are the subclasses of the Throwable class. Exception class
is used for exceptional conditions that user program should catch. Error defines
exceptions that are not excepted to be caught by the user program. Example is
Stack Overflow.
Unchecked Exceptions are those which occur at runtime and need not be
explicitly handled. RuntimeException and it\'s subclasses, Error and it\'s
subclasses fall under unchecked exceptions.
1. Apart from the exceptions already defined in Java package libraries, user can
define his own exception classes by extending Exception class.
10. Can a finally block exist with a try block but without a catch?
Yes. The following are the combinations try/catch or try/catch/finally or try/finally.
11. What will happen to the Exception object after exception handling?
Exception object will be garbage collected.
An exception is an abnormal condition that arises in a code sequence at run time. In other
words, an exception is a run-time error.
Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java
language or the constraints of the Java execution environment.
Manually generated exceptions are typically used to report some error condition to the
caller of a method.
throw ThrowableInstance;
ThrowableInstance must be an object of type Throwable or
a subclass of Throwable.
myWindow.getContentPane().add(component)
Swing components don’t implement scrolling directly. Scrolling has instead been
encapsulated in the JScrollPane class. To get scrollbars on a component, wrap it in a
JScrollPane. Instead of:
panel.add(component)
use
panel.add(new JScrollPane(component));
Components that implement the Scrollable interface will interact with JScrollPane to
configure the scrolling behavior. Components that don’t implement Scrollable will get
the default behavior supplied by JScrollPane.
By default, a window is hidden (but not disposed of) when it is closed. This happens after
all window listeners have executed. To prevent the window from closing unless the
program closes it, use this code:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
“Yes, but…” You can mix these components, and it’s documented at
http://java.sun.com/products/jfc/tsc/swingdoc-archive/mixing.html. However, if it’s at all
possible, you’ll find it much less problematic to convert
everything to Swing. (The problem is that AWT components are heavyweight, while
Swing components are lightweight, and heavyweight components always appear above
lightweight components; this causes difficulty for things like tabbed panes, internal
frames, popup menus, etc.)
Sun has a couple of articles explaining JInternalFrame and JDesktopPane in the Swing
Connection:
Override the JPanel’s paintComponent() method and use it to paint the image (which
you should store as an ImageIcon). For example:
Override isManagingFocus() to return true, then all key events should be sent to your
JComponent. <Christian Kaufhold>
While there could be many reasons for this behavior, one possibility is that you have a
JScrollPane in a GridBagLayout without a minimum size set. Try setting a reasonable
value and see if your problem disappears.
<Brian Sletten>
This should be added in J49655DK 1.4. There’s an article about this new support on The
Swing Connection. Using XML serialization is much more compact than using the old
Object serialization, but it isn’t appropriate for serializing everything.
The easiest way is to use the JOptionPane constructor where you supply the components
that are used to build the JOptionPane. Since you create the components, you can do
whatever you want to them before you pass them to the JOptionPane. The constructors to
use are any of the ones that take Objects. See the JOptionPane JavaDoc for details on
what kinds of Objects you can pass to these constructors.
A layout manager is an object that positions and resizes the components in a Container
according to some algorithm; for example, the FlowLayout layout manager lays out
components from left to right until it runs out of room and then continues laying out
components below that row.
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing
works faster than AWT.
At this point in time applets may communicate with other applets running in the same
virtual machine. If the applets are of the same class, they can communicate via shared
static variables. If the applets are of different classes, then each will need a reference to
the same class with static variables. In any case the basic idea is to pass the information
back and forth through a static variable.
PART-B
UNIT-V
PART-A
1. What invokes a thread\'s run() method? After a thread is started, via its start()
method or that of the Thread class, the JVM invokes the thread\'s run() method
when the thread is initially executed.
2. What is the GregorianCalendar class? The GregorianCalendar provides support
for traditional Western calendars.
1. What is the SimpleTimeZone class? The SimpleTimeZone class
provides support for a Gregorian calendar.
3. What is the Properties class? The properties class is a subclass of Hashtable that
can be read from or written to a stream. It also provides the capability to specify a
set of default values to be used.
1. What is the purpose of the Runtime class? The purpose of the Runtime
class is to provide access to the Java runtime system.
2. What is the purpose of the System class? The purpose of the System
class is to provide access to system resources.
4. What is the purpose of the finally clause of a try-catch-finally statement? The
finally clause is used to provide the capability to execute code no matter whether
or not an exception is thrown or caught. For example,
i. try
{
//some statements
}
catch
{
// statements when exception is cought
}
finally
{
//statements executed whether exception occurs or not
}
1. What is the Locale class? The Locale class is used to tailor program output to
the conventions of a particular geographic, political, or cultural region.
2. What must a class do to implement an interface? It must provide all of the
methods in the interface and identify the interface in its implements clause.
1. What is meant by a Thread? Thread is defined as an instantiated parallel
process of a given program.
3. What is multi-threading? Multi-threading as the name suggest is the scenario
where more than one threads are running.
4. What are two ways of creating a thread? Which is the best way and why?
Two ways of creating threads are, one can extend from the Java.lang.Thread and
can implement the rum method or the run method of a different class can be
called which implements the interface Runnable, and the then implement the run()
method. The latter one is mostly used as first due to Java rule of only one class
inheritance, with implementing the Runnable interface that problem is sorted out.
1. What is deadlock? Deadlock is a situation when two threads are waiting
on each other to release a resource. Each thread waiting for a resource
which is held by the other waiting thread. In Java, this resource is usually
the object lock obtained by the synchronized keyword.
5. What are the three types of priority? MAX_PRIORITY which is 10,
MIN_PRIORITY which is 1, NORM_PRIORITY which is 5.
10. What is the use of synchronizations? Every object has a lock, when a synchronized
keyword is used on a piece of code the, lock must be obtained by the thread first to
execute that code, other threads will not be allowed to execute that piece of code till this
lock is released.
12. What are different ways in which a thread can enter the waiting state? A thread
can enter the waiting state by invoking its sleep() method, blocking on I/O,
unsuccessfully attempting to acquire an object\'s lock, or invoking an object\'s wait()
method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
13. Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This
lock is acquired on the class\'s Class object.
1. What\'s new with the stop(), suspend() and resume() methods in new JDK
1.2? The stop(), suspend() and resume() methods have been deprecated in JDK
1.2.
14. What is the preferred size of a component? The preferred size of a component is
the minimum component size that will allow the component to display normally.
15. What method is used to specify a container\'s layout? The setLayout() method is
used to specify a container\'s layout. For example, setLayout(new FlowLayout()); will be
set the layout as FlowLayout.
16. What state does a thread enter when it terminates its processing? When a thread
terminates its processing, it enters the dead state.
18. What is Runnable interface ? Are there any other ways to make a java program
as multithred java program?
System.out.println(\"I\'m running!\");
new Thread(my1).start();
new Thread(my2).start();
Thus, every class (thread) implements the Runnable interface, has to provide logic for
run() method
19.How can i tell what state a thread is in ?
Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive() returned
false the thread was either new or terminated but there was simply no way to differentiate
between the two.
Starting with the release of Tiger (Java 5) you can now get what state a thread is in by
using the getState() method which returns an Enum of Thread.States. A thread can only
be in one of the following states at a given point in time.
Thread.State e = t.getState();
Thread.State[] ts = e.values();
for(int i = 0; i < ts.length; i++){
System.out.println(ts[i]);
Java provides three methods that threads can use to communicate with each other: wait,
notify, and notifyAll. These methods are defined for all Objects (not just Threads). The
idea is that a method called by a thread may need to wait for some condition to be
satisfied by another thread; in that case, it can call the wait method, which causes its
thread to wait until another thread calls notify or notifyAll.
A call to notify causes at most one thread waiting on the same object to be notified (i.e.,
the object that calls notify must be the same as the object that called wait). A call to
notifyAll causes all threads waiting on the same object to be notified. If more than one
thread is waiting on that object, there is no way to control which of them is notified by a
call to notify (so it is often better to use notifyAll than notify).
Synchronization is the act of serializing access to critical sections of code. We will use
this keyword when we expect multiple threads to access/modify the same data. To
understand synchronization we need to look into thread execution manner.
Threads may execute in a manner where their paths of execution are completely
independent of each other. Neither thread depends upon the other for assistance. For
example, one thread might execute a print job, while a second thread repaints a window.
And then there are threads that require synchronization, the act of serializing access to
critical sections of code, at various moments during their executions. For example, say
that two threads need to send data packets over a single network connection. Each thread
must be able to send its entire data packet before the other thread starts sending its data
packet; otherwise, the data is scrambled. This scenario requires each thread to
synchronize its access to the code that does the actual data-packet sending.
If you feel a method is very critical for business that needs to be executed by only one
thread at a time (to prevent data loss or corruption), then we need to use synchronized
keyword.
EXAMPLE
Some real-world tasks are better modeled by a program that uses threads than by a
normal, sequential program. For example, consider a bank whose accounts can be
accessed and updated by any of a number of automatic teller machines (ATMs). Each
ATM could be a separate thread, responding to deposit and withdrawal requests from
different users simultaneously. Of course, it would be important to make sure that two
users did not access the same account simultaneously. This is done in Java using
synchronization, which can be applied to individual methods, or to sequences of
statements.
One or more methods of a class can be declared to be synchronized. When a thread calls
an object\'s synchronized method, the whole object is locked. This means that if another
thread tries to call any synchronized method of the same object, the call will block until
the lock is released (which happens when the original call finishes). In general, if the
value of a field of an object can be changed, then all methods that read or write that field
should be synchronized to prevent two threads from trying to write the field at the same
time, and to prevent one thread from reading the field while another thread is in the
process of writing it.
Here is an example of a BankAccount class that uses synchronized methods to ensure that
deposits and withdrawals cannot be performed simultaneously, and to ensure that the
account balance cannot be read while either a deposit or a withdrawal is in progress. (To
keep the example simple, no check is done to ensure that a withdrawal does not lead to a
negative balance.)
balance = initialDeposit;
return balance;
balance += deposit;
balance -= withdrawal;
}
There are cases where we need to synchronize a group of statements, we can do that
using synchrozed statement.
synchronized ( B ) {
if ( D > B.Balance() ) {
ReportInsuffucientFunds();
else {
B.Withdraw( D );
PART-B
10. What are virtual classes? Explain the need for virtual classes while building class.
11. What are abstract classes? Explain the role of abstract class while building a class
hierarchy.