Global variables are globally accessible. Java does not support globally accessible variables due to
following reasons:
The valueOf() function of Integer class is is used to convert string to Number. Here is the
code example:
String numString = "1000";
int id=Integer.valueOf(numString).intValue();
Access specifiers are keywords that determine the type of access to the member of a class. These
keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
• Public : accessible to all classes
• Protected : accessible to the classes within the same package and any subclasses.
• Private : accessible only to the class to which they belong
• Default : accessible to the class to which they belong and to subclasses within the same
package
A static variable is associated with the class as a whole rather than with specific instances of a
class. Each object will share a common copy of the static variables i.e. there is only one copy per
class, no matter how many objects are created from it. Class variables or static variables are
declared with the static keyword in a class. These are declared outside a class and stored in static
memory. Class variables are mostly used for constants. Static variables are always called by the
class name. This variable is created when the program starts and gets destroyed when the
programs stops. The scope of the class variable is same an instance variable. Its initial value is
same as instance variable and gets a default value when its not initialized corresponding to the
data type. Similarly, a static method is a method that belongs to the class rather than any object
of the class and doesn't apply to an object or even require that any objects of the class have been
instantiated.
Static methods are implicitly final, because overriding is done based on the type of the object,
and static methods are attached to a class, not an object. A static method in a superclass can be
shadowed by another static method in a subclass, as long as the original method was not
declared final. However, you can't override a static method with a non-static method. In other
words, you can't change a static method into an instance method in a subclass.
1
6. What is the first argument of the String array in main method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first
element by default is the program name. If we do not provide any arguments on the command
line, then the String array of main method will be empty but not null.
7. How can one prove that the array is not null but empty?
Print array.length. It will print 0. That means it is empty. But if it would have been null then it
would have thrown a NullPointerException on attempting to print array.length.
Yes. While starting the application we mention the class name to be run. The JVM will look for the
main method only in the class whose name you have mentioned. Hence there is not conflict
amongst the multiple classes having main method.
Static variable are loaded when class loader brings the class to the JVM. It is not necessary that
an object has to be created. Static variables will be allocated memory space when they have been
loaded. The code in a static block is loaded/executed only once i.e. when the class is first
initialized. A class can have any number of static blocks. Static block is not member of a class,
they do not have a return statement and they cannot be called directly. Cannot contain this or
super. They are primarily used to initialize static fields.
10. How can I swap two variables without using a third variable?
Add two variables and assign the value into First variable. Subtract the Second value with the
result Value. and assign to Second variable. Subtract the Result of First Variable With Result of
Second Variable and Assign to First Variable. Example:
11. Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this
the OS heap or the heap maintained by the JVM? Why
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to
those objects are on the STACK.
A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.
Class instance associated with the object. It is similar to saying:
synchronized(XYZ.class) {
13. Does importing a package imports the sub packages as well? E.g. Does importing
com.bob.* also import com.bob.code.*?
2
No you will have to import the sub packages explicitly. Importing com.bob.* will import classes in
the package bob only. It will not import any class in any of its sub package’s.
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.
For example: The Java API is grouped into libraries of related classes and interfaces; these
libraries are known as package.
Two methods may not have the same name and argument list but different return types.
A constructor is a member function of a class that is used to create objects of that class, invoked
using the new operator. It has the same name as the class and has no return type. They are only
called once, whereas member functions can be called many times. A method is an ordinary
member function of a class. It has its own name, a return type (which may be void), and is
invoked using the dot operator. Constructor will be automatically invoked when an object is
created whereas method has to be called explicitly.
super.method(); is used to call a super class method from a sub class. To call a constructor of the
super class, we use the super(); statement as the first line of the subclass’s constructor.
17. What is Method Overriding? What restrictions are placed on method overriding?
When a class defines a method using the same name, return type, and argument list as that of a
method in its superclass, the method in the subclass is said to override the method present in the
Superclass. When the method is invoked for an object of the
class, it is the new definition of the method that is called, and not the method definition from
superclass.
Restrictions placed on method overriding
• Overridden methods must have the same name, argument list, and return type.
• The overriding method may not limit the access of the method it overrides. Methods may be
overridden to be more public, not more private.
• The overriding method may not throw any exceptions that may not be thrown by the overridden
method.
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. The Class class is used to
obtain information about an object's design. A Class is only a definition or prototype of real life
object. Whereas as object is an instance or living representation of real life object. Every object
belongs to a class and every class contains one or more related objects.
This design pattern is used by an application to ensure that at any time there is only one instance
of a class created. You can achieve this by having the private constructor in the class and having
a getter method which returns an object of the class and creates one for the first time if its null.
3
20. What is difference between overloading and overriding?
Method overloading: When 2 or more methods in a class have the same method names with
different arguments, it is said to be method overloading. Overloading does not block inheritance
from the superclass. Overloaded methods must have different method signatures
Method overriding : When a method in a class has the same method name with same arguments
as that of the superclass,
it is said to be method overriding. Overriding blocks inheritance from the superclass. Overridden
methods must have same signature.
A Bean is a reusable and self-contained software component. Beans created using java take
advantage of all the security and platform independent features of java. Bean can be plugged into
any software application. Bean is a simple class which has set and gets methods. It could be used
within a JSP using JSP tags to use them.
An Object May not have a class definition. eg int a[] where a is an array.
my is an instance.
25. What are the other ways to create an object other than creating as new object?
1. new operator
3. newInstance
4. object.clone
4
26. What is the difference between instance, object, reference and a class?
Class: A class is a user defined data type with set of data members & member functions
Instance: This represents the values of data members of a class at a particular time
Garbage collection is one of the most important features of Java. The purpose of garbage
collection is to identify and discard objects that are no longer needed by a program so that their
resources can be reclaimed and reused. A Java object is subject to garbage collection when it
becomes unreachable to the program in which it is used. Garbage collection is also called
automatic memory management as JVM automatically removes the unused variables/objects
(value is null) from the memory. Every class inherits finalize() method from java.lang.Object, the
finalize() method is called by garbage collector when it determines no more references to the
object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use.
In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but
there is no guarantee when all the objects will garbage collected. Garbage collection is an
automatic process and can't be forced. There is no guarantee that Garbage collection will start
immediately upon request of System.gc(). Garbage Collector uses Daemon thread.
28. How many methods in the Serializable interface? Which methods of Serializable
interface should I implement?
There is no method in the Serializable interface. It’s an empty interface which does not contain
any methods. The Serializable interface acts as a marker, telling the object serialization tools that
the class is serializable. So we do not implement any methods.
The serialization is a kind of mechanism that makes a class or a bean persistent by having its
properties or fields and state information saved and restored to and from storage. That is, it is a
mechanism with which you can save the state of an object by converting it to a byte stream.
A transient variable is a variable that may not be serialized i.e. the value of the variable can’t be
written to the stream in a Serializable class. If you don't want some field to be serialized, you can
mark that field transient or static. In such a case when the class is retrieved from the
ObjectStream the value of the variable is null.
Volatile modifier applies to variables only and it tells the compiler that the variable modified by
volatile can be changed unexpectedly by other parts of the program.
31. Difference between HashMap and HashTable? Can we make hashmap synchronized?
1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and
permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow
nulls).
5
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
A Set stores elements in an unordered way and does not contain duplicate elements, whereas a
list stores elements in an ordered way but may contain duplicate elements.
The Collections API is a set of classes and interfaces that support operations on collections of
objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
35. Which implementation of the List interface provides for the fastest insertion of a
new element into the middle of the list?
a. Vector
b. ArrayList
c. LinkedList
d. None of the above
ArrayList and Vector both use an array to store the elements of the list. When an element is
inserted into the middle of the list the elements that follow the insertion point must be shifted to
make room for the new element. The LinkedList is implemented using a doubly linked list; an
insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList
allows for fast insertions and deletions.
36. What are differences between Enumeration, ArrayList, Hashtable and Collections
and Collection?
ArrayList: It is re-sizable array implementation. Belongs to 'List' group in collection. It permits all
elements, including null. It is not thread -safe.Hashtable: It maps key to value. You can use non-
null value for key or value. It is part of group Map in collection.
6
The throw keyword denotes a statement that causes an exception to be initiated. It takes the
Exception object to be thrown as an argument. The exception will be caught by an enclosing try-
catch block or propagated further up the calling hierarchy. The throws keyword is a modifier of a
method that denotes that an exception may be thrown by the method. An exception can be
rethrown.
Throwable
40. What is the difference between the paint() and repaint() methods?
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.
Yes. Every thread maintains its own separate stack, called Runtime Stack but they share the
same memory. Elements of the stack are the method invocations,
called activation records or stack frame. The activation record contains pertinent information
about a method like local variables.
You have two ways to do so. First, making your class "extends" Thread class. The other way is
making your class implement "Runnable" interface. The latter is more advantageous, cause when
you are going for multiple inheritance, then only interface can help. . If you are already inheriting
a different class, then you have to go for Runnable Interface. Otherwise you can extend Thread
class. Also, if you are implementing interface, it means you have to implement all methods in the
interface. Both Thread class and Runnable interface are provided for convenience and use them
as per the requirement. But if you are not extending any class, better extend Thread class as it
will save few lines of coding. Otherwise performance wise, there is no distinguishable difference.
A thread is in the ready state after it has been created and started.
When you expect that your shared code will be accessed by different threads and these threads
may change a particular data causing data corruption, then they are placed in a synchronized
construct or a synchronized method.
45. What are Wrapper Classes? Describe the wrapper classes in Java.
Wrapper classes are classes that allow primitive types to be accessed as objects. Wrapper class is
wrapper around a primitive data type.
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 and all
methods are implicitly abstract. An interface has all public members and no implementation. An
abstract class is a class which may have the usual flavors of class members (private, protected,
7
etc.), but has some abstract methods.
With respect to multithreading, synchronization is the capability to control the access of multiple
threads to shared resources. Without synchronization, it is possible for one thread to modify a
shared variable while another thread is in the process of using or updating same shared variable.
This usually leads to significant errors.
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is
abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain
static data. Any class with an abstract method is automatically abstract itself, and must be
declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being
instantiated.
49. Does Java provide any construct to find out the size of an object?
No there is not sizeof operator in Java. So there is not direct way to determine the size of an
object directly in Java.
It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes
store objects and not primitive data types. And also the wrapper classes provide many utility
methods also. Because of these reasons we need wrapper classes. And since we create instances
of these classes we can store them in any of the collection classes and pass them around as a
collection. Also we can pass them around as method parameters where a method expects an
object.
51. Is it necessary that each try block must be followed by a catch block?
It is not necessary that each try block must be followed by a catch block. It should be followed by
either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be
declared in the throws clause of the method.
8
Step 4 : Exceute the query :
stmt.exceuteUpdate();
Only public and abstract modifiers are allowed for methods in interfaces.
Static variables and methods are instantiated only once per class. In other words they are class
variables, not instance variables. If you change the value of a static variable in a particular
object, the value of that variable changes for all instances of that class.
Static methods can be referenced with the name of the class rather than the name of a particular
object of the class (though that works too). That's how library methods like System.out.println()
work out is a static field in the java.lang.System class.
9
The TreeSet Class implements java.util.Set interface provides an ordered set, eliminates duplicate
entries and uses tree for storage.
The LinkedList Class implements java.util.List interface and uses linked list for storage.A linked
list allow elements to be added, removed from the collection at any location in the container by
ordering the elements.With this implementation you can only access the elements in sequentially.
An abstract class can have concrete method, which is not allowed in an interface. Abstract class
can have private or protected methods and variables and only public methods and variables are
allowed in interface. We can implement more than one interface , but we can extend only one
abstract class. Interfaces provides loose coupling where as abstract class provides tight coupling.
Constructors must have the same name of the class and can not have a return type. They are
called only once, while regular methods can be called whenever required. We cannot explicitly
call a constructor.
68. What must be the order of catch blocks when catching more than one exception? A
The sub classes must come first. Otherwise it will give a compile time error.
69. What is the difference between static and non static inner class ? A
A non-static inner class can have an object instances that are associated with instances of the
class's outer class. A static inner class can not have any object instances.
Dictionary is a parent class for any class that maps keys to values. In a dictionary every key is
associated with at most one value.
10
72. Why Java is not fully objective oriented ? A
An interface that not having single method. Eg: Serializable, Cloneable, SingleThreadModel etc. It
is used to just mark java classes that support certain capability.
We cannot override static methods. We cannot access any object variables inside static method.
Also this reference also not available in static methods.
JVM stands for Java Virtual Machine. It is the run time for java programs. All are java programs
are running inside this JVM only. It converts java byte code to OS specific commands. In addition
to governing the execution of an application's byte codes, the virtual machine handles related
tasks such as managing the system's memory, providing security against malicious code, and
managing multiple threads of program execution.
77. What is anonymous class ? A An anonymous class is a type of inner class that don't have any
name.
78. Can we compile a java program without main? A
Yes, we can. In order to compile a java program, we don't require any main method. But to
execute a java program we must have a main in it (unless it is an applet or servlet). Because
main functions is the starting point of java program.
Overridden methods must have the same name, argument list, and return type (i.e., they must
have the exact signature of the method we are going to override, including return type.) The
overriding method cannot be less visible than the method it overrides( i.e., a public method
cannot be override to private). The overriding method may not throw any exceptions that may
not be thrown by the overridden method.
80. What is coupling? A Coupling is the dependency between different components of a system
81. What is the difference between creating a thread by extending Thread class and by
implementing Runnable interface? Which one should prefer?
When creating a thread by extending the Thread class, it is not mandatory to override the run
method (If we are not overriding the run method , it is useless), because Thread class have
already given a default implementation for run method. But if we are implementing Runnable , it
is mandatory to override the run method. The preferred way to create a thread is by
implementing Runnable interface, because it give loose coupling.
11
82. What is a JVM heap? The heap is the runtime data area from which memory for all class
instances and arrays is allocated. The heap may be of a fixed size or may be expanded. The heap
is created on virtual machine start-up.
The diamond problem is an ambiguity that can occur when a class multiply inherits from two
classes that both descend from a common super class
throw is used to throw an exception manually, where as throws is used in the case of checked
exceptions, to tell the compiler that we haven't handled the exception, so that the exception will
be handled by the calling function.
Variables declared within a method are local variables. Variables declared within the class are
member variables. Variables declared within the class with static modifier are class variables
Assert keyword validates certain expressions. It replaces the if block effectively and throws an
AssertionError on failure. The assert keyword should be used only for critical arguments (means
without that the method does nothing).
Holding the reference of the other class within some other class is known as composition.
12