Core Java
Core Java
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? An object is a software bundle of variables and related
methods.An instance of a class depicting the state and behavior at that particular
time in real world.
3. What is a method? Encapsulation of a functionality which can be called to perform
specific tasks.
4. What is encapsulation? Explain with an example. 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
5. What is inheritance? Explain with an example. Inheritance in object oriented
programming means that a class of objects can inherit properties and methods from
another class of objects.
6. What is polymorphism? Explain with an example. In object-oriented
programming, polymorphism refers to a programming language’s ability to process
objects differently depending on their data type or class. More specifically, it is the
ability to redefine methods for derived classes. For example, given a base class
shape, polymorphism enables the programmer to define different area methods for
any number of derived classes, such as circles, rectangles and triangles. No matter
what shape an object is, applying the area method to it will return the correct results.
Polymorphism is considered to be a requirement of any true object-oriented
programming language
7. Is multiple inheritance allowed in Java? No, multiple inheritance is not allowed in
Java.
8. What is interpreter and compiler? Java interpreter converts the high level
language code into a intermediate form in Java called as bytecode, and then
executes it, where as a compiler converts the high level language code to machine
language making it very hardware specific
9. What is JVM? The Java interpreter along with the runtime environment required to
run the Java application in called as Java virtual machine(JVM)
10. What are the different types of modifiers? There are access modifiers and there
are other identifiers. Access modifiers are public, protected and private. Other are
final and static.
11. What are the access modifiers in Java? 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.
12. What is a wrapper class? They are classes that wrap a primitive data type so it can
be used as a object
13. 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
Page 1 of 114
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.
14. What is garbage collection? Garbage Collection is a thread that runs to reclaim the
memory by destroying the objects that cannot be referenced anymore.
15. What is abstract class? Abstract class is a class that needs to be extended and its
methods implemented, aclass has to be declared abstract if it has one or more
abstract methods.
16. What is meant by final class, methods and variables? 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.
17. What is interface? Interface is a contact that can be implemented by a class, it has
method that need implementation.
18. What is method overloading? Overloading is declaring multiple method with the
same name, but with different argument list.
19. What is method overriding? Overriding has same method name, identical
arguments used in subclass.
20. What is singleton class? Singleton class means that any given time only one
instance of the class is present, in one JVM.
21. What is the difference between an array and a vector? Number of elements in an
array are fixed at the construction time, whereas the number of elements in vector
can grow dynamically.
22. 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.
23. What is casting? Conversion of one type of data to another when appropriate.
Casting makes explicitly converting of data.
24. What is the difference between final, finally and finalize? The modifier final is
used on class variable and methods to specify certain behaviour 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.
25. What is are packages? A package is a collection of related classes and interfaces
providing access protection and namespace management.
Page 2 of 114
26. 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 derived class it has to be the first statement.
27. What is meant by a Thread? Thread is defined as an instantiated parallel process
of a given program.
28. What is multi-threading? Multi-threading as the name suggest is the scenario
where more than one threads are running.
29. 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.
30. 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.
31. What are the three types of priority? MAX_PRIORITY which is 10,
MIN_PRIORITY which is 1, NORM_PRIORITY which is 5.
32. 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.
1. What is the Collections API? - The Collections API is a set of classes and
interfaces that support operations on collections of objects
2. What is the List interface? - The List interface provides support for ordered
collections of objects.
3. What is the Vector class? - The Vector class provides the capability to implement a
growable array of objects
4. What is an Iterator interface? - The Iterator interface is used to step through the
elements of a Collection
5. Which java.util classes and interfaces support event handling? - The
EventObject class and the EventListener interface support event processing
6. What is the GregorianCalendar class? - The GregorianCalendar provides support
for traditional Western calendars
7. 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
8. What is the SimpleTimeZone class? - The SimpleTimeZone class provides
support for a Gregorian calendar
Page 3 of 114
9. What is the Map interface? - The Map interface replaces the JDK 1.1 Dictionary
class and is used associate keys with values
10. What is the highest-level event class of the event-delegation model? - The
java.util.EventObject class is the highest-level class in the event-delegation class
hierarchy
11. What is the Collection interface? - The Collection interface provides support for
the implementation of a mathematical bag - an unordered collection of objects that
may contain duplicates
12. What is the Set interface? - The Set interface provides methods for accessing the
elements of a finite mathematical set. Sets do not allow duplicate elements
13. What is the purpose of the enableEvents() method? - The enableEvents()
method is used to enable an event for a particular object. Normally, an event is
enabled when a listener is added to an object for a particular event. The
enableEvents() method is used by objects that handle events by overriding their
event-dispatch methods.
14. What is the ResourceBundle class? - The ResourceBundle class is used to store
locale-specific resources that can be loaded by a program to tailor the program’s
appearance to the particular locale in which it is being run.
15. What is the difference between yielding and sleeping? - When a task invokes its
yield() method, it returns to the ready state. When a task invokes its sleep() method,
it returns to the waiting state.
16. When a thread blocks on I/O, what state does it enter? - A thread enters the
waiting state when it blocks on I/O.
17. When a thread is created and started, what is its initial state? - A thread is in the
ready state after it has been created and started.
18. 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.
19. What method is invoked to cause an object to begin executing as a separate
thread? - The start() method of the Thread class is invoked to cause an object to
begin executing as a separate thread.
20. What is the purpose of the wait(), notify(), and notifyAll() methods? - The
wait(),notify(), and notifyAll() methods are used to provide an efficient way for
threads to wait for a shared resource. When a thread executes an object’s wait()
method, it enters the waiting state. It only enters the ready state after another thread
invokes the object’s notify() or notifyAll() methods.
21. What are the high-level thread states? - The high-level thread states are ready,
running, waiting, and dead
22. What happens when a thread cannot acquire a lock on an object? - If a thread
attempts to execute a synchronized method or synchronized statement and is unable
to acquire an object’s lock, it enters the waiting state until the lock becomes
available.
Page 4 of 114
23. How does multithreading take place on a computer with a single CPU? - The
operating system’s task scheduler allocates execution time to multiple tasks. By
quickly switching between executing tasks, it creates the impression that tasks
execute sequentially.
24. What happens when you invoke a thread’s interrupt method while it is sleeping
or waiting? - When a task’s interrupt() method is executed, the task enters the
ready state. The next time the task enters the running state, an InterruptedException
is thrown.
25. What state is a thread in when it is executing? - An executing thread is in the
running state
26. What are three ways in which a thread can enter the waiting state? - A thread
can enter the waiting state by invoking its sleep() method, by blocking on I/O, by
unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s
wait() method. It can also enter the waiting state by invoking its (deprecated)
suspend() method.
27. What method must be implemented by all threads? - All tasks must implement
the run() method, whether they are a subclass of Thread or implement the Runnable
interface.
28. What are the two basic ways in which classes that can be run as threads may
be defined? - A thread class may be declared as a subclass of Thread, or it may
implement the Runnable interface.
29. How can you store international / Unicode characters into a cookie? - One way
is, before storing the cookie URLEncode it. URLEnocder.encoder(str); And use
URLDecoder.decode(str) when you get the stored cookie.
1. What is garbage collection? What is the process that is responsible for doing
that in java? - Reclaiming the unused memory by the invalid objects. Garbage
collector is responsible for this process
2. What kind of thread is the Garbage collector thread? - It is a daemon thread.
3. What is a daemon thread? - These are the threads which can run without user
intervention. The JVM can exit when there are daemon thread by killing them
abruptly.
4. How will you invoke any external process in Java? -
Runtime.getRuntime().exec(….)
5. What is the finalize method do? - Before the invalid objects get garbage collected,
the JVM give the user a chance to clean up some resources before it got garbage
collected.
6. What is mutable object and immutable object? - If a object value is changeable
then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to
change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)
7. What is the basic difference between string and stringbuffer object? - String is
an immutable object. StringBuffer is a mutable object.
Page 5 of 114
8. What is the purpose of Void class? - The Void class is an uninstantiable
placeholder class to hold a reference to the Class object representing the primitive
Java type void.
9. What is reflection? - Reflection allows programmatic access to information about
the fields, methods and constructors of loaded classes, and the use reflected fields,
methods, and constructors to operate on their underlying counterparts on objects,
within security restrictions.
10. What is the base class for Error and Exception? - Throwable
11. What is the byte range? -128 to 127
12. What is the implementation of destroy method in java.. is it native or java
code? - This method is not implemented.
13. What is a package? - To group set of classes into a single unit is known as
packaging. Packages provides wide namespace ability.
14. What are the approaches that you will follow for making a program very
efficient? - By avoiding too much of static methods avoiding the excessive and
unnecessary use of synchronized methods Selection of related classes based on the
application (meaning synchronized classes for multiuser and non-synchronized
classes for single user) Usage of appropriate design patterns Using cache
methodologies for remote invocations Avoiding creation of variables within a loop
and lot more.
15. What is a DatabaseMetaData? - Comprehensive information about the database as
a whole.
16. What is Locale? - A Locale object represents a specific geographical, political, or
cultural region
17. How will you load a specific locale? - Using ResourceBundle.getBundle(…);
18. What is JIT and its use? - Really, just a very fast compiler… In this incarnation,
pretty much a one-pass compiler - no offline computations. So you can’t look at the
whole method, rank the expressions according to which ones are re-used the most,
and then generate code. In theory terms, it’s an on-line problem.
19. Is JVM a compiler or an interpreter? - Interpreter
20. When you think about optimization, what is the best way to findout the
time/memory consuming process? - Using profiler
21. What is the purpose of assert keyword used in JDK1.4.x? - In order to validate
certain expressions. It effectively replaces the if block and automatically throws the
AssertionError on failure. This keyword should be used for the critical arguments.
Meaning, without that the method does nothing.
22. How will you get the platform dependent values like line separator, path
separator, etc., ? - Using Sytem.getProperty(…) (line.separator, path.separator, …)
23. What is skeleton and stub? what is the purpose of those? - Stub is a client side
representation of the server, which takes care of communicating with the remote
server. Skeleton is the server side representation. But that is no more in use… it is
deprecated long before in JDK.
Page 6 of 114
24. What is the final keyword denotes? - final keyword denotes that it is the final
implementation for that method or variable or class. You can’t override that
method/variable/class any more.
25. What is the significance of ListIterator? - You can iterate back and forth.
26. What is the major difference between LinkedList and ArrayList? - LinkedList are
meant for sequential accessing. ArrayList are meant for random accessing.
27. What is nested class? - If all the methods of a inner class is static then it is a
nested class.
28. What is inner class? - If the methods of the inner class can only be accessed via
the instance of the inner class, then it is called inner class.
29. What is composition? - Holding the reference of the other class within some other
class is known as composition.
30. What is aggregation? - It is a special type of composition. If you expose all the
methods of a composite class and route the method call to the composite method
through its reference, then it is called aggregation.
31. What are the methods in Object? - clone, equals, wait, finalize, getClass,
hashCode, notify, notifyAll, toString
32. Can you instantiate the Math class? - You can’t instantiate the math class. All the
methods in this class are static. And the constructor is not public.
33. What is singleton? - It is one of the design pattern. This falls in the creational
pattern of the design pattern. There will be only one instance for that entire JVM. You
can achieve this by having the private constructor in the class. For eg., public class
Singleton { private static final Singleton s = new Singleton(); private Singleton() { }
public static Singleton getInstance() { return s; } // all non static methods … }
34. What is DriverManager? - The basic service to manage set of JDBC drivers.
35. What is Class.forName() does and how it is useful? - It loads the class into the
ClassLoader. It returns the Class. Using that you can get the instance ( “class-
instance”.newInstance() ).
36. Inq adds a question: Expain the reason for each keyword of
public static void main(String args[])
Page 7 of 114
2. 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.
3. 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.
4. 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.
5. 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.
6. 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.
7. Which containers use a FlowLayout as their default layout? The Panel and
Applet classes use the FlowLayout as their default layout.
8. What state does a thread enter when it terminates its processing? When a
thread terminates its processing, it enters the dead state.
9. What is the Collections API? The Collections API is a set of classes and interfaces
that support operations on collections of objects. One example of class in Collections
API is Vector and Set and List are examples of interfaces in Collections API.
10. What is the List interface? The List interface provides support for ordered
collections of objects. It may or may not allow duplicate elements but the elements
must be ordered.
11. How does Java handle integer overflows and underflows? It uses those low
order bytes of the result that can fit into the size of the type allowed by the operation.
12. What is the Vector class? The Vector class provides the capability to implement a
growable array of objects. The main visible advantage of this class is programmer
needn’t to worry about the number of elements in the Vector.
13. What modifiers may be used with an inner class that is a member of an outer
class? A (non-local) inner class may be declared as public, protected, private, static,
final, or abstract.
14. If a method is declared as protected, where may the method be accessed? A
protected method may only be accessed by classes or interfaces of the same
package or by subclasses of the class in which it is declared.
15. What is an Iterator interface? The Iterator interface is used to step through the
elements of a Collection.
16. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8
characters? Unicode requires 16 bits, ASCII require 7 bits (although the ASCII
character set uses only 7 bits, it is usually represented as 8 bits), UTF-8 represents
characters using 8, 16, and 18 bit patterns, UTF-16 uses 16-bit and larger bit
patterns
Page 8 of 114
17. What is the difference between yielding and sleeping? Yielding means a thread
returning to a ready state either from waiting, running or after creation, where as
sleeping refers a thread going to a waiting state from running state. With reference to
Java, when a task invokes its yield() method, it returns to the ready state and when a
task invokes its sleep() method, it returns to the waiting state
18. What are wrapper classes? Wrapper classes are classes that allow primitive types
to be accessed as objects. For example, Integer, Double. These classes contain
many methods which can be used to manipulate basic data types
19. Does garbage collection guarantee that a program will not run out of memory?
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 main purpose of Garbage Collector is recover
the memory from the objects which are no longer required when more memory is
needed.
20. Name Component subclasses that support painting? The following classes
support painting: Canvas, Frame, Panel, and Applet.
21. What is a native method? A native method is a method that is implemented in a
language other than Java. For example, one method may be written in C and can be
called in Java.
22. How can you write a loop indefinitely?
for(;;) //for loop
while(true); //always true
23. Can an anonymous class be declared as implementing an interface and
extending a class? An anonymous class may implement an interface or extend a
superclass, but may not be declared to do both.
24. What is the purpose of finalization? The purpose of finalization is to give an
unreachable object the opportunity to perform any cleanup processing before the
object is garbage collected. For example, closing a opened file, closing a opened
database Connection.
25. 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.
26. What is the GregorianCalendar class? The GregorianCalendar provides support
for traditional Western calendars.
27. What is the SimpleTimeZone class? The SimpleTimeZone class provides support
for a Gregorian calendar.
28. 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.
29. What is the purpose of the Runtime class? The purpose of the Runtime class is to
provide access to the Java runtime system.
30. What is the purpose of the System class? The purpose of the System class is to
provide access to system resources.
Page 9 of 114
31. 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,
try
{
//some statements
}
catch
{
// statements when exception is cought
}
finally
{
//statements executed whether exception occurs or not
}
32. 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.
33. 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.
Page 10 of 114
Q: What is the difference between an Interface and an Abstract class?
A: An Abstract class declares have at least one instance method that is declared abstract which
will be implemented by the subclasses. An abstract class can have instance methods that
implement a default behavior. An Interface can only declare constants and instance methods,
but cannot implement default behavior.
TOP
Page 11 of 114
may be void), and is invoked using the dot operator.
TOP
Q: What is an Iterators?
A: Some of the collection classes provide traversal of their contents via a java.util.Iterator
interface. This interface allows you to walk a collection of objects, operating on each object in
turn. Remember when using Iterators that they contain a snapshot of the collection at the time
the Iterator was obtained; generally it is not advisable to modify the collection itself while
traversing an Iterator.
TOP
Q: State the significance of public, private, protected, default modifiers both singly and in
combination and state the effect of package relationships on declared items qualified by
these modifiers.
A: public : Public class is visible in other packages, field is visible everywhere (class must be
public too) private : Private variables or methods may be used only by an instance of the
same class that declares the variable or method, A private feature may only be accessed by
the class that owns the feature. protected : Is available to all classes in the same package
and also available to all subclasses of the class that owns the protected feature.This access is
provided even to subclasses that reside in a different package from the class that owns the
protected feature. default :What you get by default ie, without any access modifier (ie, public
private or protected).It means that it is visible to all within a particular package.
TOP
Q: What is final?
A: A final class can't be extended ie., final class may not be subclassed. A final method can't be
overridden when its class is inherited. You can't change value of a final variable (is a constant).
A. The class System has a variable out that represents the standard output, and the variable err that
represents the standard error device. By default, they both point at the system console. This how the standard
output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);
Page 12 of 114
*Q2. What's the difference between an interface and an abstract class?
A. 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.
*Q3. Why would you use a synchronized block vs. synchronized method?
A. Synchronized blocks place locks for shorter periods than synchronized methods.
A. This keyword indicates that the value of this member variable does not have to be serialized with the
object. When the class will be de-serialized, this variable will be initialized with a default value of its data type
(i.e. zero for integers).
A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be
started immediately.
A. If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For
example:
Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.
*Q7. What's the difference between the methods sleep() and wait()
A. The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up
to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait()
is defined in the class Object and the method sleep() is defined in the class Thread.
*Q8. Can you write a Java class that could be used both as an applet as well as an application?
A. Constructors must have the same name as the class and can not return a value. They are only called once
while regular methods could be called many times.
*Q10. Can you call one constructor from another if a class has multiple constructors
A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming
conflicts when different packages have classes with the same names. Packages access level also allows you
to protect data from being used by the non-authorized classes.
Page 13 of 114
*Q12. If a class is located in a package, what do you need to change in the OS environment to be able
to use it?
A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH
environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file
c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this
class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee
*Q13. What's the difference between J2SDK 1.5 and J2SDK 5.0?
*Q14. What would you use to compare two String variables - the operator == or the method equals()?
A. I'd use the method equals() to compare the values of the Strings and the == to check if two variables point
at the same instance of a String object.
*Q15. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are
written?
A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to
be caught first.
*Q16. Can an inner class declared inside of a method access local variables of this method?
*Q17. What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}
A. A single ampersand here would lead to a NullPointerException.
A. This method is used to ensure that Swing components are updated through the event-dispatching thread.
A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in
the first line of the subclass's constructor.
**Q21. What's the difference between a queue and a stack?
A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule
**Q22. You can create an abstract class that contains only abstract methods. On the other hand, you
can create an interface that declares the same methods. So can you use abstract classes instead of
interfaces?
Page 14 of 114
A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only
option.
**Q23. What comes to mind when you hear about a young generation in Java?
A. Garbage collection.
**Q24. What comes to mind when someone mentions a shallow copy in Java?
A. Object cloning.
**Q25. If you're overriding the method equals() of an object, which other method you might also
consider?
A. hashCode()
**Q26. You are planning to do an indexed search in a list of objects. Which of the two Java collections
should you use:
ArrayList or LinkedList?
A. ArrayList
**Q27. How would you make a copy of an entire Java object with its state?
A. Have this class implement Cloneable interface and call its method clone().
**Q28. How can you minimize the need of garbage collection and make the memory use more
effective?
**Q29. There are two classes: A and B. The class B need to inform a class A when some important
event has happened. What Java technique would you use to implement it?
A. If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer
interface.
*Q30. What access level do you need to specify in the class declaration to ensure that only classes
from the same directory can access it?
A. You do not need to specify any access level, and Java will use a default package access level.
Page 15 of 114
Sample Questions
Question 1 (Declaration and access control)
Which of the following are valid constructors within a class Test? Select the two correct answers.
A. test() { }
B. Test() { }
C. void Test() { }
D. private final Test() { }
E. abstract Test() { }
F. Test(Test t) { }
G. Test(void) { }
Answer: B and F. A constructor must have the same name as the class. The name of the class is Test. Since
Java is case sensitive, test is different than Test, hence option A is not valid. The constructor must not return
any value, so option C is incorrect. A constructor cannot be declared abstract or final. Hence D and E are
incorrect answers. Since taking a void argument is illegal in Java, G is also illegal.
Answer: A and C. The main method initialized x to 0. The if condition at line 4 returns false, so x remains zero
at the beginning of the switch statement. The value of x matches with case 0. Hence 0 gets printed. Since
there is no break statement after this, 2 also get printed. The break statement after case 2 leads to the control
coming out of the switch statement. Hence 0 and 2 are the only numbers that get printed.
Page 16 of 114
A. The class compiles and runs, but does not print anything.
B. The number 1 gets printed first with AssertionError.
C. The number 2 gets printed first with AssertionError.
D. The number 3 gets printed first with AssertionError.
E. The program generates a compilation error.
Answer: A. The if condition returns true, if i is less than j. The assert statement performs a check whether i is
equal to j. Since i will never be equal to j, the assert statement will always return true. Hence the
AssertionError does not get generated. So B, C, and D are incorrect.
Answer: D. After statement 3, r and s are pointing to two different memory locations both containing "abc".
After statement 4, the memory location to which r was pointing is available for garbage collection. After
statement 6, s now points to a different location. The memory block that s was pointing to that contained "abc"
is now available for garbage collection.
A. number_1
B. number_a
C. $1234
D. -volatile
Answer: A, B, and C. In Java, each character of an identifier can be either a digit, letter, underscore, or a
currency symbol. The first character cannot be a digit. Since - is not a valid character in an identifier name, D
is incorrect.
1. class test {
2. public static void main(String args[]) {
3. if(args.length > 0)
4. System.out.println(args.length);
5. }
6. }
A. The program compiles and runs but does not print anything.
B. The program compiles and runs and prints 0.
C. The program compiles and runs and prints 1.
D. The program compiles and runs and prints 2.
E. The program does not compile.
Answer: A. The above program is a legal Java file. No arguments are passed to the program, as the
command line just says java test. test here is the name of the class. The args array does not contain any
elements. Since args.length is zero, the program does not print anything.
Page 17 of 114
Question 7 What happens when the following program is compiled and run? Select the one correct answer.
Answer: E. The example is a legal Java class so A is incorrect. When array is passed as an argument, Java
treats it as a call by reference. When the method change_i updates i[0], the first element of the array is
directly getting modified. This element is set to 4 in change_i. This change in the value of i[0] is available in
the main method also. Hence 4 gets printed.
Answer: C. "A" is a character. So assigning "A" to c in statement 5 is perfectly valid. Assigning a character to
integer is also valid and does not require a cast. Thus the statement labeled 6 does not generate a
compilation error. It's not possible to assign an integer to a character without a cast. Hence the statement 7
generates a compilation error.
Question 9 (Objects)
Which of the following are true? Select the three correct answers.
A. A static method may be invoked before even a single instance of the class is constructed.
B. A static method cannot access nonstatic methods of the class.
C. An abstract modifier can appear before a class or a method but not before a variable.
D. The final modifier can appear before a class or a variable but not before a method.
E. A synchronized modifier may appear before a method or a variable but not before a class.
Answer: A, B, and C. A and B are correct statements about the behavior of static methods. The abstract
modifier may appear before a method or a class, but not before a variable, so C is also correct. A final modifier
Page 18 of 114
may appear before a method, a variable or before a class. Hence D is incorrect. A synchronized modifier
cannot come before a variable so E is also incorrect.
Question 10 (Collections)
Which of these are interfaces in the collection framework? Select the two correct answers.
A. HashMap
B. ArrayList
C. Collection
D. SortedMap
E. TreeMap
Answer: C and D. Collection and SortedMap are examples of interfaces in the collection framework.
HashMap. ArrayMap and TreeMap are examples of general purpose implementations for some of the
collection interfaces.
Answer: E. The method ceil returns the smallest double value equal to a mathematical integer that is not less
than the argument. Hence ceil(2.3f) returns 3. The round method round returns the integer closest to the
argument. Hence round(2.7) returns 3. Multiplying the two numbers returns 9.
1) The Java interpreter is used for the execution of the source code.
a) True b) False
Ans: a.
Page 19 of 114
Ans: A class and the main( ) method declarations.
6) What are the two parts in executing a Java program and their purposes?
Ans:
Two parts in executing a Java program are:
1, Java Compiler 2, Java Interpreter.
The Java Compiler is used for compilation and the Java Interpreter is used for execution of
the application.
10) In order for a source code file, containing the public class Test, to successfully compile,
which of the following must be true?
Ans : Identifiers are used for class names, method names and variable names. An identifier
may be any descriptive sequence of upper case & lower case letters,numbers or
underscore or dollar sign and must not begin with numbers.
Page 20 of 114
14) Which characters are as first characters of an identifier?
Ans : A - Z, a - z, _ ,$
2) /* --
*/ => multiple line comment
3) /** --
*/ =>documentation
2) What are the kinds of variables in Java? What are their uses?
Ans: Java has three kinds of variables namely, the instance variable, the local variable and
the class variable.
Local variables are used inside blocks as counters or in methods as temporary variables
and are used to store information needed by a single method.
Instance variables are used to define attributes or the state of a particular object and are
used to store information needed by multiple methods in the objects.
Class variables are global to a class and to all the instances of the class and are useful for
communicating between different objects of all the same class or keeping track of global
states.
Variables with the same data type can be declared together. Local variables must be given
a value before usage.
Page 21 of 114
Ans: Variable types can be any data type that java supports, which includes the eight
primitive data types, the name of a class or interface and an array.
There are different types of literals namely number literals, character literals,
boolean literals, string literals,etc.
7) What is an array?
Ans: An array is an object that stores a list of items.
Ans: a.
Ans: a.
Ans: a.
13) When a string literal is used in the program, Java automatically creates instances of the
string class.
a)Trueb)False
Ans: a.
Ans : a, b and d
Page 22 of 114
16) What is the value of a[3] as the result of the following array declaration?
a) 1 b) 2 c) 3 d) 4
Ans : d
Ans : a.
Ans. d
Ans: b.
Page 23 of 114
Operators
1) What are operators and what are the various types of operators available in Java?
Ans: Operators are special symbols used in expressions.
2) The ++ operator is used for incrementing and the -- operator is used for decrementing.
a)True b)False
Ans: a.
Ans: a.
Ans: a.
Ans : c.
Page 24 of 114
Associativity determines whether an expression is evaluated left-right or right-left.
13) What is the difference between prefix and postfix of -- and ++ operators?
Ans : The prefix form returns the increment or decrement operation and returns the value of
the increment or decrement operation.
The postfix form returns the current value of all of the expression and then
Ans : d
Control Statements
Ans: a.
2) class conditional {
public static void main(String args[]) {
int i = 20;
int j = 55;
int z = 0;
z = i < j ? i : j; // ternary operator
System.out.println("The value assigned is " + z);
}
}
What is output of the above program?
Ans: The value assigned is 20
Page 25 of 114
Ans: b.
Ans: a.
5) The while loop repeats a set of code while the condition is false.
a) True b) False
Ans: b.
6) The do-while loop repeats a set of code atleast once before the condition is tested.
a) True b) False
Ans: a.
The continue is similar to break, except that instead of halting the execution of the loop, it
starts the next iteration.
8) The for loop repeats a set of statements a certain number of times until a condition is
matched.
a) True b) False
Ans: a.
A do statement checks at the end of a loop to see whether the next iteration of a loop
should occur. The do statement will always execute the body of a loop at least once.
2) The new operator creates a single instance named class and returns a reference to that
object.
a) True b) False
Ans: a.
Page 26 of 114
Ans: a.
Method definition has four parts. They are name of the method, type of object or primitive
type the method returns, a list of parameters and the body of the method.
Ex: obj.methodname(param1,param2)
8) All the classes in java.lang package are automatically imported when a program is
compiled.
a) True b) False
Ans: a.
Page 27 of 114
Ans: a.
16) Casting between primitive types allows conversion of one primitive type to another.
a) True b) False
Ans: a.
Ans: a.
18) Boolean values can be cast into any other primitive type.
a) True b) False
Ans: b.
Ans: a.
20) Which cast must be used to convert a larger value into a smaller one?
Ans: Explicit cast.
22) Which of the following features are common to both Java & C++?
a. The class declaration
b. The access modifiers
c. The encapsulation of data & methods with in objects
d. The use of pointers
Ans: a,b,c.
23) Which of the following statements accurately describe the use of access modifiers
within a class definition?
Ans: a,b,d.
Page 28 of 114
Ans: b.
25) Which of the following statements can be used to describe a public method?
a. It is accessible to all other classes in the hierarchy
b. It is accessablde only to subclasses of its parent class
c. It represents the public interface of its class
d. The only way to gain access to this method is by calling one of the public class
methods
Ans: a,c.
26) Which of the following types of class members can be part of the internal part of a
class?
a.Public instance variables
b.Private instance variables
c.Public methods
d.Private methods
Ans: b,d.
27) You would use the ____ operator to create a single instance of a named class.
a.new b.dot
Ans: a.
28) Which of the following statements correctly describes the relation between an object
and the instance variable it stores?
a. Each new object has its own distinctive set of instance variables
b. Each object has a copy of the instance variables of its class
c. the instance variable of each object are seperate from the variables of other objects
d. The instance variables of each object are stored together with the variables of other
objects
Ans: a,b,c.
29) If no input parameters are specified in a method declaration then the declaration will
include __.
a. an empty set of parantheses b.the term void
Ans: a.
Ans: a,b,c.
Page 29 of 114
b. The methods of a class only
c. The instance variables and methods of a class
Ans: c.
Ans: b.
33) Which of the following operators are used in conjunction with the this and super
references?
a.The new operator b.The instanceof operator c.The dot operator
Ans: c.
Ans: a.
Ans: c.
Ans: a.
37) When an object is referenced, does this mean that it has been identified by the finalizer
method for garbage collection?
a.yes b.no
Ans: b.
38) Because finalize () belongs to the java.lang.Object class, it is present in all ___.
a.objects b.classes c.methods
Ans: b.
Ans: a,c.
40) When you write finalize() method for your class, you are overriding a finalizer
inherited from a super class.
Page 30 of 114
a.true b.false
Ans: a.
41) Java memory management mechanism garbage collects objects which are no longer
referenced
a true b.false
Ans: a.
42) are objects referenced by a variable candidates for garbage collection when the
variable goes out of scope?
a yes b. no
Ans: a.
43) Java's garbage collector runs as a ___ priority thread waiting for __priority threads to
relinquish the processor.
a.high b.low
Ans: a,b.
44) The garbage collector will run immediately when the system is out of memory
a.true b.false
Ans: a.
45) You can explicitly drop a object reference by setting the value of a variable whose data
type is a reference type to ___
Ans: null
46) When might your program wish to run the garbage collecter?
a. before it enters a compute-intense section of code
b. before it enters a memory-intense section of code
c. before objects are finalized
d. when it knows there will be some idle time
Ans: a,b,d
47) For externalizable objects the class is solely responsible for the external format of its
contents
a.true b.false
Ans: a
48) When an object is stored, are all of the objects that are reachable from that object
stored as well?
a.true b.false
Ans: a
49) The default__ of objects protects private and trancient data, and supports the __ of the
classes
a.evolution b.encoding
Page 31 of 114
Ans: b,a.
Ans : d and e
51) When must the main class and the file name coincide?
Ans : When class is declared public.
Ans : c
Use: * It specifies to which package the classes defined in a file belongs to. * Package is
both naming and a visibility control mechanism.
Where as "java.applet.*" will import all the classes from java.applet package.
Page 32 of 114
4) What is interface? What is use of interface?
Ans : It is similar to class which may contain method's signature only but not bodies.
Methods declared in interface are abstract methods. We can implement many interfaces on
a class which support the multiple inheritance.
In Interface we need not use the keyword abstract for the methods.
Ans : True
10) Java compiler stores the .class files in the path specified in CLASSPATH environmental
variable.
True/False
Ans : False
11) User-defined package can also be imported just like the standard packages.
True/False
Ans : True
12) When a program does not want to handle exception, the ______class is used.
Ans : Throws
16) The catch clause of the user-defined exception class should ______ its Base class
catch clause.
Ans : Exception
Page 33 of 114
17) A _______ is used to separate the hierarchy of the class while declaring an
Import statement.
Ans : Package
18) All standard classes of Java are included within a package called _____.
Ans : java.lang
19) All the classes in a package can be simultaneously imported using ____.
Ans : *
20) Can you define a variable inside an Interface. If no, why? If yes, how?
Ans.: YES. final and static
21) How many concrete classes can you have inside an interface?
Ans.: None
23) Is it necessary to implement all the methods of an interface while implementing the
interface?
Ans.: No
24) If you do not implement all the methods of an interface while implementing , what
specifier should you use for the class ?
Ans.: abstract
Ans : a.
28) Can variables be declared in an interface ? If so, what are the modifiers?
Ans : Yes. final and static are the modifiers can be declared in an interface.
29) What are the possible access modifiers when implementing interface methods?
Ans : public.
Ans : b.
Page 34 of 114
32) Name interfaces without a method?
Ans : Serializable, Cloneble & Remote.
Exception Handling
1) What is the difference between 'throw' and 'throws' ?And it's application?
Ans : Exceptions that are thrown by java runtime systems can be handled by Try and catch
blocks. With throw exception we can handle the exceptions thrown by the program itself. If
a method is capable of causing an exception that it does not handle, it must specify this
behavior so the callers of the method can guard against that exception.
Error defines exceptions that are not excepted to be caught by you program. Example is
Stack Overflow.
Ans :
Signature is..
type method-name (parameter-list) throws exception-list
9) The finally block is executed when an exception is thrown, even if no catch matches it.
True/False
Page 35 of 114
Ans : True
10) The subclass exception should precede the base class exception when used within the
catch clause.
True/False
Ans : True
Ans : True
12) The statements following the throw keyword in a program are not executed.
True/False
Ans : True
Ans : True
MULTI THREADING
5) What is the data type for the method isAlive() and this method is
available in which class?
Ans : boolean, Thread
7) What are all the methods used for Inter Thread communication and what is the class in
which these methods are defined?
Ans :1. wait(),notify() & notifyall() 2. Object class
8) What is the mechanisam defind by java for the Resources to be used by only one Thread
at a time?
Ans : Synchronisation
Page 36 of 114
9) What is the procedure to own the moniter by many threads?
Ans : not possible
11) What is the data type for the parameter of the sleep() method?
Ans : long
12) What are all the values for the following level?
1,max-priority , 2,min-priority, 3,normal-priority
Ans : 10,1,5
14) What is the default thread at the time of starting the program?
Ans : main thread
Ans : False
16) Which priority Thread can prompt the lower primary Thread?
Ans : Higher Priority
18) What are all the four states associated in the thread?
Ans : 1. new 2. runnable 3. blocked 4. dead
Ans : False
20) The run() method should necessary exists in clases created as subclass of thread?
True /False
Ans : True
21) When two threads are waiting on each other and can't proceed the programe is said to
be in a deadlock?
True/False
Ans : True
Page 37 of 114
Ans : join() method
1) wait(),notify(),notifyall() are defined as final & can be called only from with in a
synchronized method
2) Among wait(),notify(),notifyall() the wait() method only throws IOException
3) wait(),notify(),notifyall() & sleep() are methods of object class
1
2
3
1&2
1,2 & 3
Ans : D
26) What is meant by daemon thread? In java runtime, what is it's role?
Ans : Daemon thread is a low priority thread which runs intermittently in the background
doing the garbage collection operation for the java runtime system.
Inheritance
Ans : False
Ans : True
Page 38 of 114
7) Java supports multiple inheritance?
True/False
Ans : False
8) What is inheritance?
Ans : Deriving an object from an existing class. In the other words, Inheritance is the
process of inheriting all the features from a class
10) Which method is used to call the constructors of the superclass from the subclass?
Ans : super(argument)
11) Which is used to execute any method of the superclass from the subclass?
Ans : super.method-name(arguments)
12) Which methods are used to destroy the objects created by the constructor methods?
Ans : finalize()
Ans : False
Ans: True
Ans : True
Page 39 of 114
Ans : An abstract class may not be declared as final.
24) What modifiers may be used with an inner class that is a member of an outer class?
Ans : a (non-local) inner class may be declared as public, protected, private, static, final or
abstract.
Ans: c
a)Non-abstract
b)Implemented
c)unimplemented
Ans:c
Page 40 of 114
1.what is a transient variable?
Ans.: A transient variable is a variable that may not be serialized.
7. What's new with the stop(), suspend() and resume() methods in JDK 1.2?
Ans.: The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
8. Is null a keyword?
Ans.: The null value is not a keyword.
12. What state does a thread enter when it terminates its processing?
Ans.: When a thread terminates its processing, it enters the dead state.
14. Which characters may be used as the second character of an identifier, but not as the
first character of an identifier?
Ans.: The digits 0 through 9 may not be used as the first character of an identifier but they
may be used after the first character of an identifier.
Page 41 of 114
15. What is the List interface?
Ans.: The List interface provides support for ordered collections of objects.
18. What modifiers may be used with an inner class that is a member of an outer class?
Ans.: A (non-local) inner class may be declared as public, protected, private, static, final, or
abstract.
20. What is the difference between the >> and >>> operators?
Ans.: The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that
have been shifted out.
21. Which method of the Component class is used to set the position and size of a
component?
Ans.: setBounds()
22. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Ans.: Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set
uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8,
16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
27. Does garbage collection guarantee that a program will not run out of memory?
Ans.: Garbage collection does not guarantee that a program will not run out of memory. 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
28. What restrictions are placed on the location of a package statement within a source
code file?
Ans.: A package statement must appear as the first line in a source code file (excluding
blank lines and comments).
Page 42 of 114
29. Can an object's finalize() method be invoked while it is reachable?
Ans.: An object's finalize() method cannot be invoked by the garbage collector while the
object is still reachable. However, an object's finalize() method may be invoked by other
objects.
31. What is the difference between preemptive scheduling and time slicing?
Ans.: Under preemptive scheduling, the highest priority task executes until it enters the
waiting or dead states or a higher priority task comes into existence. Under time slicing, a
task executes for a predefined slice of time and then reenters the pool of ready tasks. The
scheduler then determines which task should execute next, based on priority and other
factors.
33. What value does readLine() return when it has reached the end of a file?
Ans.: The readLine() method returns null when it has reached the end of a file.
38. What are order of precedence and associativity, and how are they used?
Ans.: Order of precedence determines the order in which operators are evaluated in
expressions. Associatity determines whether an expression is evaluated left-to-right or right-
to-left
Page 43 of 114
43. What is a task's priority and how is it used in scheduling?
Ans.: A task's priority is an integer value that identifies the relative order in which it should
be executed with respect to other tasks. The scheduler attempts to schedule higher priority
tasks before lower priority tasks.
45. When a thread is created and started, what is its initial state?
Ans.: A thread is in the ready state after it has been created and started.
49. In which package are most of the AWT events that support the event-delegation model
defined?
Ans.: Most of the AWT-related events of the event-delegation model are defined in the
java.awt.event package. The AWTEvent class is defined in the java.awt package.
54. What is the difference between the Boolean & operator and the && operator?
Ans.: If an expression involving the Boolean & operator is evaluated, both operands are
evaluated. Then the & operator is applied to the operand. When an expression involving the
&& operator is evaluated, the first operand is evaluated. If the first operand returns a value
of true then the second operand is evaluated. The && operator is then applied to the first
and second operands. If the first operand evaluates to false, the evaluation of the second
operand is skipped.
Page 44 of 114
Ans.: Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or
TextComponent
57. Which Container method is used to cause a container to be laid out and redisplayed?
Ans.: validate()
59. How many times may an object's finalize() method be invoked by the garbage collector?
Ans.: An object's finalize() method may only be invoked once by the garbage collector.
65. What is the difference between a break statement and a continue statement?
Ans.: A break statement results in the termination of the statement to which it applies
(switch, for, do, or while). A continue statement is used to end the current loop iteration and
return control to the loop statement.
67. What method is invoked to cause an object to begin executing as a separate thread?
Ans.: The start() method of the Thread class is invoked to cause an object to begin
executing as a separate thread.
69. What is the advantage of the event-delegation model over the earlier event-inheritance
model?
Ans.: 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
Page 45 of 114
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.
71. How are commas used in the intialization and iteration parts of a for statement?
Ans.: Commas are used to separate multiple statements within the initialization and
iteration parts of a for statement.
72. What is the purpose of the wait(), notify(), and notifyAll() methods?
Ans.: The wait(),notify(), and notifyAll() methods are used to provide an efficient way for
threads to wait for a shared resource. When a thread executes an object's wait() method, it
enters the waiting state. It only enters the ready state after another thread invokes the
object's notify() or notifyAll() methods.
75. What is the relationship between the Canvas class and the Graphics class?
Ans.: A Canvas object provides access to a Graphics object via its paint() method.
77. What value does read() return when it has reached the end of a file?
Ans.: The read() method returns -1 when it has reached the end of a file.
79. What is the difference between a static and a non-static inner class?
Ans.: A non-static inner class may have object instances that are associated with instances
of the class's outer class. A static inner class does not have any object instances.
80. What is the difference between the String and StringBuffer classes?
Ans.: String objects are constants. StringBuffer objects are not.
Page 46 of 114
Ans.: An object's lock is a mechanism that is used by multiple threads to obtain
synchronized access to the object. A thread may execute a synchronized method of an
object only after it has acquired the object's lock. All objects and classes have locks. A
class's lock is acquired on the class's Class object.
91. What is the difference between the Font and FontMetrics classes?
Ans.: The FontMetrics class is used to define implementation-specific properties, such as
ascent and descent, of a Font object.
94. What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream class hierarchy?
Ans.: The Reader/Writer class hierarchy is character-oriented, and the
InputStream/OutputStream class hierarchy is byte-oriented.
Page 47 of 114
Ans.: A catch clause can catch any exception that may be assigned to the Throwable type.
This includes the Error and Exception types.
96. If a class is declared without any access modifiers, where may the class be accessed?
Ans.: A class that is declared without any access modifiers is said to have package access.
This means that the class can only be accessed by other classes and interfaces that are
defined within the same package.
Page 48 of 114
101. What is the purpose of the System class?
Ans.: The purpose of the System class is to provide access to system resources.
102. Which TextComponent method is used to set a TextComponent to the read-only state?
Ans.: setEditable()
106. Which class should you use to obtain design information about an object?
Ans.: The Class class is used to obtain information about an object's design.
110. What restrictions are placed on the values of each case of a switch statement?
Ans.: During compilation, the values of each case of a switch statement must evaluate to a
value that can be promoted to an int value.
Page 49 of 114
113. What is the highest-level event class of the event-delegation model?
Ans.: The java.util.EventObject class is the highest-level class in the event-delegation class
hierarchy.
118. What advantage do Java's layout managers provide over traditional windowing
systems?
Ans.: Java uses layout managers to lay out components in a consistent manner across all
windowing platforms. Since Java's layout managers aren't tied to absolute sizing and
positioning, they are able to accomodate platform-specific differences among windowing
systems.
122. What is the difference between the paint() and repaint() methods?
Ans.: The paint() method supports painting via a Graphics object. The repaint() method is
used to cause paint() to be invoked by the AWT painting thread.
Page 50 of 114
123. What is the purpose of the File class?
Ans.: The File class is used to create objects that provide access to the files and directories
of a local file system.
125. Which Math method is used to calculate the absolute value of a number?
Ans.: The abs() method is used to calculate absolute values.
126. How does multithreading take place on a computer with a single CPU?
Ans.: The operating system's task scheduler allocates execution time to multiple tasks. By
quickly switching between executing tasks, it creates the impression that tasks execute
sequentially.
127. When does the compiler supply a default constructor for a class?
Ans.: The compiler supplies a default constructor for a class if no other constructors are
provided.
131. How can the Checkbox class be used to create a radio button?
Ans.: By associating Checkbox objects with a CheckboxGroup.
132. Which non-Unicode letter characters may be used as the first character of an
identifier?
Ans.: The non-Unicode letter characters $ and _ may appear as the first character of an
identifier
Page 51 of 114
134. What happens when you invoke a thread's interrupt method while it is sleeping or
waiting?
Ans.: When a task's interrupt() method is executed, the task enters the ready state. The
next time the task enters the running state, an InterruptedException is thrown.
139. What class of exceptions are generated by the Java run-time system?
Ans.: The Java runtime system generates RuntimeException and Error exceptions.
140. What class allows you to read objects directly from a stream?
Ans.: The ObjectInputStream class supports the reading of objects from input streams.
141. What is the difference between a field variable and a local variable?
Ans.: A field variable is a variable that is declared as a member of a class. A local variable
is a variable that is declared local to a method.
142. Under what conditions is an object's finalize() method invoked by the garbage
collector?
Ans.: The garbage collector invokes an object's finalize() method when it detects that the
object has become unreachable.
Page 52 of 114
144. What is the relationship between a method's throws clause and the exceptions that
can be thrown during the method's execution?
Ans.: A method's throws clause must declare any checked exceptions that are not caught
within the body of the method.
145. What is the difference between the JDK 1.02 event model and the event-delegation
model introduced with JDK 1.1?
Ans.: The JDK 1.02 event model uses an event inheritance or bubbling approach. In this
model, components are required to handle their own events. If they do not handle a
particular event, the event is inherited by (or bubbled up to) the component's container. The
container then either handles the event or it is bubbled up to its container and so on, until
the highest-level container has been tried.
In the event-delegation model, specific objects are designated as event handlers for GUI
components. These objects implement event-listener interfaces. The event-delegation
model is more efficient than the event-inheritance model because it eliminates the
processing required to support the bubbling of unhandled events.
146. How is it possible for two String objects with identical values not to be equal under the
== operator?
Ans.: The == operator compares two objects to determine if they are the same object in
memory. It is possible for two String objects to have the same value, but located indifferent
areas of memory.
Page 53 of 114
153. If an object is garbage collected, can it become reachable again?
Ans.: Once an object is garbage collected, it ceases to exist. It can no longer become
reachable again.
160. What is the difference between the File and RandomAccessFile classes?
Ans.: The File class encapsulates the files and directories of the local file system. The
RandomAccessFile class provides the methods needed to directly access data contained in
any part of a file.
Page 54 of 114
164. What interface must an object implement before it can be written to a stream as an
object?
Ans.: An object must implement the Serializable or Externalizable interface before it can be
written to a stream as an object.
174. What are three ways in which a thread can enter the waiting state?
Ans.: A thread can enter the waiting state by invoking its sleep() method, by blocking on
I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's
wait() method. It can also enter the waiting state by invoking its (deprecated) suspend()
method.
Page 55 of 114
175. Can an abstract class be final?
Ans.: An abstract class may not be declared as final.
177. What happens if a try-catch-finally statement does not have a catch clause to handle
an exception that is thrown within the body of the try statement?
Ans.: The exception propagates up to the next higher level try-catch statement (if any) or
results in the program's termination.
183. What is the difference between the prefix and postfix forms of the ++ operator?
Ans.: The prefix form performs the increment operation and returns the value of the
increment operation. The postfix form returns the current value all of the expression and
then performs the increment operation on that value.
Page 56 of 114
185. What is a Java package and how is it used?
Ans.: A Java package is a naming context for classes and interfaces. A package is used to
create a separate name space for groups of classes and interfaces. Packages are also
used to organize related classes and interfaces into a single API unit and to control
accessibility to these classes and interfaces.
187. What are the Object and Class classes used for?
Ans.: The Object class is the highest-level class in the Java class hierarchy. The Class
class is used to represent the classes and interfaces that are loaded by a Java program.
188. How does a try statement determine which catch clause should be used to handle an
exception?
Ans.: When an exception is thrown within the body of a try statement, the catch clauses of
the try statement are examined in the order in which they appear. The first catch clause that
is capable of handling the exception is executed.
192. What methods are used to get and set the text label displayed by a Button object?
Ans.: getLabel() and setLabel()
195. What are the two basic ways in which classes that can be run as threads may be
defined?
Ans.: A thread class may be declared as a subclass of Thread, or it may implement the
Runnable interface.
Page 57 of 114
196. What are the problems faced by Java programmers who don't use layout managers?
Ans.: Without layout managers, Java programmers are faced with determining how their
GUI will be displayed across multiple windowing systems and finding a common sizing and
positioning that will work within the constraints imposed by each windowing system.
Page 58 of 114
Question 1)
Which of the following lines will compile without warning or error.
1) float f=1.3;
2) char c="a";
3) byte b=257;
4) boolean b=null;
5) int i=10;
Question 2)
What will happen if you try to compile and run the following code
public class MyClass {
public static void main(String arguments[]) {
amethod(arguments);
}
public void amethod(String[] arguments) {
System.out.println(arguments);
System.out.println(arguments[1]);
}
}
1) error Can't make static reference to void amethod.
2) error method main not correct
3) error array must include parameter
4) amethod must be declared with String
Question 3)
Which of the following will compile without error
1)
import java.awt.*;
package Mypackage;
class Myclass {}
2)
package MyPackage;
import java.awt.*;
class MyClass{}
3)
/*This is a comment */
package MyPackage;
import java.awt.*;
class MyClass{}
Question 4)
A byte can be of what size
1) -128 to 127
2) (-2 power 8 )-1 to 2 power 8
3) -255 to 256
4)depends on the particular implementation of the Java Virtual machine
Question 5)
Page 59 of 114
What will be printed out if this code is run with the following command line?
java myprog good morning
public class myprog{
public static void main(String argv[])
{
System.out.println(argv[2])
}
}
1) myprog
2) good
3) morning
4) Exception raised: "java.lang.ArrayIndexOutOfBoundsException: 2"
Question 6)
Which of the following are keywords or reserved words in Java?
1) if
2) then
3) goto
4) while
5) case
Question 7)
Which of the following are legal identifiers
1) 2variable
2) variable2
3) _whatavariable
4) _3_
5) $anothervar
6) #myvar
Question 8)
What will happen when you compile and run the following code?
Question 9)
What will happen if you try to compile and run the following code?
public class Q {
public static void main(String argv[]){
Page 60 of 114
int anar[]=new int[]{1,2,3};
System.out.println(anar[1]);
}
}
1) 1
2) Error anar is referenced before it is initialized
3) 2
4) Error: size of array must be defined
Question 10)
What will happen if you try to compile and run the following code?
public class Q {
public static void main(String argv[]){
int anar[]=new int[5];
System.out.println(anar[0]);
}
}
1) Error: anar is referenced before it is initialized
2) null
3) 0
4) 5
Question 11)
What will be the result of attempting to compile and run the following code?
abstract class MineBase {
abstract void amethod();
static int i;
}
public class Mine extends MineBase {
public static void main(String argv[]){
int[] ar=new int[5];
for(i=0;i < ar.length;i++)
System.out.println(ar[i]);
}
}
1) a sequence of 5 0's will be printed
2) Error: ar is used before it is initialized
3) Error Mine must be declared abstract
4) IndexOutOfBoundes Error
Question 12)
What will be printed out if you attempt to compile and run the following code ?
int i=1;
switch (i) {
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
case 2:
Page 61 of 114
System.out.println("two");
default:
System.out.println("default");
}
1) one
2) one, default
3) one, two, default
4) default
Question 13)
What will be printed out if you attempt to compile and run the following code?
int i=9;
switch (i) {
default:
System.out.println("default");
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
case 2:
System.out.println("two");
}
1) default
2) default, zero
3) error default clause not defined
4) no output displayed
Question 14)
Which of the following lines of code will compile without error
1)
int i=0;
if(i) {
System.out.println("Hello");
}
2)
boolean b=true;
boolean b2=true;
if(b==b2) {
System.out.println("So true");
}
3)
int i=1;
int j=2;
if(i==1|| j==2)
System.out.println("OK");
4)
int i=1;
int j=2;
if(i==1 &| j==2)
System.out.println("OK");
Question 15)
Page 62 of 114
What will be output if you try to compile and run the following code, but there is
no file called Hello.txt in the current directory?.
import java.io.*;
public class Mine {
public static void main(String argv[]){
Mine m=new Mine();
System.out.println(m.amethod());
}
public int amethod() {
try {
FileInputStream dis=new FileInputStream("Hello.txt");
}catch (FileNotFoundException fne) {
System.out.println("No such file found");
return -1;
}catch(IOException ioe) {
} finally{
System.out.println("Doing finally");
}
return 0;
}
}
1) No such file found
2 No such file found ,-1
3) No such file found, Doing finally, -1
4) 0
Question 16)
Which of the following statements are true?
1) Methods cannot be overriden to be more private
2) Static methods cannot be overloaded
3) Private methods cannot be overloaded
4) An overloaded method cannot throw exceptions not checked in the base class
Question 17)
What will happen if you attempt to compile and run the following code?
1) Compile and run without error
2) Compile time Exception
3) Runtime Exception
class Base {}
class Sub extends Base {}
class Sub2 extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=(Sub) b;
}
}
Question 18)
Which of the following statements are true?
Page 63 of 114
1) System.out.println( -1 >>> 2);will output a result larger than 10
2) System.out.println( -1 >>> 2); will output a positive number
3) System.out.println( 2 >> 1); will output the number 1
4) System.out.println( 1 <<< 2); will output the number 4
Question 19)
You are browsing the Java HTML documentation for information on the
java.awt.TextField component. You want to create Listener code to respond to focus
events. The only Listener method listed is addActionListener. How do you go about
finding out about Listener methods?
1) Define your own Listener interface according to the event to be tracked
2) Use the search facility in the HTML documentation for the listener needed
3) Move up the hierarchy in the HTML documentation to locate methods in base
classes
4) Subclass awt.event with the appropriate Listener method
Question 20)
What will be displayed when you attempt to compile and run the following code
//Code start
import java.awt.*;
public class Butt extends Frame{
public static void main(String argv[]){
Butt MyBut=new Butt();
}
Butt(){
Button HelloBut=new Button("Hello");
Button ByeBut=new Button("Bye");
add(HelloBut);
add(ByeBut);
setSize(300,300);
setVisible(true);
}
}
//Code end
1) Two buttons side by side occupying all of the frame, Hello on the left and Bye on
the right
2) One button occupying the entire frame saying Hello
3) One button occupying the entire frame saying Bye
4) Two buttons at the top of the frame one saying Hello the other saying Bye
Question 21)
Page 64 of 114
for(j=1; j<3; j++) {
if (j==2)
continue outer;
System.out.println("Value for i=" + i + " Value for j=" +j);
}
}
}
1) Value for i=1 value for j=1
2) Value for i=2 value for j=1
3) Value for i=2 value for j=2
4) Value for i=3 value for j=1
Question 22)
If g is a graphics instance what will the following code draw on the screen?.
g.fillArc(45,90,50,50,90,180);
1) An arc bounded by a box of height 45, width 90 with a centre point of 50,50, starting
at an angle of 90 degrees traversing through 180 degrees counter clockwise.
2) An arc bounded by a box of height 50, width 50, with a centre point of 45,90 starting
at an angle of 90 degrees traversing through 180 degrees clockwise.
3) An arc bounded by a box of height 50, width 50, with a top left at coordinates of 45,
90, starting at 90 degrees and traversing through 180 degrees counter clockwise.
4) An arc starting at 45 degrees, traversing through 90 degrees clockwise bounded by a
box of height 50, width 50 with a centre point of 90, 180.
Question 23)
Which of the following methods can be legally inserted in place of the comment //Method
Here ?
class Base{
public void amethod(int i) { }
}
public class Scope extends Base{
public static void main(String argv[]){
}
//Method Here
}
1) void amethod(int i) throws Exception {}
2) void amethod(long i)throws Exception {}
3) void amethod(long i){}
4) public void amethod(int i) throws Exception {}
Question 24)
Page 65 of 114
3) System.out.println(Math.ceil(-4.7));
4) System.out.println(Math.min(-4.7));
Question 25)
What will happen if you attempt to compile and run the following code?
Integer ten=new Integer(10);
Long nine=new Long (9);
System.out.println(ten + nine);
int i=1;
System.out.println(i + ten);
1) 19 followed by 20
2) 19 followed by 11
3) Error: Can't convert java lang Integer
4) 10 followed by 1
Question 26)
Question 27)
If you wanted to find out where the position of the letter v (ie return 2) in the string s
containing "Java", which of the following could you use?
1) mid(2,s);
2) charAt(2);
3) s.indexOf('v');
4) indexOf(s,'v');
Question 28)
Given the following declarations
String s1=new String("Hello")
String s2=new String("there");
String s3=new String();
Which of the following are legal operations?
1) s3=s1 + s2;
2) s3=s1-s2;
3) s3=s1 & s2;
4) s3=s1 && s2
Question 29)
Page 66 of 114
What is the result of the following operation?
System.out.println(4 | 3);
1) 6
2) 0
3) 1
4) 7
Question 30)
public class MyClass1 {
public static void main(String argv[]){ }
/*Modifier at XX */ class MyInner {}
}
What modifiers would be legal at XX in the above code?
1) public
2) private
3) static
4) friend
Question 31)
Question 32)
An Applet has its Layout Manager set to the default of FlowLayout. What code would be
correct to change to another Layout Manager.
1) setLayoutManager(new GridLayout());
2) setLayout(new GridLayout(2,2));
3) setGridLayout(2,2);
4) setBorderLayout();
Question 33)
What will happen when you attempt to compile and run the following code?.
1) It will compile and the run method will print out the increasing value of i.
2) It will compile and calling start will print out the increasing value of i.
3) The code will cause an error at compile time.
4) Compilation will cause an error because while cannot take a parameter of true.
class Background implements Runnable{
int i=0;
public int run(){
while(true){
i++;
System.out.println("i="+i);
Page 67 of 114
} //End while
return 1;
}//End run
}//End class
Question 34)
You have created an applet that draws lines. You have overriden the paint operation and
used the graphics drawLine method, and increase one of its parameters to multiple lines
across the screen. When you first test the applet you find that the news lines are redrawn,
but the old lines are erased. How can you modify your code to allow the old lines to stay on
the screen instead of being cleared.
1) Override repaint thus
public void repaint(Graphics g){
paint(g);
}
2)Override update thus
public void update(Graphics g) {
paint(g);
}
3) turn off clearing with the method setClear();
4) Remove the drawing from the paint Method and place in the calling code
Question 35)
What will be the result when you attempt to compile and run the following code?.
public class Conv{
public static void main(String argv[]){
Conv c=new Conv();
String s=new String("ello");
c.amethod(s);
}
public void amethod(String s){
char c='H';
c+=s;
System.out.println(c);
}
}
1) Compilation and output the string "Hello"
2) Compilation and output the string "ello"
3) Compilation and output the string elloH
4) Compile time error
Question 36)
Given the following code, what test would you need to put in place of the comment line?
//place test here
to result in an output of
Equal
Page 68 of 114
public class EqTest{
public static void main(String argv[]){
EqTest e=new EqTest();
}
EqTest(){
String s="Java";
String s2="java";
//place test here {
System.out.println("Equal");
}else
{
System.out.println("Not equal");
}
}
}
1) if(s==s2)
2) if(s.equals(s2)
3) if(s.equalsIgnoreCase(s2))
4)if(s.noCaseMatch(s2))
Question 37)
Given the following code
import java.awt.*;
public class SetF extends Frame{
public static void main(String argv[]){
SetF s=new SetF();
s.setSize(300,200);
s.setVisible(true);
}
}
How could you set the frame surface color to pink
1)s.setBackground(Color.pink);
2)s.setColor(PINK);
3)s.Background(pink);
4)s.color=Color.pink
Question 38)
How can you change the current working directory using an instance of the File class called
FileName?
1) FileName.chdir("DirName")
2) FileName.cd("DirName")
3) FileName.cwd("DirName")
4) The File class does not support directly changing the current directory.
Question 39)
If you create a TextField with a constructor to set it to occupy 5 columns, what difference
will it make if you use it with a proportional font (ie Times Roman) or a fixed pitch typewriter
style font (Courier).
1)With a fixed font you will see 5 characters, with a proportional it will depend on the width
of the characters
2)With a fixed font you will see 5 characters,with a proportional it will cause the field to
Page 69 of 114
expand to fit the text
3)The columns setting does not affect the number of characters displayed
4)Both will show exactly 5 characters
Question 40)
Given the following code how could you invoke the Base constructor that will print out the
string "base constructor";
class Base{
Base(int i){
System.out.println("base constructor");
}
Base(){
}
}
public class Sup extends Base{
public static void main(String argv[]){
Sup s= new Sup();
//One
}
Sup()
{
//Two
}
public void derived()
{
//Three
}
}
1) On the line After //One put Base(10);
2) On the line After //One put super(10);
3) On the line After //Two put super(10);
4) On the line After //Three put super(10);
Question 41)
Given the following code what will be output?
public class Pass{
static int j=20;
public static void main(String argv[]){
int i=10;
Pass p = new Pass();
p.amethod(i);
System.out.println(i);
System.out.println(j);
}
public void amethod(int x){
x=x*2;
j=j*2;
}
}
1) Error: amethod parameter does not match variable
2) 20 and 40
3) 10 and 40
4) 10, and 20
Question 42)
Page 70 of 114
What code placed after the comment //For loop would populate the elements of the array
ia[] with values of the variable i.?
public class Lin{
public static void main(String argv[]){
Lin l = new Lin();
l.amethod();
}
public void amethod(){
int ia[] = new int[4];
//Start For loop
{
ia[i]=i;
System.out.println(ia[i]);
}
}
}
1) for(int i=0; i < ia.length() -1; i++)
2) for (int i=0; i< ia.length(); i++)
3) for(int i=1; i < 4; i++)
4) for(int i=0; i< ia.length;i++)
Question 43)
What will be the result when you try to compile and run the following code?
private class Base{
Base(){
int i = 100;
System.out.println(i);
}
}
public class Pri extends Base{
static int i = 200;
public static void main(String argv[]){
Pri p = new Pri();
System.out.println(i);
}
}
1) Error at compile time
2) 200
3) 100 followed by 200
4) 100
Question 44)
What will the following code print out?
public class Oct{
public static void main(String argv[]){
Oct o = new Oct();
o.amethod();
}
public void amethod(){
int oi= 012;
System.out.println(oi);
}
}
Page 71 of 114
1)12
2)012
3)10
4)10.0
Question 45
What will happen when you try compiling and running this code?
public class Ref{
public static void main(String argv[]){
Ref r = new Ref();
r.amethod(r);
}
public void amethod(Ref r){
int i=99;
multi(r);
System.out.println(i);
}
public void multi(Ref r){
r.i = r.i*2;
}
}
1) Error at compile time
2) An output of 99
3) An output of 198
4) An error at runtime
Question 46)
You need to create a class that will store a unique object elements. You do not need to sort
these elements but they must be unique.
What interface might be most suitable to meet this need?
1)Set
2)List
3)Map
4)Vector
Question 47)
Which of the following will successfully create an instance of the Vector class and add an
element?
1) Vector v=new Vector(99);
v[1]=99;
Page 72 of 114
4 Vector v=new Vector(100);
v.addElement("99");
Question 48)
You have created a simple Frame and overridden the paint method as follows
public void paint(Graphics g){
g.drawString("Dolly",50,10);
}
What will be the result when you attempt to compile and run the program?
1) The string "Dolly" will be displayed at the centre of the frame
2) An error at compilation complaining at the signature of the paint method
3) The lower part of the word Dolly will be seen at the top of the frame, with the top hidden.
4) The string "Dolly" will be shown at the bottom of the frame.
Question 49)
What will be the result when you attempt to compile this program?
public class Rand{
public static void main(String argv[]){
int iRand;
iRand = Math.random();
System.out.println(iRand);
}
}
1) Compile time error referring to a cast problem
2) A random number between 1 and 10
3) A random number between 0 and 1
4) A compile time error about random being an unrecognised method
Question 50)
Given the following code
import java.io.*;
public class Th{
public static void main(String argv[]){
Th t = new Th();
t.amethod();
}
public void amethod(){
try{
ioCall();
}catch(IOException ioe){}
}
}
What code would be most likely for the body of the ioCall method
1) public void ioCall ()throws IOException{
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
2) public void ioCall ()throw IOException{
DataInputStream din = new DataInputStream(System.in);
din.readChar();
Page 73 of 114
}
3) public void ioCall (){
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
4) public void ioCall throws IOException(){
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
Question 51)
What will happen when you compile and run the following code?
public class Scope{
private int i;
public static void main(String argv[]){
Scope s = new Scope();
s.amethod();
}//End of main
public static void amethod(){
System.out.println(i);
}//end of amethod
}//End of class
1) A value of 0 will be printed out
2) Nothing will be printed out
3) A compile time error
4) A compile time error complaining of the scope of the variable i
Question 52)
You want to lay out a set of buttons horizontally but with more space between the first
button and the rest. You are going to use the GridBagLayout manager to control the way the
buttons are set out. How will you modify the way the GridBagLayout acts in order to change
the spacing around the first button?
1) Create an instance of the GridBagConstraints class, call the weightx() method and then
pass the GridBagConstraints instance with the component to the setConstraints method of
the GridBagLayout class.
2) Create an instance of the GridBagConstraints class, set the weightx field and then pass
the GridBagConstraints instance with the component to the setConstraints method of the
GridBagLayout class.
3) Create an instance of the GridBagLayout class, set the weightx field and then call the
setConstraints method of the GridBagLayoutClass with the component as a parameter.
4) Create an instance of the GridBagLayout class, call the setWeightx() method and then
pass the GridBagConstraints instance with the component to the setConstraints method of
the GridBagLayout class.
Question 53)
Which of the following can you perform using the File class?
Page 74 of 114
1) Change the current directory
2) Return the name of the parent directory
3) Delete a file
4) Find if a file contains text or binary information
Question 54)
Which of the following code fragments will compile without error
1)
public void paint(Graphics g){
int polyX[] = {20,150,150};
int polyY[]= {20,20,120};
g.drawPolygon(polyX, polyY,3);
}
2)
public void paint(Graphics g){
int polyX[] = {20,150,150};
int polyY[]= {20,20,120};
g.drawPolygon(polyX, polyY);
}
3)
public void paint(Graphics g){
int polyX[3] = {20,150,150};
int polyY[3]= {20,20,120};
g.drawPolygon(polyX, polyY,3);
}
4)
public void paint(Graphics g){
int polyX[] = {20,150,150};
int polyY[]= {20,20,120};
drawPolygon(polyX, polyY);
}
Question 55)
You are concerned that your program may attempt to use more memory than is available.
To avoid this situation you want to ensure that the Java Virtual Machine will run its garbage
collection just before you start a complex routine. What can you do to be certain that
garbage collection will run when you want .
1) You cannot be certain when garbage collection will run
2) Use the Runtime.gc() method to force garbage collection
3) Ensure that all the variables you require to be garbage collected are set to null
4) Use the System.gc() method to force garbage collection
Question 56)
You are using the GridBagLayout manager to place a series of buttons on a Frame. You
want to make the size of one of the buttons bigger than the text it contains. Which of the
following will allow you to do that?
1) The GridBagLayout manager does not allow you to do this
2) The setFill method of the GridBagLayout class
3) The setFill method of the GridBagConstraints class
4) The fill field of the GridBagConstraints class
Page 75 of 114
Question 57)
Which of the following most closely describes a bitset collection?
1) A class that contains groups of unique sequences of bits
2) A method for flipping individual bits in instance of a primitive type
3) An array of boolean primitives that indicate zeros or ones
4) A collection for storing bits as on-off information, like a vector of bits
Question 58)
You have these files in the same directory. What will happen when you attempt to compile
and run Class1.java if you have not already compiled Base.java
//Base.java
package Base;
class Base{
protected void amethod(){
System.out.println("amethod");
}//End of amethod
}//End of class base
package Class1;
//Class1.java
public class Class1 extends Base{
Question 59)
What will happen when you attempt to compile and run the following code
class Base{
private void amethod(int iBase){
System.out.println("Base.amethod");
}
}
Page 76 of 114
1) Compile time error complaining that Base.amethod is private
2) Runtime error complaining that Base.amethod is private
3) Output of "Base.amethod"
4) Output of "Over.amethod"
Question 60)
You are creating an applet with a Frame that contains buttons. You are using the
GridBagLayout manager and you have added Four buttons. At the moment the buttons
appear in the centre of the frame from left to right. You want them to appear one on top of
the other going down the screen. What is the most appropriate way to do this.
1) Set the gridy value of the GridBagConstraint class to a value increasing from 1 to 4
2) set the fill value of the GridBagConstraint class to VERTICAL
3) Set the ipady value of the GridBagConstraint class to a value increasing from 0 to 4
4) Set the fill value of the GridBagLayout class to GridBag.VERTICAL
Java Quiz
Question 1.
Read this piece of code carefully
if("String".toString() == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");
Answers
Question 2.
Read this piece of code carefully
Page 77 of 114
Answers
1. the code will compile an print "Equal".
2. the code will compile an print "Not Equal".
3. the code will cause a compiler error
Question 3.
Read the code below. Will be the result of attempting to compile and run the code below.
Question 4.
Read the code below. Will be the result of attempting to compile and run the code below.
Page 78 of 114
question.method(null);
}
}
Answers
1. The code does not compile.
2. The code compiles cleanly and shows "StringBuffer Version".
3. The code compiles cleanly and shows "String Version"
4. The code throws an Exception at Runtime.
Question 5.
Read the following code below.
public interface AQuestion
{
public abstract void someMethod() throws Exception;
}
A Class implementing this interface should
Question 6.
An Interface can never be private or protected.
Answers
True
False
Question 7.
A Vector class in jdk 1.2
1. is public
2. is final
3. implements java.util.List
4. is serializable
5. has only One constructor
Page 79 of 114
Question 8.
A String Class
1. is final
2. is public
3. is serializable
4. has a constructor which takes a StingBuffer Object as an Argument
Question 9.
Question 10.
Answers
1. Compiler error complaining about access restriction of private variables of
AQuestion.
2. Compiler error complaining about forward referencing.
3. No error - The output is 0;
Page 80 of 114
4. No error - The output is 10;
Question 11.
public class AQuestion
{
private int i = giveMeJ();
private int j = 10;
Answers
Question 12.
public class AQuestion
{
public static void main(String args[])
{
System.out.println("Before Try");
try
{
}
catch(Throwable t)
{
System.out.println("Inside Catch");
}
System.out.println("At the End");
}
}
1. Compiler error complaining about the catch block, where no Throwable object can
ever be thrown.
2. Compiler error - Throwable Object can not be caught, only Exceptions must be
caught.
Page 81 of 114
3. No compiler error. The lines "Before Try" and "At the end" are printed on the screen.
Question 13.
Question 14.
The class java.lang.Exception
i. Is public
ii. Extends Throwable
iii. Implements Throwable
iv. Is serializable
Question 15.
Read this piece of code carefully
if("String".trim() == "String".trim())
System.out.println("Equal");
else
System.out.println("Not Equal");
Answers
1. the code will compile an print "Equal".
2. the code will compile an print "Not Equal".
Page 82 of 114
3. the code will cause a compiler error
Question 16.
Read this piece of code carefully
Answers
1. the code will compile an print "Equal".
2. the code will compile an print "Not Equal".
3. the code will cause a compiler error
Question 17.
The following lines of code
byte b = 0;
b += 1;
Question 18.
The following express
char c = -1;
1. will cause a compiler error as the range of character is between 0 and 2^16 - 1. Will
request for an explicit cast.
2. will not cause a compiler error and c will have the value -1;
3. c will not represent any ascii character.
4. c will still be a unicode character.
Page 83 of 114
Question 19.
Which of the following statements are true?
Question 20.
All the wrapper classes (Integer, Boolean, Float, Short, Long, Double and Character)
1. are public
2. are serializable
3. are immutatable
4. extend java.lang.Number
5. are final
Question 21.
Read this piece of code carefully
if("String".substring(0) == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");
Answers
1. the code will compile an print "Equal".
2. the code will compile an print "Not Equal".
3. the code will cause a compiler error
Question 22.
Read this piece of code carefully
if("String".substring(0,6) == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");
Answers
1. the code will compile an print "Equal".
Page 84 of 114
2. the code will compile an print "Not Equal".
3. the code will cause a compiler error
Question 23.
Read this piece of code carefully
if("String".replace('t','t') == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");
Answers
1. the code will compile an print "Equal".
2. the code will compile an print "Not Equal".
3. the code will cause a compiler error
Question 24.
An Anonymous Inner class
Question 25.
public class A
{
private void method1() throws Exception
{
throw new RuntimeException();
}
public void method2()
{
try
{
method1();
}
catch(RuntimeException e)
{
System.out.println("Caught Runtime Exception");
}
catch(Exception e)
{
System.out.println("Caught Exception");
}
}
Page 85 of 114
public static void main(String args[])
{
A a = new A();
a.method2();
}
}
The above lines of code -
Question 26.
public XXXX extends something1, something2
1. XXX should be an interface,something1 and something2 need not, for the expression
to be legal
2. XXX should be a class, something1 and something2 must be interfaces for the
expression to be legal.
3. XXX, something1 and something2 must be interfaces for the expression to be legal.
4. The above statement is alway illegal in Java as multiple inheritance is not supported.
Question 27.
public class ADirtyOne
{
char a = '\u000A';
}
An attempt to compile the above class
1. will complete successfully.
2. will not compile as 0x000A is out of range for unicode charaters.
3. will complain about illegal character assignment
4. will compile but will cause a runtime error in accessing the variable.
Question 28.
public class ADirtyOne
{
//char a = '\u000A';
}
An attempt to compile the above class
1. will complete successfully.
Page 86 of 114
2. will compile sucessfully but with a warning message.
3. will not compile - complains on an invalid expression.
Question 29.
Question 30.
interface One
{
public void someMethod();
}
public class One_impl implements One
{
public native void someMethod();
}
Assuming that the native method is not provided in any local library, an attempt to compile
and run the above lines of code will cause
Page 87 of 114
Answers
1. the code will compile an print "Equal".
2. the code will compile an print "Not Equal".
3. the code will cause a compiler error
Question 32.
Read this piece of code carefully
System.out.println("String".substring(0,4));
Answers
1. the code will print "Strin" on the screen.
2. the code will print "Stri" on the screen.
3. the code will cause a compiler error.
Question 33.
Read this piece of code carefully
if("String".replace('g','G') == "String".replace('g','G'))
System.out.println("Equal");
else
System.out.println("Not Equal");
Answers
1. the code will compile an print "Equal".
2. the code will compile an print "Not Equal".
3. the code will cause a compiler error
Question 34.
Page 88 of 114
3. Cause no error and the value printed on the screen is one more than
Integer.MAX_VALUE
4. Will throw a runtime exception due to overflow - Integer.MAX_VALUE is less in
magnitue than Integer.MIN_VALUE.
Question 35.
public class ADirtyOne
{
public static void main(String args[])
{
System.out.println(Math.min(0.0,-0.0));
}
}
Question 36.
Question 37.
Math.round(Float.MAX_VALUE);
1. Returns Integer.MAX_VALUE.
Page 89 of 114
2. Returns a closest integer to Float.MAX_VALUE;
3. Causes a compilation error.
4. Causes a runtime Exception
Question 38.
Read the code below carefully
import java.awt.*;
public class TestFrame extends Frame
{
Button bNorth = new Button("North");
Button bSouth = new Button("South");
Button bEast = new Button("East");
Button bWest = new Button("West");
Button bCenter = new Button("Center");
public TestFrame()
{
setLayout(new BorderLayout());
add(bSouth,BorderLayout.SOUTH);
add(bWest,BorderLayout.WEST);
add(bEast,BorderLayout.EAST);
add(bNorth,BorderLayout.NORTH);
add(bCenter);
setLayout(new FlowLayout());
validate();
pack();
setVisible(true);
}
What will be the effect trying compile and run the above class?
Page 90 of 114
Question 39.
import java.awt.*;
public class TestFrame extends Frame
{
Button bNorth = new Button("North");
Button bSouth = new Button("South");
Button bEast = new Button("East");
Button bWest = new Button("West");
Button bCenter = new Button("Center");
public TestFrame()
{
setLayout(new FlowLayout());
add(bNorth);
add(bSouth);
add(bWest);
add(bEast);
add(bCenter);
setLayout(new BorderLayout());
validate();
setSize(300,300);
setVisible(true);
}
1. Will cause a compilation error - a Layout cannot be set after a component has been
added with a preset Layout Manager.
2. Will cause a Runtime Exception - a Layout cannot be set after a component has
been added with a preset Layout Manager.
3. Will compile cleanly and throw no runtime Exception. Only the button with label
"Center" is visible and occupies the whole screen.
4. Will compile cleanly an throw no runtime Exception. All the buttons are arranged in a
single line. Any other component added in future will follow the rules of the
BorderLayout Manager.
5. Will compile and run cleanly, but no component is visible.
6. Will compile cleanly and throw no runtime Exception. The buttons are arranged as
listed below
Button Label Position
Center Center
North North
Page 91 of 114
South South
East East
West West
Question 40.
A frame uses BorderLayout Management and has components added to all the regions.
One resizing the Frame Some space becomes available. The space is alloted to the
regions, in which Order of preference?
import java.awt.*;
public class TestFrame extends Frame
{
Button firstOne = new Button("One");
Button secondOne = new Button("Two");
public TestFrame()
{
add(firstOne,BorderLayout.NORTH);
add(secondOne,BorderLayout.NORTH);
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
TestFrame tf = new TestFrame();
}
}
Page 92 of 114
Question 42.
import java.awt.*;
public class TestFrame extends Frame
{
public TestFrame()
{
Button one = new Button("One");
Button two = new Button("Two");
Button three = new Button("Three");
setLayout(new FlowLayout());
add(one);
add(two);
add(three);
two.setVisible(false);
setSize(1000,1000);
setVisible(true);
validate();
}
public static void main(String args[])
{
TestFrame tf = new TestFrame();
}
}
1. If the above code runs, the buttons - one and three are laid out in a single row from
left to right with a gap in between .
2. If the above code runs, the buttons - one and three are laid out in a single row from
left to right with no gap in between.
3. Code does not compile - a component can not be hidden after being added to a
container.
4. Code gets compiled successfully but throws runtime Exception - a component can
not be hidden after being added to a container.
Question 43.
Read the code below carefully.
import java.awt.*;
public class TestFrame extends Frame
{
public TestFrame()
{
setLayout(new GridLayout(2,1));
for(int i = 1 ; i <= 4 ;++i)
{
add(new Button(Integer.toString(i)));
}
pack();
setVisible(true);
}
Page 93 of 114
public static void main(String args[])
{
TestFrame tf = new TestFrame();
}
}
1. The code above will not compile - The number of components added is more than
the magnitude of row * columns of the Grid Layout Manager.
2. The code will throw a runtime Exception - The number of components added is
more than the magnitude of row * columns of the Grid Layout Manager.
3. The code will compile cleanly and when run Four buttons are visible in 2 rows and 2
columns.
4. The code will compile and when run, Four buttons are seen in a single Column.
Question 44.
Read the code below carefully.
import java.awt.*;
public class TestFrame extends Frame
{
public TestFrame()
{
setLayout(new GridLayout());
for(int i = 1 ; i <= 4 ;++i)
{
add(new Button(Integer.toString(i)));
}
pack();
setVisible(true);
}
Question 45.
Which of the following statements are true about setLayout() method in
java.awt.ScrollPane
Page 94 of 114
1. Does nothing.
2. Throws UnsupportedMethodException when called.
3. It is not overriden in java.awt.ScrollPane.
4. Sets the layout to the specified Layout Manager.
Question 46.
An Outer class which has all its constructors declared as private
1. Cannot be instantiated by any other Outer class.
2. Cannot be extended.
3. Both i and ii.
4. has to be declared final.
Question 47.
The GridBagConstraints Class
1. Is serializable.
2. Is cloneable.
3. belongs to the java.awt package.
4. extends Object.
Question 48.
Read the following code carefully
import java.awt.*;
public class TestFrame extends Frame
{
public TestFrame()
{
CheckboxGroup chg = null;
Checkbox ch = new Checkbox("Test",true,chg);
setLayout(new FlowLayout());
add(ch);
pack();
setVisible(true);
}
public static void main(String args[])
{
TestFrame tf = new TestFrame();
}
}
Page 95 of 114
1. will cause a compilation error as the checkbox group is null in the constructor.
2. will compile successfully but throws a runtime exception because the checkbox
group is null in the constructor of the check box
3. will compile and run successfully. The checkbox appears as a single radio button
which is always true.
4. will compile and run successfully. The checkbox bears its original appearence and
does not appear as a radio button.
Question 49.
Read the following code carefully
import java.awt.*;
public class TestFrame extends Frame
{
public TestFrame()
{
CheckboxGroup chg = new CheckboxGroup();
Checkbox ch = new Checkbox("Test",true,chg);
setLayout(new FlowLayout());
add(ch);
pack();
setVisible(true);
}
public static void main(String args[])
{
TestFrame tf = new TestFrame();
}
}
Question 50.
Which of the following methods of the java.io.File class throws a checked Exceptions -
1. getCanonicalPath()
2. getCanonicalFile()
3. getAbsolutePath()
Page 96 of 114
4. getAbsoluteFile()
5. createTempFile()
6. createNewFile()
7. mkdir()
8. mkdirs()
9. toURL()
Question 51.
Read the code below carefully.
if( "String".endsWith(""))
Sytem.out.println("True");
else
System.out.println("False");
The code produces
1. True
2. False
Question 52.
Read the code below carefully.
if( "String".startsWith(""))
Sytem.out.println("True");
else
System.out.println("False");
The code produces
1. True
2. False
Question 53.
Read the code below carefully.
Page 97 of 114
Is the line marked "lots of code" ever reached?
Question 54.
Read the code below carefully.
nt1.run();
nt2.run();
nt3.run();
}
}
1. The code does not compile - "nt2.run() is never reached"
2. The code compiles and runs 3 non ending non demon threads.
3. The code compiles but runs only 1 non ending, non demon thread.
Question 55.
When does the JVM exit?
Question 56.
Read the following code, which is a part of a synchronized method of a monitor.
Page 98 of 114
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
//do some crap here.
}
//more and more code here
}
1. The code causes compilation error - sleep cannot be called inside synchronized
methods.
2. The code causes compilation error - sleep is not a static method of java.lang.Thread
3. The Thread sleeps for at least 500 milliseconds in this method if not interrupted.
4. When the thread "goes to sleep" it releases the lock on the object.
5. The "sleeping" Threads always have the lock on the Object.
Question 57.
The no-argument constructor provided by the compiler when no constructor is explicitly
provided in the code
1. is always public
2. is always "friendly"
3. always defaults to the access modifier provided for the class.
4. depends on the compilation options of javac
Question 58.
Which of the following is the direct base class of java.awt.AWTEvent.
1. java.lang.Object.
2. java.util.EventObect
Question 59.
Interface methods can be declared with the following modifiers
1. public
2. none (i.e., no access modifier).
3. private.
4. static
Page 99 of 114
5. native
6. synchronized.
Question 60.
Which of the following are true about the class defined inside an interface
1. it is not possible in the java Laungage.
2. The class is always public.
3. The class is always static.
4. the class methods cannot call the methods declared in the interface.
5. the class methods can call only the static methods declared in the interface.
Question 61.
what does the following expression return?
(0.0 == -0.0)
1. true
2. false
Question 62.
What does the following expression print on the screen?
System.out.println(Math.min(Float.NaN, Float.POSITIVE_INFINITY));
1. NaN
2. Infinity
3. The expression throws a runtime exception - NaN is an illegal argument.
Question 63.
What does the following expression return
Math.max(Float.POSITIVE_INFINITY,Double.POSITIVE_INFINITY);
1. Float.POSITIVE_INFINITY
2. Double.POSITIVE_INFINITY
3. runtime Exception
System.out.println(s2);
}
}
Question 65.
Read the code below carefully.
public class AQueryClass
{
public static synchronized void method1()
{
//lots and lots of code here.
}
public sychronized void method2()
{
//lots of code here too.
}
}
Assuming that all the code inside the method is legal and cannot be a cause for compilation
error -
Question 66.
Class fields with the following modifiers will not be serialized
1. private
2. static
3. transient
4. protected
Question 67.
Assume that Cat is a class and String[] args is the argument passed to the public static void
method of the class. The class is executed with the following command line
main(String args[])
string
c:\somedirectory> java Cat
1. The above expression will cause a '0' appear on the command line.
2. Will throw a NullPointerException.
3. Will a blank line to appear.
Question 68.
A demon Thread group
1. has only demon threads.
2. can have non demon threads.
3. does not exist after all non demon threads in the group have finished executing.
4. does not exist after all the threads in the group have finished executing.
Question 69.
1. True
2. False
Question 70.
Read the code below carefully.
import java.io.*;
public class OutOut
{
public static void main(String args[]) throws IOException
{
PrintStream pr = new PrintStream(new FileOutputStream("outfile"));
System.out = pr;
}
Attempting to compile and run the code will cause
1. Compiler error - abstract classes cannot have constructors.
2. Compiler error - the method AbstractClass does not have a valid return type.
3. Compiler error - the class cannot be declared as abstract as it does not have any
unimplemented methods.
4. No compiler error - the class is practically not an abstract class and can be
instantiated.
Question 72.
Read the following piece of code carefully.
import java.io.IOException;
It is required that none of the constructors of Question72E should throw any checked
exception.
1. It can be achived by placing the call to the superclass with a super keyword , which
is placed in a try block with a catch block to handle the IOException thrown by the
super class.
2. It can be achived by avoiding explicit calls to the base class constructor.
3. It cannot be done in the Java Laungage with the above definition of the base class.
Question 73.
Read the following piece of code carefully. (This is an extention to question 72.)
public abstact class Question73 extends Question72
{
public abstract void method();
}
class Base
{
Base()
{
System.out.println("Message 1 : In the base class constructor");
}
}
abstract class Derived1 extends Base
{
Derived1()
{
System.out.println("Message 2 : In the abstract class Derived1\'s constructor");
}
}
1. will cause a compiler error. The non-abstract classes cannot be extended to the
abstract classes.
2. will cause a compiler error. The abstract classes cannot have constructors defined.
3. will not cause any compiler error. The lines "Message 1..." and "Message 3 ... " are
printed on the screen.
4. will not cause any compiler error. The lines "Message 1..." and "Message 2...." and
Message 3...." are printed on the screen.
Question 75.
Read the following piece of code carefully.
public class A
{
A()
{
}
}
1. The class A can be referenced outside the package in which it is defined.
Question 77.
If the finalize() method of an object is re-references an object so that it becomes in-
eligible for garbage collection
Question 78.
If a Runtime Exception is thrown in the finalize method -
Question 79.
The factory class java.util.Collections
1. is public
2. implements the java.util.Collection interface.
Question 80.
import java.io.*;
public class TransientWriter implements Externalizable
{
class K
{
public static void main(String args[]) throws IOException, ClassNotFoundException
{
TransientWriter tw = new TransientWriter();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tw.out"));
out.writeObject(tw);
1. will cause a compiler error due to the attempt to write a transient object.
2. will cause a runtime exception when an attempt is made to write a transient object.
3. will not cause any runtime error and the transient object is writen to the file named
"tw.out".
4. will not cause any runtime error and the transient object is not written to the file
named "tw.out". The program prints a blank line on the screen.
The following code is for Questions 81 and 82
//Contents of File AnInterface.java
Question 81.
Read the code below carefully.
public class ATest
{
public static void main(String args[])
{
AnInterface ai = new AnInterfaceImpl();
ai.methodOne();
}
}
Question 82.
Read the code below carefully.
public class ATest
{
public static void main(String args[])
{
AnInterfaceImpl ai = new AnInterfaceImpl();
ai.methodOne();
}
}
1. Will cause a compile time error. (Line 5 : Exception must be caught or thrown by main(String))
2. Will cause a compile time error for Class AnInterfaceImpl. The method methodOne() be declared
with "throws Exception".
3. Will cause no compile time error and print "I will never throw and Exception the screen".
Question 83
//Contents of Constants.java
The Constants.java file is edited and the greetingString is changed to "Hello World!". The file after editing is
shown below.
public class Constants
{
public static final String greetingString="Hello World!";
}
On Compilation of Constants.java and running of the application gives. (Note : The client class SomeClass
is not compiled)
3. The program terminates normally and "Hello" is printed on the system console.
4. The program terminates normally and "Hello World!" is printed on the system console.
Question 84.
Read the code below carefully
import java.util.*;
An attempt to compile and call the someMethod of the above class at runtime will cause
Question 86.
//Contents of File AllFinals.java
import java.util.*;
Question 87.
public class A
{
final StringBuffer sb = new StringBuffer("I am final");
public A()
{
}
Question 88.
public class A
{
StringBuffer sb = new StringBuffer("I am final");
public A()
Question 89.
public class A
{
StringBuffer sb = new StringBuffer("I am final");
public A()
{
}
public StringBuffer getSb()
{
return this.sb;
}
Question 90.
A(int i)
{
System.out.println("No B this time");
}
}
class C
{
public static void main(String[] args)
{
A a = new A(1);
}
}
Question 91.
Read the following code excerpt carefully. //Contents of file A.java public class A
{
A()
{
class B
A(int i)
{
class B
{
{
System.out.println("I am in the arg constructor");
}
}
new B();
}
}
class C
{
public static void main(String[] args)
{
A a = new A(1);
}
}
Which of the following are true
1. A.java cannot be compiled. Duplicate defination of inner class B.
2. A.java compiles without any error. An attempt to run C as an application will cause
runtime linkage error. Duplicate definations of inner class B are found
3. Only one class file corresponding to the inner class B is created in the file system.
4. Two class files corresponding to both inner classes (B) is created in the file system.
5. The classes compile cleanly and on running C as an application causes "I am in the arg
constructor" to be printed on the console