java interview questions

127
Java Interview Questions Question: What is the difference between an Interface and an Abstract class? Question: What is the purpose of garbage collection in Java, and when is it used? Question: Describe synchronization in respect to multithreading. Question: Explain different way of using thread? Question: What are pass by reference and passby value? Question: What is HashMap and Map? Question: Difference between HashMap and HashTable? Question: Difference between Vector and ArrayList? Question: Difference between Swing and Awt? Question: What is the difference between a constructor and a method? Question: What is an Iterator? Question: 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. Question: What is an abstract class? Question: What is static in java? Question: What is final? Q: What is the difference between an Interface and an Abstract class? A: 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, etc.), but has some abstract methods. . TOP Q: What is the purpose of garbage collection in Java, and when is it used? A: 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. TOP

Upload: arunsmile

Post on 21-Apr-2017

235 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Java Interview Questions

Java Interview Questions

Question: What is the difference between an Interface and an Abstract class?   Question:What is the purpose of garbage collection in Java, and when is it used?  Question:  Describe synchronization in respect to multithreading.Question:  Explain different way of using thread?  Question:  What are pass by reference and passby value? Question:  What is HashMap and Map?Question:  Difference between HashMap and HashTable?Question: Difference between Vector and ArrayList?Question:  Difference between Swing and Awt?Question:  What is the difference between a constructor and a method? Question:  What is an Iterator?Question:  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.

Question: What is an abstract class?Question: What is static in java? Question: What is final?

Q:What is the difference between an Interface and an Abstract class? A: 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, etc.), but has some abstract methods..

  TOP

Q:What is the purpose of garbage collection in Java, and when is it used?A: 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.

  TOP

Q:Describe synchronization in respect to multithreading.A: With respect to multithreading, synchronization is the capability to control the access of

multiple threads to shared resources. Without synchonization, 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. 

  TOP

Q:Explain different way of using thread? A: The thread could be implemented by using runnable interface or by inheriting from the

Thread class. The former is more advantageous, 'cause when you are going for multiple

Page 2: Java Interview Questions

inheritance..the only interface can help.  TOP

Q:What are pass by reference and passby value? A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value

means passing a copy of the value to be passed.   TOP

Q:What is HashMap and Map?A: Map is Interface and Hashmap is class that implements that.  TOP

Q:Difference between HashMap and HashTable?A: 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 doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

  TOP

Q:Difference between Vector and ArrayList?A: Vector is synchronized whereas arraylist is not.  TOP

Q:Difference between Swing and Awt?A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing

works faster than AWT.  TOP

Q:What is the difference between a constructor and a method? A: A constructor is a member function of a class that is used to create objects of that class.

It has the same name as the class itself, has no return type, and is invoked using the new operator.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.

  TOP

Q:What is an Iterator?A: Some of the collection classes provide traversal of their contents via a java.util.Iterator

interface. This interface allows you to walk through 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

Page 3: Java Interview Questions

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 an abstract class?A: 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.

  TOP

Q:What is static in java?A: Static means one per class, not one for each object no matter how many instance of a

class might exist. This means that you can use them without creating an instance of a class.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 nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

  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).

Java Interview Questions

Question: What if the main method is declared as private? Question: What if the static modifier is removed from the signature of the main method? Question: What if I write static public void instead of public static void?Question: What if I do not provide the String array as the argument to the method?  Question: What is the first argument of the String array in main method? Question: If I do not provide any arguments on the command line, then the String array of

Main method will be empty or null?Question: How can one prove that the array is not null but empty using one line of code?Question: What environment variables do I need to set on my machine in order to be able

to run Java programs?Question: Can an application have multiple classes having main method?Question: Can I have multiple main methods in the same class? Question: Do I need to import java.lang package any time? Why ?Question: Can I import same package/class twice? Will the JVM load the package twice at

runtime?

Page 4: Java Interview Questions

Question: What are Checked and UnChecked Exception?Question: What is Overriding? Question: What are different types of inner classes?

Q:What if the main method is declared as private?A: The program compiles properly but at runtime it will give "Main method not public."

message.  [ Received from Sandesh Sadhale] TOP

Q:What if the static modifier is removed from the signature of the main method?A: Program compiles. But at runtime throws an error "NoSuchMethodError".   [ Received from Sandesh Sadhale] TOP

Q:What if I write static public void instead of public static void?A: Program compiles and runs properly.   [ Received from Sandesh Sadhale] TOP

Q:What if I do not provide the String array as the argument to the method?A: Program compiles but throws a runtime error "NoSuchMethodError".   [ Received from Sandesh Sadhale] TOP

Q:What is the first argument of the String array in main method?A: 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.  [ Received from Sandesh Sadhale] TOP

Q: If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?

A: It is empty. But not null.  [ Received from Sandesh Sadhale] TOP

Q:How can one prove that the array is not null but empty using one line of code?A: Print args.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 args.length.  [ Received from Sandesh Sadhale] TOP

Q:What environment variables do I need to set on my machine in order to be able to run Java programs?

A: CLASSPATH and PATH are the two variables.  [ Received from Sandesh Sadhale] TOP

Q:Can an application have multiple classes having main method?A: Yes it is possible. 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.

  [ Received from Sandesh Sadhale] TOP

Q:Can I have multiple main methods in the same class?A: No the program fails to compile. The compiler says that the main method is already

defined in the class.  [ Received from Sandesh Sadhale] TOP

Page 5: Java Interview Questions

Q:Do I need to import java.lang package any time? Why ?A: No. It is by default loaded internally by the JVM.  [ Received from Sandesh Sadhale] TOP

Q:Can I import same package/class twice? Will the JVM load the package twice at runtime?

A: One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.

  [ Received from Sandesh Sadhale] TOP

Q:What are Checked and UnChecked Exception?A: A checked exception is some subclass of Exception (or Exception itself), excluding class

RuntimeException and its subclasses.Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch theexception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

  TOP

Q:What is Overriding?A: When a class defines a method using the same name, return type, and arguments as a

method in its superclass, the method in the class overrides the method 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. Methods may be overridden to be more public, not more private.

  TOP

Q:What are different types of inner classes?

A: Nested top-level classes, Member classes, Local classes, Anonymous classesNested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful

Page 6: Java Interview Questions

beyond the declaration block, it would need to implement amore publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

 

  Java Interview Questions

Question: Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?

Question: Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*? 

Question: What is the difference between declaring a variable and defining a variable?Question: What is the default value of an object reference declared as an instance variable? Question: Can a top level class be private or protected? Question: What type of parameter passing does Java support?Question: Primitive data types are passed by reference or pass by value?Question: Objects are passed by value or by reference?Question: What is serialization?Question: How do I serialize an object to a file?Question: Which methods of Serializable interface should I implement?Question: How can I customize the seralization process? i.e. how can one have a control

over the serialization process?Question: What is the common usage of serialization?Question: What is Externalizable interface?Question: When you serialize an object, what happens to the object references included in

the object?Question: What one should take care of while serializing the object?Question: What happens to the static fields of a class during serialization?   

Q:Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?

A: Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbolsymbol : class ABCDlocation: package ioimport java.io.ABCD;

  [ Received from Sandesh Sadhale] TOP

Q:Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?

A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.

  [ Received from Sandesh Sadhale] TOP

Q:What is the difference between declaring a variable and defining a variable?

Page 7: Java Interview Questions

A: In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization.e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.

  [ Received from Sandesh Sadhale] TOP

Q:What is the default value of an object reference declared as an instance variable?

A: null unless we define it explicitly.  [ Received from Sandesh Sadhale] TOP

Q:Can a top level class be private or protected?A: No. A top level class can not be private or protected. It can have either "public" or no

modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.

  [ Received from Sandesh Sadhale] TOP

Q:What type of parameter passing does Java support?A: In Java the arguments are always passed by value .  [ Update from Eki and Jyothish Venu] TOP

Q:Primitive data types are passed by reference or pass by value?A: Primitive data types are passed by value.  [ Received from Sandesh Sadhale] TOP

Q:Objects are passed by value or by reference?A: Java only supports pass by value. With objects, the object reference itself is passed by

value and so both the original reference and parameter copy both refer to the same object .

  [ Update from Eki and Jyothish Venu] TOP

Q:What is serialization?A: Serialization is a mechanism by which you can save the state of an object by converting it

to a byte stream.  [ Received from Sandesh Sadhale] TOP

Q:How do I serialize an object to a file?A: The class whose instances are to be serialized should implement an interface Serializable.

Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.

  [ Received from Sandesh Sadhale] TOP

Q:Which methods of Serializable interface should I implement?A: The serializable interface is an empty interface, it does not contain any methods. So we

do not implement any methods.  [ Received from Sandesh Sadhale] TOP

Q:How can I customize the seralization process? i.e. how can one have a control over the serialization process?

A: Yes it is possible to have control over serialization process. The class should implement

Page 8: Java Interview Questions

Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.

  [ Received from Sandesh Sadhale] TOP

Q:What is the common usage of serialization?A: Whenever an object is to be sent over the network, objects need to be serialized.

Moreover if the state of an object is to be saved, objects need to be serilazed.  [ Received from Sandesh Sadhale] TOP

Q:What is Externalizable interface?A: Externalizable is an interface which contains two methods readExternal and

writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.

  [ Received from Sandesh Sadhale] TOP

Q:When you serialize an object, what happens to the object references included in the object?

A: The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.

  [ Received from Sandesh Sadhale] TOP

Q:What one should take care of while serializing the object?A: One should make sure that all the included objects are also serializable. If any of the

objects is not serializable then it throws a NotSerializableException.  [ Received from Sandesh Sadhale] TOP

Q:What happens to the static fields of a class during serialization? A: There are three exceptions in which serialization doesnot necessarily read and write to

the stream. These are1. Serialization ignores static fields, because they are not part of ay particular state state.2. Base class fields are only hendled if the base class itself is serializable.3. Transient fields.

Java Interview Questions

Question:Does Java provide any construct to find out the size of an object?Question:Give a simplest way to find out the time a method takes for execution without

using any profiling tool? Question:What are wrapper classes?Question:Why do we need wrapper classes?  Question:What are checked exceptions? Question:What are runtime exceptions?Question:What is the difference between error and an exception??Question:How to create custom exceptions?Question:If I want an object of my class to be thrown as an exception object, what should I

do?Question:If my class already extends from some other class what should I do if I want an

Page 9: Java Interview Questions

instance of my class to be thrown as an exception object?Question:How does an exception permeate through the code?Question:What are the different ways to handle exceptions?Question:What is the basic difference between the 2 approaches to exception handling...1>

try catch block and 2> specifying the candidate exceptions in the throws clause?When should you use which approach?

Question:Is it necessary that each try block must be followed by a catch block ? Question:If I write return at the end of the try block, will the finally block still execute ? Question:If I write System.exit (0); at the end of the try block, will the finally block still

execute?   

Q:Does Java provide any construct to find out the size of an object?A: No there is not sizeof operator in Java. So there is not direct way to determine the size of

an object directly in Java.  [ Received from Sandesh Sadhale] TOP

Q:Give a simplest way to find out the time a method takes for execution without using any profiling tool?

A: Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.

To put it in code...

long start = System.currentTimeMillis ();method ();long end = System.currentTimeMillis ();

System.out.println ("Time taken for execution is " + (end - start));

Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing.

  [ Received from Sandesh Sadhale] TOP

Q:What are wrapper classes?A: Java provides specialized classes corresponding to each of the primitive data types. These

are called wrapper classes. They are e.g. Integer, Character, Double etc.  [ Received from Sandesh Sadhale] TOP

Q:Why do we need wrapper classes?A: 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 resons 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.

  [ Received from Sandesh Sadhale] TOP

Q:What are checked exceptions?A: Checked exception are those which the Java compiler forces you to catch. e.g.

Page 10: Java Interview Questions

IOException are checked Exceptions.  [ Received from Sandesh Sadhale] TOP

Q:What are runtime exceptions?A: Runtime exceptions are those exceptions that are thrown at runtime because of either

wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

  [ Received from Sandesh Sadhale] TOP

Q:What is the difference between error and an exception?A: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error.

These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).

  [ Received from Sandesh Sadhale] TOP

Q:How to create custom exceptions?A: Your class should extend class Exception, or some more specific type thereof.  [ Received from Sandesh Sadhale] TOP

Q: If I want an object of my class to be thrown as an exception object, what should I do?

A: The class should extend from Exception class. Or you can extend your class from some more precise exception type also.

  [ Received from Sandesh Sadhale] TOP

Q: If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?

A: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

  [ Received from Sandesh Sadhale] TOP

Q:How does an exception permeate through the code?A: An unhandled exception moves up the method stack in search of a matching When an

exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

  [ Received from Sandesh Sadhale] TOP

Q:What are the different ways to handle exceptions?A: There are two ways to handle exceptions,

1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and 2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.

  [ Received from Sandesh Sadhale] TOP

Page 11: Java Interview Questions

Q:What is the basic difference between the 2 approaches to exception handling.1> try catch block and 2> specifying the candidate exceptions in the throws clause?When should you use which approach?

A: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

  [ Received from Sandesh Sadhale] TOP

Q: Is it necessary that each try block must be followed by a catch block?A: 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.

  [ Received from Sandesh Sadhale] TOP

Q: If I write return at the end of the try block, will the finally block still execute?A: Yes even if you write return as the last statement in the try block and no exception

occurs, the finally block will execute. The finally block will execute and then the control return.

  [ Received from Sandesh Sadhale] TOP

Q: If I write System.exit (0); at the end of the try block, will the finally block still execute?

A: No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.

Java Interview Questions

Question:How are Observer and Observable used?Question:What is synchronization and why is it important? Question:How does Java handle integer overflows and underflows?Question:Does garbage collection guarantee that a program will not run out of

memory?  Question:What is the difference between preemptive scheduling and time slicing? Question:When a thread is created and started, what is its initial state?Question:What is the purpose of finalization?Question:What is the Locale class?Question:What is the difference between a while statement and a do statement?Question:What is the difference between static and non-static variables?Question:How are this() and super() used with constructors?Question:What are synchronized methods and synchronized statements?Question:What is daemon thread and which method is used to create the daemon thread?Question:Can applets communicate with each other?Question:What are the steps in the JDBC connection?Question:How does a try statement determine which catch clause should be used to handle

Page 12: Java Interview Questions

an exception?      

Q:How are Observer and Observable used?A: Objects that subclass the Observable class maintain a list of observers. When an

Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

  [Received from Venkateswara Manam] TOP

Q:What is synchronization and why is it important?A: 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 object while another thread is in the process of using or updating that object's value. This often leads to significant errors.

  [ Received from Venkateswara Manam] TOP

Q:How does Java handle integer overflows and underflows?A: It uses those low order bytes of the result that can fit into the size of the type allowed by

the operation.  [ Received from Venkateswara Manam] TOP

Q:Does garbage collection guarantee that a program will not run out of memory?A: 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.

  [ Received from Venkateswara Manam] TOP

Q:What is the difference between preemptive scheduling and time slicing?A: 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.

  [ Received from Venkateswara Manam] TOP

Q:When a thread is created and started, what is its initial state?A: A thread is in the ready state after it has been created and started.  [ Received from Venkateswara Manam] TOP

Q:What is the purpose of finalization?A: The purpose of finalization is to give an unreachable object the opportunity to perform

any cleanup processing before the object is garbage collected.  [ Received from Venkateswara Manam] TOP

Q:What is the Locale class?A: The Locale class is used to tailor program output to the conventions of a particular

geographic, political, or cultural region.  [ Received from Venkateswara Manam] TOP

Page 13: Java Interview Questions

Q:What is the difference between a while statement and a do statement?A: A while statement checks at the beginning of a loop to see whether the next loop

iteration should occur. 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.

  [ Received from Venkateswara Manam] TOP

Q:What is the difference between static and non-static variables?A: A static variable is associated with the class as a whole rather than with specific instances

of a class. Non-static variables take on unique values with each object instance.  [ Received from Venkateswara Manam] TOP

Q:How are this() and super() used with constructors?A: This() is used to invoke a constructor of the same class. super() is used to invoke a

superclass constructor.  [ Received from Venkateswara Manam] TOP

Q:What are synchronized methods and synchronized statements?A: Synchronized methods are methods that are used to control access to an object. A thread

only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

  [ Received from Venkateswara Manam] TOP

Q:What is daemon thread and which method is used to create the daemon thread?

A: Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.

  [ Received from Shipra Kamra] TOP

Q:Can applets communicate with each other?A: At this point in time applets may communicate with other applets running in the same

virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable.

An applet can also get references to all other applets on the same page using the getApplets() method of java.applet.AppletContext. Once you get the reference to an applet, you can communicate with it by using its public members.

It is conceivable to have applets in different virtual machines that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial.

  [ Received from Krishna Kumar ] TOP

Q:What are the steps in the JDBC connection?A:   While making a JDBC connection we go through the following steps :

Page 14: Java Interview Questions

Step 1 : Register the database driver by using :

Class.forName(\" driver classs for that specific database\" );

Step 2 : Now create a database connection using :

Connection con = DriverManager.getConnection(url,username,password);

Step 3: Now Create a query using :

Statement stmt = Connection.Statement(\"select * from TABLE NAME\");

Step 4 : Exceute the query :

stmt.exceuteUpdate();

  [ Received from Shri Prakash Kunwar] TOP

Q:How does a try statement determine which catch clause should be used to handle an exception?

A: 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 exceptionis executed. The remaining catch clauses are ignored.

Java Interview Questions

Question:Can an unreachable object become reachable again? Question:What method must be implemented by all threads? Question:What are synchronized methods and synchronized statements?Question:What is Externalizable?  Question:What modifiers are allowed for methods in an Interface? Question:What are some alternatives to inheritance?Question:What does it mean that a method or field is "static"? ?Question:What is the difference between preemptive scheduling and time slicing?Question:What is the catch or declare rule for method declarations?       

Q:Can an unreachable object become reachable again?A: An unreachable object may become reachable again. This can happen when the object's

finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

  [Received from P Rajesh] TOP

Q:What method must be implemented by all threads?A: All tasks must implement the run() method, whether they are a subclass of Thread or

implement the Runnable interface.  [ Received from P Rajesh] TOP

Page 15: Java Interview Questions

Q:What are synchronized methods and synchronized statements?A: Synchronized methods are methods that are used to control access to an object. A thread

only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

  [ Received from P Rajesh] TOP

Q:What is Externalizable? A: Externalizable is an Interface that extends Serializable Interface. And sends data into

Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

  [ Received from Venkateswara Manam] TOP

Q:What modifiers are allowed for methods in an Interface?A: Only public and abstract modifiers are allowed for methods in interfaces.   [ Received from P Rajesh] TOP

Q:What are some alternatives to inheritance?A: Delegation is an alternative to inheritance. Delegation means that you include an

instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

  [ Received from P Rajesh] TOP

Q:What does it mean that a method or field is "static"? A: 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.

  [ Received from P Rajesh] TOP

Q:What is the difference between preemptive scheduling and time slicing?A: 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.

  [ Received from P Rajesh] TOP

Q:What is the catch or declare rule for method declarations? A: If a checked exception may be thrown within the body of a method, the method must

either catch the exception or declare it in its throws clause.

Page 16: Java Interview Questions

Java Interview Questions

Question:Is Empty .java file a valid source file? Question:Can a .java file contain more than one java classes? Question:Is String a primitive data type in Java?Question:Is main a keyword in Java?  Question:Is next a keyword in Java? Question:Is delete a keyword in Java?Question:Is exit a keyword in Java?Question:What happens if you dont initialize an instance variable of any of the primitive

types in Java?Question:What will be the initial value of an object reference which is defined as an instance

variable? Question:What are the different scopes for Java variables? Question:What is the default value of the local variables? Question:How many objects are created in the following piece of code?

MyClass c1, c2, c3;c1 = new MyClass ();c3 = new MyClass ();

Question:Can a public class MyClass be defined in a source file named YourClass.java? Question:Can main method be declared final? Question:What will be the output of the following statement?

System.out.println ("1" + 3); Question:What will be the default values of all the elements of an array defined as an

instance variable?       

Q: Is Empty .java file a valid source file?A: Yes, an empty .java file is a perfectly valid source file.  [Received from Sandesh Sadhale] TOP

Q:Can a .java file contain more than one java classes?A: Yes, a .java file contain more than one java classes, provided at the most one of them is a

public class.  [ Received from Sandesh Sadhale] TOP

Q: Is String a primitive data type in Java?A: No String is not a primitive data type in Java, even though it is one of the most

extensively used object. Strings in Java are instances of String class defined in java.lang package.

  [ Received from Sandesh Sadhale] TOP

Q: Is main a keyword in Java? A: No, main is not a keyword in Java.   [ Received from Sandesh Sadhale] TOP

Q: Is next a keyword in Java?A: No, next is not a keyword.   [ Received from Sandesh Sadhale] TOP

Page 17: Java Interview Questions

Q: Is delete a keyword in Java?A: No, delete is not a keyword in Java. Java does not make use of explicit destructors the

way C++ does.  [ Received from Sandesh Sadhale] TOP

Q: Is exit a keyword in Java? A: No. To exit a program explicitly you use exit method in System object.  [ Received from Sandesh Sadhale] TOP

Q:What happens if you dont initialize an instance variable of any of the primitive types in Java?

A: Java by default initializes it to the default value for that primitive type. Thus an int will be initialized to 0, a boolean will be initialized to false.

  [ Received from Sandesh Sadhale] TOP

Q:What will be the initial value of an object reference which is defined as an instance variable?

A: The object references are all initialized to null in Java. However in order to do anything useful with these references, you must set them to a valid object, else you will get NullPointerExceptions everywhere you try to use such default initialized references.

  [ Received from Sandesh Sadhale] TOP

Q:What are the different scopes for Java variables? A: The scope of a Java variable is determined by the context in which the variable is

declared. Thus a java variable can have one of the three scopes at any given point in time.1. Instance : - These are typical object level variables, they are initialized to default values at the time of creation of object, and remain accessible as long as the object accessible.2. Local : - These are the variables that are defined within a method. They remain accessbile only during the course of method excecution. When the method finishes execution, these variables fall out of scope.3. Static: - These are the class level variables. They are initialized when the class is loaded in JVM for the first time and remain there as long as the class remains loaded. They are not tied to any particular object instance.

  [ Received from Sandesh Sadhale] TOP

Q:What is the default value of the local variables? A: The local variables are not initialized to any default value, neither primitives nor object

references. If you try to use these variables without initializing them explicitly, the java compiler will not compile the code. It will complain abt the local varaible not being initilized..

  [ Received from Sandesh Sadhale] TOP

Q:How many objects are created in the following piece of code?MyClass c1, c2, c3;c1 = new MyClass ();c3 = new MyClass ();

A: Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized.

  [ Received from Sandesh Sadhale] TOP

Page 18: Java Interview Questions

Q:Can a public class MyClass be defined in a source file named YourClass.java? A: No the source file name, if it contains a public class, must be the same as the public class

name itself with a .java extension.  [ Received from Sandesh Sadhale] TOP

Q:Can main method be declared final? A: Yes, the main method can be declared final, in addition to being public static.  [ Received fromSandesh Sadhale] TOP

Q:What will be the output of the following statement?System.out.println ("1" + 3);

A: It will print 13.  [ Received from Sandesh Sadhale] TOP

Q:What will be the default values of all the elements of an array defined as an instance variable?

A: If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type. e.g. All the elements of an array of int will be initialized to 0, while that of boolean type will be initialized to false. Whereas if the array is an array of references (of any type), all the elements will be initialized to null.

Question: What is transient variable?Answer: Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

Question: Name the containers which uses Border Layout as their default layout?Answer: Containers which uses Border Layout as their default are: window, Frame and Dialog classes.  

Question: What do you understand by Synchronization?Answer: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.E.g. Synchronizing a function:public synchronized void Method1 () {   // Appropriate method-related code. }E.g. Synchronizing a block of code inside a function:

Page 19: Java Interview Questions

public myFunction (){  synchronized (this) {   // Synchronized code here.   }}  

Question: What is Collection API?Answer: The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.Example of interfaces: Collection, Set, List and Map.  

Question: Is Iterator a Class or Interface? What is its use?Answer: Iterator is an interface which is used to step through the elements of a Collection.  

Question: What is similarities/difference between an Abstract class and Interface?Answer:  Differences are as follows:

Interfaces provide a form of multiple inheritance. A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation. Abstract

classes can have a partial implementation, protected parts, static methods, etc.

A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.

Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. 

Similarities:

Neither Abstract classes or Interface can be instantiated.  

Question: How to define an Abstract class?Answer: A class containing abstract method is called Abstract class. An Abstract class can't be instantiated. Example of Abstract class:abstract class testAbstractClass {   protected String myString;   public String getMyString() {   return myString;   }   public abstract string anyAbstractFunction();

Page 20: Java Interview Questions

Question: How to define an Interface?Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.Emaple of Interface:

public interface sampleInterface {  public void functionOne();

  public long CONSTANT_ONE = 1000; } 

Question: Explain the user defined Exceptions?Answer: User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions. Example:class myCustomException extends Exception {   // The class simply has to exist to be an exception }   

Question: Explain the new Features of JDBC 2.0 Core API?Answer: The JDBC 2.0 API includes the complete JDBC API, which includes both core and Optional Package API, and provides inductrial-strength database computing capabilities. New Features in JDBC 2.0 Core API:

Scrollable result sets- using new methods in the ResultSet interface allows programmatically move the to particular row or to a position relative to its current position

JDBC 2.0 Core API provides the Batch Updates functionality to the java applications.

Java applications can now use the ResultSet.updateXXX methods.

New data types - interfaces mapping the SQL3 data types

Custom  mapping of user-defined types (UTDs)

Miscellaneous features, including performance hints, the use of character streams, full precision for java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp values. 

Page 21: Java Interview Questions

  

Question: Explain garbage collection?Answer: Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. 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. I 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.  

Question: How you can force the garbage collection?Answer: Garbage collection automatic process and can't be forced.   

Question: What is OOPS?Answer: OOP is the common abbreviation for Object-Oriented Programming.   

Question: Describe the principles of OOPS.Answer: There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.   

Question: Explain the Encapsulation principle.Answer: Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.   

Question: Explain the Inheritance principle.Answer: Inheritance is the process by which one object acquires the properties of another object.

 

Question: Explain the Polymorphism principle.Answer: The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".   

Page 22: Java Interview Questions

Question: Explain the different forms of Polymorphism.Answer: From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:

Method overloading Method overriding through inheritance

Method overriding through the Java interface

  

Question: What are Access Specifiers available in Java?Answer: Access specifiers are keywords that determines the type of access to the member of a class. These are:

Public Protected

Private

Defaults

  

Question: Describe the wrapper classes in Java.Answer: Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive Wrapperboolean   java.lang.Boolean

byte   java.lang.Byte

char   java.lang.Character

double   java.lang.Double

float   java.lang.Float

int   java.lang.Integer

long   java.lang.Long

short   java.lang.Short

void   java.lang.Void

Page 23: Java Interview Questions

  

Question: Read the following program:

public class test {public static void main(String [] args) {  int x = 3;  int y = 1;   if (x = y)   System.out.println("Not equal");  else  System.out.println("Equal"); }}

What is the result?   A. The output is ?Equal?   B. The output in ?Not Equal?   C. An error at " if (x = y)" causes compilation to fall.   D. The program executes but no output is show on console.Answer: C

Question: what is the class variables ?Answer: When we create a number of objects of the same class, then each object will share a common copy of variables. That means that 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, but mind it that it should be declared outside outside a class. These variables are stored in static memory. Class variables are mostly used for constants, variable that never change its initial value. Static variables are always called by the class name. This variable is created when the program starts i.e. it is created before the instance is created of class by using new operator and gets destroyed when the programs stops. The scope of the class variable is same a instance variable. The class variable can be defined anywhere at class level with the keyword static. It initial value is same as instance variable. When the class variable is defined as int then it's initial value is by default zero, when declared boolean its default value is false and null for object references. Class variables are associated with the class, rather than with any object. 

Question: What is the difference between the instanceof and getclass, these two are same or not ?Answer: instanceof is a operator, not a function while getClass is a method of java.lang.Object class. Consider a condition where we use if(o.getClass().getName().equals("java.lang.Math")){ }This method only checks if the classname we have passed is equal to java.lang.Math. The class java.lang.Math is loaded by the bootstrap ClassLoader. This class is an abstract class.This class loader is responsible for loading classes. Every Class object contains a reference to the

Page 24: Java Interview Questions

ClassLoader that defines. getClass() method returns the runtime class of an object. It fetches the java instance of the given fully qualified type name. The code we have written is not necessary, because we should not compare getClass.getName(). The reason behind it is that if the two different class loaders load the same class but for the JVM, it will consider both classes as different classes so, we can't compare their names. It can only gives the implementing class but can't compare a interface, but instanceof operator can. The instanceof operator compares an object to a specified type. We can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. We should try to use instanceof operator in place of getClass() method. Remember instanceof opeator and getClass are not same. Try this example, it will help you to better understand the difference between the two. Interface one{}

Class Two implements one {}Class Three implements one {}

public class Test {public static void main(String args[]) {one test1 = new Two();one test2 = new Three();System.out.println(test1 instanceof one); //trueSystem.out.println(test2 instanceof one); //trueSystem.out.println(Test.getClass().equals(test2.getClass())); //false}} 

PAPER : JAVA Sample Question Bank (Solved)

1. Consider the following code , what is the output provided a valid file name is given on the command prompt?

import java.io.*;class Q032{

public static void main(String args[]) throws Exception{FileInputStream fin;int c = 0;try{

fin = new FileInputStream(args[0]);while ((c = fin.read()) != -1){

System.out.print((char)c);}

}catch (Exception e)

Page 25: Java Interview Questions

{System.out.println(e);

}fin.close();

}};

Options :

a. Compile-time error " Variable fin may not have been initialized." b. Run-time exception " java.lang.ArrayIndexOutOfBoundsException: 0"

c. Run's fine displaying the contents of the file .

d. Compile-time error " Undefined variable: args"

 

2. What is the output for the following -

class A{static int i;

A(){ ++i;}

private int get(){return ++i;

}};

class B extends A{

B(){i++;

}

int get(){return ( i + 3);

}};

class Q028 extends B{

public static void main(String ka[]){Q028 obj = new Q028();A ob_a = new A();ob_a = (A)obj;System.out.println(ob_a.get());

}};

Options :

Page 26: Java Interview Questions

a. 2 b. Compile error " No method matching get() found in class Q026."

c. 5

d. NullPointerException thrown at run-time .

 

3. What is the output ?

class Q006{

public static void main(String args[]){boolean flag = false;if ( flag = true){

System.out.println("true");}if ( flag == false){

System.out.println("false");}

}};

Options :

a. true b. false

c. Compile-time error " Q006.java:11: Incompatible type for declaration. Can't convert boolean to java.lang.Boolean. "

d. truefalse

 

4. What is the output ?

class A{

A(){System.out.print("1");

}};

class Q005 extends A{

Q005(){System.out.print("2");

Page 27: Java Interview Questions

}

public static void main(String args[]){Q005 obj = new Q005();System.out.println("3");

}};

Options :

a. 123 b. 23

c. 3

d. 1 , 2 , 3 each on a separate line

 

5. What is the output ?

class Q002{

public static void main(String args[]){int i = -1;System.out.println(-1 >> 17);

}};

Options :

a. Compile error b. Run-time Exception thrown

c. -1

d. Do you expect me to shift the bits

 

6. Predict the output -

class Q008{public static void main(String args[]){

int i = -1;System.out.println((i<0)?-i:i);

}};

Options :

a. 1

Page 28: Java Interview Questions

b. -1

c. Compile error

d. Run-time error

 

7. Will the following compile ? If yes what is the output ?

class Q009{public static void main(String args[]){

System.out.println((Math.abs(Integer.MIN_VALUE)));//FYI Integer.MIN_VALUE = -2147483648

}};

Options :

a. 2147483648 b. Compile Error

c. -2147483648

d. NegativeArraySizeException thrown at runtime

 

8. Will the following code compile ? If yes , what is the output ?

class Q012{

Q012(int i){System.out.println(i);this.i = i;

}

public static void main(String ka[]){Q012 obj = new Q012(10);

}}

Options :

a. 0 b. 10

c. null

d. Compile error " Q012.java:10: No variable i defined in class Q012. "

Page 29: Java Interview Questions

9. What is the output of this code ?

class Q011{int i;Q011(int i){

System.out.println(i);this.i = i;

}

public static void main(String ka[]){Q011 obj = new Q011(10);System.out.println(obj.i);

}}

Options :

a. 1010

b. Compile error " Q012.java:16: Variable i may not have been initialized. "

c. 010

d. 100

10. What is the output for this piece ?

class Test{

static boolean flag;

public static void main(String args[]){if ( flag ){

System.out.println(flag);}

}};

Options :

a. Compiler error , boolean flag : variable flag may not have been initialized b. Compiler error , System.out.println ( flag ) : can't convert boolean to String

c. true

d. false

e. Compiles & runs fine with no output generated

Page 30: Java Interview Questions

 

Answers :

1. a 2. b

3. a

4. a

5. c

6. a

7. c

8. d

9. a

10. e

PAPER : JAVA Sample Question Bank (Solved)

1. What is the output when Test01 class is run ?

class A{

A(){//some initialization

}

void do_something(){System.out.println("I'm in A");

}};

class B extends A{

B(){//some initialization

}

void do_something(){System.out.println("I'm in B");

}};

class Test01{

public static void main(String args[]){

Page 31: Java Interview Questions

A a = new B();a.do_something();

}};

Options :

a. I'm in A b. I'm in B

c. Compiler error , A a = new B ( ) : Explicit cast needed to convert A to B

d. ClassCastException thrown at runtime

 

2. What is the output for the following code ?

class Q014{

public String get(int i){return null;

}

public static void main(String ka[]){System.out.println((new Q014()).get(1));

}};

Options :

a. 0 b. NullPointerException at run-time

c. Compile error

d. null

 

3.What is the output ?

class Q018{static Object obj;static String get(){

return null;}

public static void main(String args[]){System.out.println((Q018.get()) == (Q018.obj));

}

Page 32: Java Interview Questions

};

Options :

a. Compile error b. Run-time error

c. true

d. false

 

4. What is the output ?

class Q015{

public String get(int i){return null;

}

public static void main(String ka[]){Q015 obj = new Q015();Object i = obj.get(10);System.out.println(i.toString());

}};

Options :

a. null b. NullPointerException at run-time

c. Compile error

d. 0

 

5.What is the output ?

class Q013{int i;

Q013(int i){System.out.println(i);

}

public static void main(String ka[]){Q013 obj = new Q013(10);

Page 33: Java Interview Questions

System.out.println(obj.i);}

}

Options :

a. 1010

b. Compile error , System.out.println ( obj.i ) : variable i may not have been initialized

c. 010

d. 100

 

6. What is the output ?

class Test02{

public String fetch(){return null;

}

public static void main(String args[]){Test02 obj = new Test02();String str = obj.fetch();System.out.println((str+"").toString());

}};

Options :

a. null b. Compiler error , can't invoke a method on null

c. NullPointerException thrown at runtime

d. ClassCastException thrown at runtime

 

7. What is the output ?

class Q022{public static void main(String ka[]){

while(false){System.out.println("Great");

Page 34: Java Interview Questions

}}

};

Options :

a. Run's with no output b. Run-time error " Statement not reached."

c. Great

d. Compiler error , System.out.println ( "Great") : statement not reached

 

8. What is the output ?

class A{static int i;

private int get(){return 1;

}};

class B extends A{

private int get(){return 2;

}};

class Q027 extends B{

public static void main(String ka[]){Q027 obj = new Q027();System.out.println(obj.get());

}};

Options :

a. 2 b. Compile error , System.out.println ( obj.get ( ) ) : no method matching get ( ) found in class Q027

c. 1

d. 2

e. NullPointerException thrown at run-time .

Page 35: Java Interview Questions

 

9. What is the output ?

class Q029{public static void main(String args[]){

boolean b[] = new boolean[2];System.out.println(b[1]);

}};

Options :

a. Compile error " Variable b may not have been initialized." b. Run-time error " Variable b may not have been initialized."

c. false

d. true

 

10. Consider the following applet . Is there something wrong with it ? Choose the most appropriate option ( only one ) .

public class App_Test extends Applet{

App_Test(){//some initialization

}

public void paint(Graphics g){g.drawString("Applet started" , 50 , 50);

}};

Options :

a. Nothings wrong with it b. It should override the init ( ) method of it's superclass ( Applet )

c. An applet subclass can't override the default constructor

d. The drawString ( ) method in paint ( ) has wrong number of arguments

e. The constructor of App_Test must be defined as public

 

Answers :

Page 36: Java Interview Questions

1. b 2. d

3. c

4. b

5. d

6. a

7. d

8. b

9. c

10. e

PAPER : JAVA Sample Question Bank (Solved)

 

1. Will the following code compile ? If yes choose the most correct two options .

class Q011{ public static void main(String args[]){ char a = 'a' + 2; System.out.println(a); int i = 2; char c = 'a' + i;//---1 System.out.println(c);//---2 }};

Options :

a. Compile-time error " Explicit cast needed to convert int to char " b. The code can be made to compile by commenting out lines marked as 1 & 2

c. The code can be made to compile by commenting out the line " char a = 'a' + 2; "

d. The output is6767

 

Page 37: Java Interview Questions

2. What is the output ? FYI ( int ) ' A ' = 65 

class Q1{ public static void main(String args[]){ byte b = 65; switch (b) { case 'A': System.out.println("A"); break; case 65: System.out.println("65"); break; default: System.out.println("default"); } }};

Options :

a. A b. 65

c. Compile time error , case 65 : duplicate case label

d. Runtime error "Duplicate case label: 65"

e. default

 

3. Will the output from the following two code snippets be any different ?

Snippet 1 : for ( int i = 0 ; i < 5 ; i++ ) { System.out.println(i); }

Snippet 2 : for ( int i = 0 ; i < 5 ; ++i ) { System.out.println(i); }

Options :

a. yes b. no

Page 38: Java Interview Questions

 

4. What is the output of the following code ? FYI 1 divided by 2 = 0.5

class Q009{ public static void main(String args[]){ float f = 1/2; System.out.println(f); }};

Options :

a. Compile-time error float f = 1 / 2 : explicit cast needed to convert int to float b. 0.0

c. 0.5

d. ClassCastException thrown at run-time

 

5. What is the output for the following code ?

class Torment{

int i = 2;

public static void main(String args[]){ int i = 12; System.out.println(i); }};

Options :

a. Compiler error , System.out.println ( i ) : can't make a static reference to a non static variable i b. Output = 2

c. Output = 12

d. Compiler error , i = 12 : variable i is already defined in this class

 

6. What is the output ?

class FearFactory{ static{ System.out.println("Genesis");

Page 39: Java Interview Questions

}

FearFactory(){ System.out.println("Birth"); }

public static void main(String args[]){ //I'm Lazy }};

Options :

a. Output = Birth b. Output = Genesis

c. No output generated

d. Compiler error , System.out.println ( " Genesis " ) : type expected

 

7. Consider the following class . Which of the marked lines need to be commented out for the class to compile correctly ?

class Evolve{

static int i = 1; static int j = 2; int x = 3; static int y = 6;

public static void main(String args[]){ System.out.println(i + j);//---1 System.out.println(x + i);//---2 System.out.println(i + y);//---3 System.out.println(x + j);//---4 }};

Options :

a. 1 & 2 b. 1 ,2 & 4

c. 3 & 4

d. 2 & 4

e. 1 , 2 & 3

Page 40: Java Interview Questions

 

8. What is the compiler error generated ( if any ) by the following piece of code .

class Jelly{

public static void main(String args[]){ float f = 1./2; System.out.println(f); }};

Options :

a. float f = 1. / 2 : invalid numeric type b. float f = 1. / 2 : explicit cast needed t convert int to float

c. System.out.println ( f ) : can't invoke a method on primitive data types

d. No problem , the code compiles fine .

e. float f = 1. / 2 : explicit cast needed to convert double to float

 

9. Will the following class compile ? If yes what is the output ?

class Envy{ static int i;

Envy(){ ++i; }

public static void main(String args[]){ System.out.println(i); }};

Options :

a. Yes , it compiles but NullPointerException thrown at runtime b. Compiler error , System.out.println ( i ) : variable i may not have been initialized

c. Yes it compiles & output = 0

d. Yes it compiles & the output = 1

e. Compiler error , ++ i : can't make a nonstatic reference to a static variable , i

Page 41: Java Interview Questions

 

10. Choose all the valid declarations for the main method from the list below ( any  three )

a. public void main(String args[]) b. public static int main(String args[]) c. public static void main(String [] ka) d. public static void main(String [] args) e. public static void main(String ka [])

 

 

Answer :

1. a & b 2. c

3. b

4. b

5. c

6. b

7. d

8. e

9. c

10. c , d & e

Java Certification Model Question & Answer - 2

1. What makes a Thread to stop execution

a. An interrupted exception is thrown b. Invoke sleep() method

Page 42: Java Interview Questions

c. Higher priority thread takes over

d. While a thread does a read() using inputstream

2. Which is the correct expression to be used to read line by line and store the result into a String object

a) File f = new File("test.txt");

b. FileInputStream f = new FileInputStream("test.txt"); c. DataInputStream d = new DataInputStream(new FileInputStream("test.txt"));

d. BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));

e. BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt", "8859_1)));

3. Which of the following will not throw a NullPointerException?

String s = null;

a. if ((s!=null) & (s.length() > 0)) b. if ((s!=null) && (s.length() > 0))

c. if ((s==null) | (s.length() == 0))

d. if ((s==null) || (s.length() == 0))

4. Which of the following describes a fully encapsulated class?

a. Methods cannot be private b. Variables cannot be private

c. The state of the object can only be modified through accessor method.

d. All variables are private.

e. All variables and all methods are private

5. Which state decide a var. ’a’ which is suitable for referring to an array of 50 string objects?

a. char a[ ] [ ]; b. String a [ ];

c. String [ ] a;

d. Object a [50];

Page 43: Java Interview Questions

e. String a[50];

6. In the following program, if somecondition() is true, then only line number 3 must throw a custom exception MyException. MyException is not a subclass of runtime exceptions. What are the changes to be made to the given method.

1. Public void method() { 2. If (somecondition()) {

3.

4. }

5.

6. }

a. Add throws new MyException(); in line number 3

b. Add throws new MyException(); in line number 5

c. Add throw new MyException(); in line number 3

d. Modify the method declaration such that an object of type Exception is to be thrown

7. What is the output of the following program

public class Example{

private int i;

public static void main(String args[]) {

method() ;

}

public static void method() {

int j;

j= i;

System.out.println("The value of i is " +i);

}

Page 44: Java Interview Questions

}

a. The program prints The value of i is 0; b. The program gives a compilation error. By changing the private int i to public int i

the problem gets resolved

c. The program gives a compilation error. By changing the private int i to private static int i the problem gets resolved

d. The program gives a compilation error. By changing the public static of the method to public only and then calling this method from the main using an instance of Example, the problem gets resolved.

8. Which of the following are true?

Long L9 = new Long(9);

Long L10 = new Long(9);

Long L11 = L10;

long A = 9;

long B = 9;

a. L9 == L10 b. L9 == L11

c. L10 == L11

d. A == L9

e. A == B

9. How should we make a class to handle the events generated by a single user interface component?

a. Subclassing a adapter class is inappropriate in this case - False b. Implements class which handles all the user interface listener methods -

True

 

10. What are the assignments which are valid in the line XXXX

class Super{private int i;public int ma_cd(float f){

Page 45: Java Interview Questions

i = (int) f;return i; }}class Sub extends Super{int j;float g;public Sub(){Super s = new Super();XXXX }

}a. j = i; b. g = f;

c. j = s.ma_cd(3.2f);

d. j = s.i;

e. g = s.f;

11. What is the output of the above code?

outer : for(int x = 0 ; x<2 ; x++){

inner: for(int a = 0 ; a < 2 ; a++){

if (a==1) {

break inner;

}

System.out.println(" a is " + a + " x is " + x );

}

}

a. a is 0 x is 0 b. a is 0 x is 1

c. a is 0 x is 2

d. a is 1 x is 0

e. a is 1 x is 1

f. a is 1 x is 2

g. a is 2 x is 0

h. a is 2 x is 1

Page 46: Java Interview Questions

i. a is 2 x is 2

12. Which is the earliest possible instance that Garbage Collection is activated for String created in line 1.

public static void main(String args[ ]){

1. String s = "abcd"; 2. String s1 = "efghi";

3. String s2 = s+ s1;

4. s = null;

5. s = s1;

6. s1 = s;

a. Before Line 3.

b. Before Line 4.

c. Before Line 5.

d. Before line 6.

13. There is a plan to prepare a class which is going to used in many unrelated parts of the project. The class should be Polygon object which is a Shape. The polygon has a information about the coordinates stored in a vector, color status which states whether true or false. Write a class declaration which describes the above

public class Polygon extends Shape{

vector coord;

boolean colorstatus;

}

14. There is an Employee who is a Person. The employee stores details in a Vector, date employed and number of instances. What are the type of

variables that is to be added to the Employee class

a. Vector b. Date

Page 47: Java Interview Questions

c. Object

d. Person

e. Employee

f. Int

15. What is the constructor argument for the FilterInputStream

a. File b. InputStream

c. DataInputStream

d. BufferedReader

e. InputStreamReader

16. What is the hexadecimal representation of 7 (not more that 4 characters)

0x7

17. What is the output of the following program Example if args[0] is printed

java Example cat dog

a. dog b. cat

c. Example

d. java

e. Null PointerException is thrown

18. What is the modifier for all the listener methods

a. private b. default (no access modifier specified)

c. protected

d. public

e. static

19. Which of the following is true regarding GridBagLayout

Page 48: Java Interview Questions

a. if a component has been given fill both is true, then as the container resizes the component resizes

b. The number of rows and columns are fixed while loading the components.

c. The number of rows and columns are fixed while loading the layout itself .

d. if a component has a non-zero weighty value, then the component grows in height as the container is resized.

20. What is the value of x, if "Test 3" to be printed

Switch(x){

Case 1: System.out.println("Test 1");

Case 2:

Case 3: System.out.println("Test 3"); break;

default : System.out.println("Test 4"); break;

}

a. 1 b. 2

c. 3

d. 4

e. 0

21. If the string array name is argc in the arguments in the main method, which is invoked by the interpreter when a program is executed

a. char string [ ] [ ] b. char [ ] a [ ]

c. char a[ ]

d. String argc

e. String argv[ ]

f. String argc[ ]

22. What is the argument of the KeyListener methods

KeyEvent

Page 49: Java Interview Questions

23. What is the correct declaration of an abstract method

a. public abstract method(); // no ret type b. public void abstract method(): // position ret type

c. public abstract void method() {} // no body

d. public final abstract void method(); // final abs cannot come together

e. public abstract void method () ;

24. How will you override or overload the following method method1 of the Super class in the class Sub?

class Super{

protected void method1() {}

}

class Sub extends Super{}

a. public void method1() { return 0; } b. public int method1() { return 0; }

c. public void method1(StringBuffer s) { }

d. public void method1() { }

e. public void method1(String s) { }

25. What is the value of x if Test 3 is to be printed

if (x > 4) {

System.out.println( "Test 1" );

} else if (x> 9){

System.out.println("Test 2");

} else

System.out.println("Test 3");

a. 0 to 4 b. Less than 0

Page 50: Java Interview Questions

c. 5 to 9

d. Greater than 10

26. What is the range of a char type?

0 – 216-1

27. What does >> and >>> denotes

A. >> is right shift >>> is round B. >> is signed right shift >>> round

C. >> is signed shift and >>> is unsigned shift

D. >> is unsigned >>> is unsigned

28. What are valid keywords

a. NULL b. TRUE

c. implements

d. interface

e. instanceof

f. sizeof

29. Which of the following should be used to have No Order, Duplication or Perfect retrieval mechanism

a. Map // no order, no dupe, perfect retrive b. List //order, dupe, no ret

c. Set //no order, no dupe, not perfect retrieve

d. Collection //no order, dupes, no ret

30. In which LayoutManager, a component to be added to have only the width resized but not the height

a. FlowLayout b. GridLayout

c. GridBagLayout

d. East or West of BorderLayout

Page 51: Java Interview Questions

e. North or South of BorderLayout

31. What is the access modifier for a class member variable which is to be used in the same package where the class is defined

a. protected b. private

c. public

d. no access modifier

e. static

32. What is the body of a Thread

a. run b. begin

c. execute

d. start

e. resume

33. What is the output of the following code?

int i = 0;

do {

System.out.println("The value of i is " + i);

}while(--i > 0)

System.out.println("Finished");

a. The value of i is 1 b. The value of i is 0

c. Finished

d. Compilation Error ( no ; after while condn);

e. Runtime Error

34. What is the output of the following program

class Example{

Page 52: Java Interview Questions

static int arr[] = new int[10];

public static void main(String args[]){

System.out.println(" The value 4th element is " + arr[4]);

} }

a. The value of 4th element is 4 b. The value of 4th element is null

c. The value of 4th element is 0

d. Null Pointer exception is raised

e. Runtime error, because the class is not instantiated

35. Which of the following is the correct class declaration for Car.java. See to that it is a case-sensitive system

a. public class Car{

int in;

public Car(int inn){

in = inn

} }

b. public class Car extends Truck, Vehicle{

int in;

public Car(int inn){

in = inn;

} }

c. public class Car{

int in;

public abstract void raceCar() {System.out.println("RaceCar");}

public Car(int inn){

Page 53: Java Interview Questions

in = inn;

} }

d. import java.io.*;

public class Car extends Object{

int in;

public Car(int inn){

in = inn;

} }

36. Which of the following are true about Threads?

a. Threads can only be created by extending the java.lang.Thread b. Threads of the same program end together

c. A thread which is suspended, cannot be restarted

d. Uncoordination of threads, will result in the data be corrupted

e. Java Interepter will exit only when all non-demon threads are not ended

37. What is true about Garbage Collection mechanism

a. Garbage Collection releases memory at predictable times and at predictable rates

b. A correct program is one in which does not depend on the memory release by the garbage collector

c. A programmer can indicate to the gc mechanism by making reference to a variable as null

d. Garbage collection ensures that there may not be any leakage of memory.

38. A question on Equality operator

Ok

39. What is the output of the following program?

class Super{

String name;

Page 54: Java Interview Questions

Super(String s){

name =s ;

} }

class Sub extends Super{

String name;

Sub(String s){

name=s;

}

public static void main(String args[]){

Super sup = new Super("First");

Sub sub = new Sub("Second");

System.out.println(sub.name + " " + sup.name);

}

}

a. First Second b. Second First

c. Compilation error

d. Runtime error stating same name found in Super as well as in the Sub class

40. An IOException needs to be thrown in some method of a program. Select the correct expression for the raising an exception

a. new Exception(); b. throw Exception();

c. throw new(new IOException());

d. throw new Exception(); // its actually throw new IOException();

e. throws new Exception();

Page 55: Java Interview Questions

41. A Question on Method Overriding

OK

42. What is the output of the following program if method1() does not throw any exception?

try{

method1();

System.out.println("First");

}catch (Exception e){

System.out.prinln("Second");

}finally{

System.out.println("Finally");

} System.out.println("Last");

a. First followed by Finally b. First followed by Finally followed by Last

c. First followed by Last

d. First

43. What are the modifier which cannot be used for a local automatic variable

a. default ( no access modifier ) b. final

c. static

d. public

44. What does getID() method of the event return

a. time of the event b. source of the event

c. nature of the cause of the event

d. place of the event

Page 56: Java Interview Questions

45. What cannot be added to a container

a. Applet b. Panel

c. Component

d. Container

e. MenuItem // can be added only to a Menu

46. How to invoke the constructor from a constructor in the same class

class Super{

float x;

float y;

float z;

Super(float a, float b){

x = a;

y = b;

}

Super(float a, float b, float c){

XXXX

z = c;

}

}

a. super(a,b); b. Super(a,b);

c. this(a,b);

d. This(a,b);

47. What is true about inner classes?

Page 57: Java Interview Questions

a. Inner classes have to be instantiated only in the enclosing class b. Inner classes can access all the final variables of the enclosing class

c. Inner classes cannot be static

d. Inner classes cannot be anonymous class

e. Inner classes can extend another class.

48. What are the correct declaration for an inner class

a. private class C b. new simpleinterface() { //Anonymous so v can use new

c. new complexinterface(x) {

d. new innerclasses() extends someotherclass {

e. new innerclasses extends someotherclass { //Not as we have given a name and so v cannot use new

49. What are true about Listener interfaces

a. A component can have only one listener attached to it b. If a component has multiple listeners attached, the order in which the

listeners are invoked are unknown

c. If a component has multiple listeners, then all the listeners have to be friends

50. If a class member variable is initialized and the value is not be changed at all, what is the modifier to be used during the declaration of the variable

a. const b. fixed

c. public

d. static

e. final

51. What will happen if the following assignment is made, take the above into account?

class Parent

class Derived1 extends Parent

Page 58: Java Interview Questions

class Derived2 extends Parent

Parent p;

Derived d1;

p = d1;

a. Legal at compile time and illegal at run time b. Legal at compile time and possibly legal at run time

c. Legal at compile time and definitely legal at run time

d. Illegal at compile time

52. Which modifiers are to be used to obtain the lock on the object

a. public b. private

c. static

d. synchornized

e. lock

53. What can be possibly used at Point X

// Point X

public class Example

a. import java.awt.*; b. package local.util;

c. class NoExample{}

d. protected class SimpleExample

e. public static final double PI = 3.14;

54. What is the range of int type

-231 to 231-1

55. What is the output of the following program?

class Super{

Page 59: Java Interview Questions

String firstname;

String secondname;

Super(){}

Super(String f, String s){

firstname = f;

secondname = s;

}

public String toString(){

return "It is Monopoly Mr. " + firstname;

}}

class Sub extends Super{

String firstname;

String secondname;

Sub(String f, String s){

firstname = f;

secondname = s;

}

public String toString(){

return "It is Monopoly Mr. " + secondname + " "+ firstname;

}}

class Test{

public static void main(String args[]){

Super first = new Super("Scott", "McNealy");

Page 60: Java Interview Questions

Super second = new Sub("Bill","Gates");

System.out.println( second + " \n " +first);

}}

a. It is Monopoly Mr. Bill Gates

It is Monopoly Mr. Scott

b. It is Monopoly Mr. Gates Bill

It is Monopoly Mr. McNealy

c. It is Monopoly Mr. Gates Bill

It is Monopoly Mr. Scott

d. It is Monopoly Mr. Gates

It is Monopoly Mr. Scott McNealy

56. How to instantiate the class Inner at point XXXX

class Outer{

class Inner{

}

public static void main(String args[]){

XXXX

}

}

a. new Inner(); b. Inner i = Outer.new Inner();

c. Outer.Inner i = new Outer().new Inner();

d. Inner i = Outer(new Inner());

57. What is the output of the following program

Page 61: Java Interview Questions

public class Example{

Stack s1;

Stack s2;

public static void main(String args[]){

new Example();

}

public Example() {

s1 = new Stack();

s2 = new Stack();

method1(s1,s2);

System.out.println(s1 + " " + s2);

}

public void method1(Stack ms1, Stack ms2){

ms2.push(new Long(100));

ms1 = ms2;

}

}

a. Compilation error since ms2 cannot be assigned to ms1. b. s1 [ ] s2 [ ]

c. s1 [ ] s2 [100]

d. s1 [100] s2 [100]

58. What are the legal identifers in Java?

a. %employee b. $employee

c. employ-ee

Page 62: Java Interview Questions

d. employee1

e. _employee

59. Which of the following are true about the listener mathods in AWT? (C)

a. In awt listener menthods generally takes an argument which is an instance of some subclass of java.awt.AWTEvent

b. When multiple listeners are added to a single component the order of invocation of the listeners is not specified.

c. A single component can have multiple listeners added to it.

(11)What is HashMap and Map?

Map is Interface and Hashmap is class that implements that and its not serialized HashMap is non serialized and Hashtable is serialized 

(12)Difference between HashMap and HashTable?

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 doesnt allow). HashMap does not guarantee that the order of  the map will remain constant over time.  

(12a) Difference between Vector and ArrayList? Vector is serialized whereas arraylist is not 

 (13)Difference between Swing and Awt?

AWT are heavyweight componenets. Swings are lightweight components. Hence swing works faster than AWT. 

14) Explain types of Enterprise Beans?

Session beans > Associated with a client and keeps states for a client Entity Beans > Represents some entity in persistent storage such as a database 

15) What is enterprise bean? Server side reusable java component 

Offers services that are hard to implement by the programmer 

Page 63: Java Interview Questions

Sun: Enterprise Bean architecture is a component architecture for the  deployment and development of componentbased distributed business applications.  Applications written using enterprise java beans are scalable, transactional and  multiuser secure. These applications may be written once and then deployed on  any server plattform that supports enterprise java beans specification.  

Enterprise beans are executed by the J2EE server. 

First version 1.0 contained session beans, entity beans were not included. Entity beans were added to version 1.1 which came out during year 1999. Current release is EJB version 1.2   16)Services of EJB? Database management : ?Database connection pooling ?DataSource, offered by the J2EE server. Needed to access connection pool of the server. ?Database access is configured to the J2EE server > easy to change database / database driver 

Transaction management : ?Distributed transactions ?J2EE server offers transaction monitor which can be accessed by the client. 

Security management :

?Authetication ?Authorization ?encryption 

Enterprise java beans can be distributed /replicated into separate machines Distribution/replication offers ?Load balancing, load can be divided into separate servers. ?Failover, if one server fails, others can keep on processing normally. ?Performance, one server is not so heavy loaded. Also, for example Weblogic has thread pools for improving performance in one server. 

Core Java Interview Question Page 3Posted on: March 26, 2008 at 12:00 AM

Question: When you declare a method as abstract method ? Answer: When i want child class to implement the behavior of the method.

Page 64: Java Interview Questions

Core Java Interview Question Page 3      

Question: When you declare a method as abstract method ?

Answer: When i want child class to implement the behavior of the method.

Question: Can I call a abstract method from a non abstract method ? 

Answer: Yes, We can call a abstract method from a Non abstract method in a Java abstract class

Question: What is the difference between an Abstract class and Interface in Java ? or can you explain when you use Abstract classes ? 

Answer: Abstract classes let you define some behaviors; they force your subclasses to provide others. These abstract classes will provide the basic funcationality of your applicatoin, child class which inherited this class will provide the funtionality of the abstract methods in abstract class. When base class calls this method, Java calls the method defined by the child class.

An Interface can only declare constants and instance methods, but cannot implement default behavior.

Interfaces provide a form of multiple inheritance. A class can extend only one other class.

Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.

A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.

Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast.

Question: What is user-defined exception in java ? 

Answer: User-defined expections are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inherite the Exception class as shown below. Using this class we can throw new exceptions.

Java Example : public class noFundException extends Exception { } Throw an exception using a throw statement: public class Fund { ... public Object getFunds() throws noFundException { if (Empty()) throw new noFundException(); ... } } User-defined exceptions should usually be checked.

Question: What is the difference between checked and Unchecked Exceptions in Java ?

Page 65: Java Interview Questions

Answer: All predefined exceptions in Java are either a checked exception or an unchecked exception. Checked exceptions must be caught using try .. catch() block or we should throw the exception using throws clause. If you dont, compilation of program will fail.

Java Exception Hierarchy +--------+ | Object | +--------+ | | +-----------+ | Throwable | +-----------+ / \ / \ +-------+ +-----------+ | Error | | Exception | +-------+ +-----------+ / | \ / | \ \________/ \______/ \ +------------------+ unchecked checked | RuntimeException | +------------------+ / | | \ \_________________/ unchecked

Question: Explain garbage collection ? 

Answer: Garbage collection is an important part of Java's security strategy. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory. The name "garbage collection" implies that objects that are no longer needed by the program are "garbage" and can be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When an object is no longer referenced by the program, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed.

Question: How you can force the garbage collection ?

Answer: Garbage collection automatic process and can't be forced. We can call garbage collector in Java by 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.

Question: What are the field/method access levels (specifiers) and class access levels ?

Answer: Each field and method has an access level:

private: accessible only in this class (package): accessible only in this package

protected: accessible only in this package and in all subclasses of this class

public: accessible everywhere this class is available

Similarly, each class has one of two possible access levels:

(package): class objects can only be declared and manipulated by code in this package public: class objects can be declared and manipulated by code in any package

Question: What are the static fields & static Methods ? 

Page 66: Java Interview Questions

Answer: If a field or method defined as a static, there is only one copy for entire class, rather than one copy for each instance of class. static method cannot accecss non-static field or call non-static method

Example Java Code

static int counter = 0;

A public static field or method can be accessed from outside the class using either the usual notation:

Java-class-object.field-or-method-name

or using the class name instead of the name of the class object:

Java- class-name.field-or-method-name

Question: What are the Final fields & Final Methods ?

Answer: Fields and methods can also be declared final. A final method cannot be overridden in a subclass. A final field is like a constant: once it has been given a value, it cannot be assigned to again.

Java Code

private static final int MAXATTEMPTS = 10;

Question: Describe the wrapper classes in Java ?

Answer: Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes: 

Primitive Wrapper boolean java.lang.Boolean byte java.lang.Byte char java.lang.Character double java.lang.Double float java.lang.Float int java.lang.Integer long java.lang.Long short java.lang.Short void java.lang.Void

Question: What are different types of inner classes ?

Page 67: Java Interview Questions

Answer: Inner classes nest within other classes. A normal class is a direct member of a package. Inner classes, which became available with Java 1.1, are four types

Static member classes Member classes

Local classes

Anonymous classes

Static member classes - a static member class is a static member of a class. Like any other static method, a static member class has access to all static methods of the parent, or top-level, class.

Member Classes - a member class is also defined as a member of a class. Unlike the static variety, the member class is instance specific and has access to any and all methods and members, even the parent's this reference.

Local Classes - Local Classes declared within a block of code and these classes are visible only within the block.

Anonymous Classes - These type of classes does not have any name and its like a local class

Java Anonymous Class Example public class SomeGUI extends JFrame { ... button member declarations ... protected void buildGUI() { button1 = new JButton(); button2 = new JButton(); ... button1.addActionListener( new java.awt.event.ActionListener() <------ Anonymous Class { public void actionPerformed(java.awt.event.ActionEvent e) { // do something } } );

Question: What are the uses of Serialization?

Answer: In some types of applications you have to write the code to serialize objects, but in many cases serialization is performed behind the scenes by various server-side containers.

These are some of the typical uses of serialization:

To persist data for future use. To send data to a remote computer using such client/server Java technologies as RMI or

socket programming.

To "flatten" an object into array of bytes in memory.

To exchange data between applets and servlets.

To store user session in Web applications.

To activate/passivate enterprise java beans.

To send objects between the servers in a cluster.

Page 68: Java Interview Questions

Question: what is a collection ?

Answer: Collection is a group of objects. java.util package provides important types of collections. There are two fundamental types of collections they are Collection and Map. Collection types hold a group of objects, Eg. Lists and Sets where as Map types hold group of objects as key, value pairs Eg. HashMap and Hashtable.

Question: For concatenation of strings, which method is good, StringBuffer or String ?

Answer: StringBuffer is faster than String for concatenation.

Question: What is Runnable interface ? Are there any other ways to make a java program as multithred java program? 

Answer: There are two ways to create new kinds of threads:

- Define a new class that extends the Thread class - Define a new class that implements the Runnable interface, and pass an object of that class to a Thread's constructor. - An advantage of the second approach is that the new class can be a subclass of any class, not just of the Thread class.

Here is a very simple example just to illustrate how to use the second approach to creating threads: class myThread implements Runnable { public void run() { System.out.println("I'm running!"); } } public class tstRunnable { public static void main(String[] args) { myThread my1 = new myThread(); myThread my2 = new myThread(); new Thread(my1).start(); new Thread(my2).start(); }

Question: How can i tell what state a thread is in ? 

Answer: Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive() returned false the thread was either new or terminated but there was simply no way to differentiate between the two.

Starting with the release of Tiger (Java 5) you can now get what state a thread is in by using the getState() method which returns an Enum of Thread.States. A thread can only be in one of the following states at a given point in time. 

NEW A Fresh thread that has not yet started to execute. RUNNABLE A thread that is executing in the Java virtual machine. BLOCKED A thread that is blocked waiting for a monitor lock. WAITING A thread that is wating to be notified by another thread.

TIMED_WAITING A thread that is wating to be notified by another thread for a specific amount of time

TERMINATED A thread whos run method has ended.

Page 69: Java Interview Questions

The folowing code prints out all thread states. public class ThreadStates{ public static void main(String[] args){ Thread t = new Thread(); Thread.State e = t.getState(); Thread.State[] ts = e.values(); for(int i = 0; i < ts.length; i++){ System.out.println(ts[i]); } } }

Question: What methods java providing for Thread communications ? 

Answer: Java provides three methods that threads can use to communicate with each other: wait, notify, and notifyAll. These methods are defined for all Objects (not just Threads). The idea is that a method called by a thread may need to wait for some condition to be satisfied by another thread; in that case, it can call the wait method, which causes its thread to wait until another thread calls notify or notifyAll.

Question: What is the difference between notify and notify All methods ?

Answer: A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notify (so it is often better to use notifyAll than notify).

Question: What is synchronized keyword? In what situations you will Use it?

Answer: Synchronization is the act of serializing access to critical sections of code. We will use this keyword when we expect multiple threads to access/modify the same data. To understand synchronization we need to look into thread execution manner.

Threads may execute in a manner where their paths of execution are completely independent of each other. Neither thread depends upon the other for assistance. For example, one thread might execute a print job, while a second thread repaints a window. And then there are threads that require synchronization, the act of serializing access to critical sections of code, at various moments during their executions. For example, say that two threads need to send data packets over a single network connection. Each thread must be able to send its entire data packet before the other thread starts sending its data packet; otherwise, the data is scrambled. This scenario requires each thread to synchronize its access to the code that does the actual data-packet sending.

If you feel a method is very critical for business that needs to be executed by only one thread at a time (to prevent data loss or corruption), then we need to use synchronized keyword.

EXAMPLE

Some real-world tasks are better modeled by a program that uses threads than by a normal, sequential program. For example, consider a bank whose accounts can be accessed and updated by any of a number of automatic teller machines (ATMs). Each ATM could be a separate thread, responding to deposit and withdrawal requests from different users simultaneously. Of course, it would be important to make sure that two users did not access the same account simultaneously.

Page 70: Java Interview Questions

This is done in Java using synchronization, which can be applied to individual methods, or to sequences of statements.

One or more methods of a class can be declared to be synchronized. When a thread calls an object's synchronized method, the whole object is locked. This means that if another thread tries to call any synchronized method of the same object, the call will block until the lock is released (which happens when the original call finishes). In general, if the value of a field of an object can be changed, then all methods that read or write that field should be synchronized to prevent two threads from trying to write the field at the same time, and to prevent one thread from reading the field while another thread is in the process of writing it.

Here is an example of a BankAccount class that uses synchronized methods to ensure that deposits and withdrawals cannot be performed simultaneously, and to ensure that the account balance cannot be read while either a deposit or a withdrawal is in progress. (To keep the example simple, no check is done to ensure that a withdrawal does not lead to a negative balance.)

public class BankAccount { private double balance; // constructor: set balance to given amount public BankAccount( double initialDeposit ) { balance = initialDeposit; } public synchronized double Balance( ) { return balance; } public synchronized void Deposit( double deposit ) { balance += deposit; } public synchronized void Withdraw( double withdrawal ) { balance -= withdrawal; } }

Note: that the BankAccount's constructor is not declared to be synchronized. That is because it can only be executed when the object is being created, and no other method can be called until that creation is finished.

There are cases where we need to synchronize a group of statements, we can do that using synchrozed statement.

Java Code Example synchronized ( B ) { if ( D > B.Balance() ) { ReportInsuffucientFunds(); } else { B.Withdraw( D ); } }

Question: What is serialization ? 

Answer: Serialization is the process of writing complete state of java object into output stream, that stream can be file or byte array or stream associated with TCP/IP socket.

Question: What does the Serializable interface do ? 

Answer: Serializable is a tagging interface; it prescribes no methods. It serves to assign the Serializable data type to the tagged class and to identify the class as one which the developer has designed for persistence. ObjectOutputStream serializes only those objects which implement this interface.

Page 71: Java Interview Questions

Question: How do I serialize an object to a file ?

Answer: To serialize an object into a stream perform the following actions:

- Open one of the output streams, for exaample FileOutputStream - Chain it with the ObjectOutputStream - Call the method writeObject() providingg the instance of a Serializable object as an argument. - Close the streams

Java Code --------- try{ fOut= new FileOutputStream("c:\\emp.ser"); out = new ObjectOutputStream(fOut); out.writeObject(employee); //serializing System.out.println("An employee is serialized into c:\\emp.ser"); } catch(IOException e){ e.printStackTrace(); }

Question: How do I deserilaize an Object? 

Answer: To deserialize an object, perform the following steps:

- Open an input stream - Chain it with the ObjectInputStream - Call the method readObject() and cast tthe returned object to the class that is being deserialized. - Close the streams

Java Code try{ fIn= new FileInputStream("c:\\emp.ser"); in = new ObjectInputStream(fIn); //de-serializing employee Employee emp = (Employee) in.readObject(); System.out.println("Deserialized " + emp.fName + " " + emp.lName + " from emp.ser "); }catch(IOException e){ e.printStackTrace(); }catch(ClassNotFoundException e){ e.printStackTrace(); }

Question: What is Externalizable Interface ? 

Answer : Externalizable interface is a subclass of Serializable. Java provides Externalizable interface that gives you more control over what is being serialized and it can produce smaller object footprint. ( You can serialize whatever field values you want to serialize)

This interface defines 2 methods: readExternal() and writeExternal() and you have to implement these methods in the class that will be serialized. In these methods you'll have to write code that reads/writes only the values of the attributes you are interested in. Programs that perform serialization and deserialization have to write and read these attributes in the same sequence.

Question: Explain garbage collection ? 

Answer: Garbage collection is an important part of Java's security strategy. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory. The name "garbage collection" implies that objects that are no longer needed by the program are "garbage" and can be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When an object is no longer referenced by

Page 72: Java Interview Questions

the program, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed

Question : How you can force the garbage collection ? 

Answer : Garbage collection automatic process and can't be forced. We can call garbage collector in Java by 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.

Question : What are the field/method access levels (specifiers) and class access levels ? 

Answer: Each field and method has an access level:

private: accessible only in this class (package): accessible only in this package

protected: accessible only in this package and in all subclasses of this class

public: accessible everywhere this class is available

Similarly, each class has one of two possible access levels:

(package): class objects can only be declared and manipulated by code in this package

public: class objects can be declared and manipulated by code in any package

Question: What are the static fields & static Methods ? 

Answer: If a field or method defined as a static, there is only one copy for entire class, rather than one copy for each instance of class. static method cannot accecss non-static field or call non-static method

Example Java Code

static int counter = 0;

A public static field or method can be accessed from outside the class using either the usual notation:

Java-class-object.field-or-method-name

or using the class name instead of the name of the class object:

Java- class-name.field-or-method-name

Page 73: Java Interview Questions

Question: What are the Final fields & Final Methods ? 

Answer: Fields and methods can also be declared final. A final method cannot be overridden in a subclass. A final field is like a constant: once it has been given a value, it cannot be assigned to again.

Java Code

private static final int MAXATTEMPTS = 10;

Question: Describe the wrapper classes in Java ? 

Answer: Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes: 

Primitive Wrapper boolean java.lang.Boolean byte java.lang.Byte char java.lang.Character double java.lang.Double float java.lang.Float int java.lang.Integer long java.lang.Long short java.lang.Short void java.lang.Void

Question: What are different types of inner classes ? 

Answer: Inner classes nest within other classes. A normal class is a direct member of a package. Inner classes, which became available with Java 1.1, are four types

Static member classes Member classes

Local classes

Anonymous classes

Static member classes - a static member class is a static member of a class. Like any other static method, a static member class has access to all static methods of the parent, or top-level, class.

Member Classes - a member class is also defined as a member of a class. Unlike the static variety, the member class is instance specific and has access to any and all methods and members, even the parent's this reference.

Page 74: Java Interview Questions

Local Classes - Local Classes declared within a block of code and these classes are visible only within the block.

Anonymous Classes - These type of classes does not have any name and its like a local class

Java Anonymous Class Example public class SomeGUI extends JFrame { ... button member declarations ... protected void buildGUI() { button1 = new JButton(); button2 = new JButton(); ... button1.addActionListener( new java.awt.event.ActionListener() <------ Anonymous Class { public void actionPerformed(java.awt.event.ActionEvent e) { // do something } } );

Question: What is the difference between notify and notify All methods ? 

Answer: A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notify (so it is often better to use notifyAll than notify).

Question: What is synchronized keyword? In what situations you will Use it? 

Answer: Synchronization is the act of serializing access to critical sections of code. We will use this keyword when we expect multiple threads to access/modify the same data. To understand synchronization we need to look into thread execution manner.

Threads may execute in a manner where their paths of execution are completely independent of each other. Neither thread depends upon the other for assistance. For example, one thread might execute a print job, while a second thread repaints a window. And then there are threads that require synchronization, the act of serializing access to critical sections of code, at various moments during their executions. For example, say that two threads need to send data packets over a single network connection. Each thread must be able to send its entire data packet before the other thread starts sending its data packet; otherwise, the data is scrambled. This scenario requires each thread to synchronize its access to the code that does the actual data-packet sending.

If you feel a method is very critical for business that needs to be executed by only one thread at a time (to prevent data loss or corruption), then we need to use synchronized keyword.

EXAMPLE

Some real-world tasks are better modeled by a program that uses threads than by a normal, sequential program. For example, consider a bank whose accounts can be accessed and updated by any of a number of automatic teller machines (ATMs). Each ATM could be a separate thread, responding to deposit and withdrawal requests from different users simultaneously. Of course, it would be important to make sure that two users did not access the same account simultaneously.

Page 75: Java Interview Questions

This is done in Java using synchronization, which can be applied to individual methods, or to sequences of statements.

One or more methods of a class can be declared to be synchronized. When a thread calls an object's synchronized method, the whole object is locked. This means that if another thread tries to call any synchronized method of the same object, the call will block until the lock is released (which happens when the original call finishes). In general, if the value of a field of an object can be changed, then all methods that read or write that field should be synchronized to prevent two threads from trying to write the field at the same time, and to prevent one thread from reading the field while another thread is in the process of writing it.

Here is an example of a BankAccount class that uses synchronized methods to ensure that deposits and withdrawals cannot be performed simultaneously, and to ensure that the account balance cannot be read while either a deposit or a withdrawal is in progress. (To keep the example simple, no check is done to ensure that a withdrawal does not lead to a negative balance.)

public class BankAccount { private double balance; // constructor: set balance to given amount public BankAccount( double initialDeposit ) { balance = initialDeposit; } public synchronized double Balance( ) { return balance; } public synchronized void Deposit( double deposit ) { balance += deposit; } public synchronized void Withdraw( double withdrawal ) { balance -= withdrawal; } }

Note: that the BankAccount's constructor is not declared to be synchronized. That is because it can only be executed when the object is being created, and no other method can be called until that creation is finished.

There are cases where we need to synchronize a group of statements, we can do that using synchrozed statement.

Java Code Example synchronized ( B ) { if ( D > B.Balance() ) { ReportInsuffucientFunds(); } else { B.Withdraw( D ); } }

1.what  is a transient variable?

A transient variable is a variable that may not be serialized. 

2.which containers use a border Layout as their default layout?

The window, Frame and Dialog classes use a border layout as their default layout. 

3.Why do threads block on I/O?

Page 76: Java Interview Questions

Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed. 

4. How are Observer and Observable used?

Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. 

5. What is synchronization and why is it important?

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 object while another thread is in the process of using or updating that object's value. This often leads to significant errors. 

6. 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. 

7. What's new with the stop(), suspend() and resume() methods in JDK 1.2?

The stop(), suspend() and resume() methods have been deprecated in JDK 1.2. 

8. Is null a keyword?

The null value is not a keyword. 

9. 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. 

10. What method is used to specify a container's layout?

The setLayout() method is used to specify a container's layout. 

11. Which containers use a FlowLayout as their default layout?

The Panel and Applet classes use the FlowLayout as their default layout. 

12. What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state. 

Page 77: Java Interview Questions

13. What is the Collections API?

The Collections API is a set of classes and interfaces that support operations on collections of objects. 

14. Which characters may be used as the second character of an identifier, but not as the first character of an identifier?

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. 

15. What is the List interface?

The List interface provides support for ordered collections of objects. 

16. 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. 

 17. What is the Vector class?

The Vector class provides the capability to implement a growable array of objects 

18. 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. 

19. What is an Iterator interface?

The Iterator interface is used to step through the elements of a Collection. 

20. What is the difference between the >> and >>> operators?

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?

setBounds() 

22. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

Page 78: Java Interview Questions

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. 

23What 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. 

24. Which java.util classes and interfaces support event handling?

The EventObject class and the EventListener interface support event processing. 

25. Is sizeof a keyword?

The sizeof operator is not a keyword. 

26. What are wrapped classes?

Wrapped classes are classes that allow primitive types to be accessed as objects. 

27. Does garbage collection guarantee that a program will not run out of memory?

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?

A package statement must appear as the first line in a source code file (excluding blank lines and comments). 

29. Can an object's finalize() method be invoked while it is reachable?

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. 

30. What is the immediate superclass of the Applet class?

Panel 

31. What is the difference between preemptive scheduling and time slicing?

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

Page 79: Java Interview Questions

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. 

32. Name three Component subclasses that support painting.

The Canvas, Frame, Panel, and Applet classes support painting. 

33. What value does readLine() return when it has reached the end of a file?

The readLine() method returns null when it has reached the end of a file. 

34. What is the immediate superclass of the Dialog class?

Window 

35. What is clipping?

Clipping is the process of confining paint operations to a limited area or shape. 

36. What is a native method?

A native method is a method that is implemented in a language other than Java. 

37. Can a for statement loop indefinitely?

Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ; 

38. What are order of precedence and associativity, and how are they used?

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 

39. When a thread blocks on I/O, what state does it enter?

A thread enters the waiting state when it blocks on I/O. 

40. To what value is a variable of the String type automatically initialized?

The default value of an String type is null. 

41. What is the catch or declare rule for method declarations?

If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause. 

42. What is the difference between a MenuItem and a CheckboxMenuItem?

Page 80: Java Interview Questions

The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked. 

43. What is a task's priority and how is it used in scheduling?

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. 

44. What class is the top of the AWT event hierarchy?

The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy. 

45. 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. 

46. 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. 

47. What is the range of the short type?

The range of the short type is -(2^15) to 2^15 - 1. 

48. What is the range of the char type?

The range of the char type is 0 to 2^16 - 1.  

49. In which package are most of the AWT events that support the event-delegation model defined?

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. 

50. What is the immediate superclass of Menu?

MenuItem 

51. 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. 

Page 81: Java Interview Questions

52. Which class is the immediate superclass of the MenuComponent class.

Object 

53. 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. 

54. What is the difference between the Boolean & operator and the && operator?

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. 

55. Name three subclasses of the Component class.

Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent 

56. What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars. 

57. Which Container method is used to cause a container to be laid out and redisplayed?

validate() 

58. What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java runtime system. 

59. How many times may an object's finalize() method be invoked by the garbage collector?

An object's finalize() method may only be invoked once by the garbage collector. 

60. 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. 

61. What is the argument type of a program's main() method?

A program's main() method takes an argument of the String[] type. 

Page 82: Java Interview Questions

62. Which Java operator is right associative?

The = operator is right associative. 

63. 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.  

64. Can a double value be cast to a byte?

Yes, a double value can be cast to a byte. 

65. What is the difference between a break statement and a continue statement?

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. 

66. 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. 

67. 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. 

68. Name two subclasses of the TextComponent class.

TextField and TextArea 

69. What is the advantage of the event-delegation model over the earlier event-inheritance model?

The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model. 

70. Which containers may have a MenuBar?

Page 83: Java Interview Questions

Frame 

71. How are commas used in the intialization and iteration  parts of a for statement?

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?

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. 

73. What is an abstract method?

An abstract method is a method whose implementation is deferred to a subclass. 

74. How are Java source code files named?

A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension. 

75. What is the relationship between the Canvas class and the Graphics class?

A Canvas object provides access to a Graphics object via its paint() method. 

76. What are the high-level thread states?

The high-level thread states are ready, running, waiting, and dead. 

77. What value does read() return when it has reached the end of a file?

The read() method returns -1 when it has reached the end of a file.  

78. Can a Byte object be cast to a double value?

No, an object cannot be cast to a primitive value. 

79. What is the difference between a static and a non-static inner class?

Page 84: Java Interview Questions

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?

String objects are constants. StringBuffer objects are not. 

81. If a variable is declared as private, where may the variable be accessed?

A private variable may only be accessed within the class in which it is declared. 

82. What is an object's lock and which object's have locks?

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. 

83. What is the Dictionary class?

The Dictionary class provides the capability to store key-value pairs. 

84. How are the elements of a BorderLayout organized?

The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container. 

85. What is the % operator?

It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand. 

86. When can an object reference be cast to an interface reference?

An object reference be cast to an interface reference when the object implements the referenced interface. 

87. What is the difference between a Window and a Frame?

The Frame class extends Window to define a main application window that can have a menu bar. 

88. Which class is extended by all other classes?

The Object class is extended by all other classes. 

Page 85: Java Interview Questions

89. Can an object be garbage collected while it is still reachable?

A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.. 

90. Is the ternary operator written x : y ? z or x ? y : z ?

It is written x ? y : z. 

91. What is the difference between the Font and FontMetrics classes?

The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object. 

92. How is rounding performed under integer division?

The fractional part of the result is truncated. This is known as rounding toward zero. 

93. 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.  

94. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. 

95. What classes of exceptions may be caught by a catch clause?

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?

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. 

97. What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar. 

98. What is the Map interface?

Page 86: Java Interview Questions

The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.  

99. Does a class inherit the constructors of its superclass?

A class does not inherit constructors from any of its superclasses. 

100. For which statements does it make sense to use a label?

The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement. 

101. What is the purpose of the System class?

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?

setEditable() 

103. How are the elements of a CardLayout organized?

The elements of a CardLayout are stacked, one on top of the other, like a deck of cards. 

104. Is &&= a valid Java operator?

No, it is not. 

105. Name the eight primitive Java types.

The eight primitive types are byte, char, short, int, long, float, double, and boolean. 

106. Which class should you use to obtain design information about an object?

The Class class is used to obtain information about an object's design. 

107. What is the relationship between clipping and repainting?

When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting. 

108. Is "abc" a primitive value?

The String literal "abc" is not a primitive value. It is a String object. 

109. What is the relationship between an event-listener interface and an event-adapter class?

Page 87: Java Interview Questions

An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface. 

110. What restrictions are placed on the values of each case of a switch statement?

During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value. 

111. What modifiers may be used with an interface declaration?

An interface may be declared as public or abstract. 

112. Is a class a subclass of itself?

A class is a subclass of itself. 

113. 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. 

114. What event results from the clicking of a button?

The ActionEvent event is generated as the result of the clicking of a button. 

115. How can a GUI component handle its own events?

A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener. 

116. What is the difference between a while statement and a do  statement?

A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. 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. 

117. How are the elements of a GridBagLayout organized?

The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes. 

118. What advantage do Java's layout managers provide over traditional windowing systems?

Page 88: Java Interview Questions

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. 

119. 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. 

120. What modifiers can be used with a local inner class?

A local inner class may be final or abstract. 

121. What is the difference between static and non-static variables?

A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance. 

122. 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. 

123. What is the purpose of the File class?

The File class is used to create objects that provide access to the files and directories of a local file system. 

124. Can an exception be rethrown?

Yes, an exception can be rethrown. 

125. Which Math method is used to calculate the absolute value of a number?

The abs() method is used to calculate absolute values. 

126. 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. 

127. When does the compiler supply a default constructor for a class?

The compiler supplies a default constructor for a class if no other constructors are provided. 

128. When is the finally clause of a try-catch-finally statement executed?

Page 89: Java Interview Questions

The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause. 

129. Which class is the immediate superclass of the Container class?

Component 

130. 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. 

131. How can the Checkbox class be used to create a radio button?

By associating Checkbox objects with a CheckboxGroup. 

132. Which non-Unicode letter characters may be used as the first character of an identifier?

The non-Unicode letter characters $ and _ may appear as the first character of an identifier 

133. What restrictions are placed on method overloading?

Two methods may not have the same name and argument list but different return types. 

134. 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. 

135. What is casting?

There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference. 

136. What is the return type of a program's main() method?

A program's main() method has a void return type. 

137. Name four Container classes.

Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane 

Page 90: Java Interview Questions

138. What is the difference between a Choice and a List?

A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items. 

139. What class of exceptions are generated by the Java run-time system?

The Java runtime system generates RuntimeException and Error exceptions. 

140. What class allows you to read objects directly from a stream?

The ObjectInputStream class supports the reading of objects from input streams. 

141. What is the difference between a field variable and a local variable?

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?

The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable. 

143. How are this() and super() used with constructors?

this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. 

144. What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution?

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?

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. 

Page 91: Java Interview Questions

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?

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. 

147. Why are the methods of the Math class static?

So they can be invoked as if they are a mathematical code library. 

148. What Checkbox method allows you to tell if a Checkbox is checked?

getState() 

149. What state is a thread in when it is executing?

An executing thread is in the running state. 

150. What are the legal operands of the instanceof operator?

The left operand is an object reference or null value and the right operand is a class, interface, or array type. 

151. How are the elements of a GridLayout organized?

The elements of a GridBad layout are of equal size and are laid out using the squares of a grid. 

152. What an I/O filter?

An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. 

153. If an object is garbage collected, can it become reachable again?

Once an object is garbage collected, it ceases to exist.  It can no longer become reachable again.  

154. 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.  

Page 92: Java Interview Questions

155. What classes of exceptions may be thrown by a throw statement?

A throw statement may throw any expression that may be assigned to the Throwable type. 

156. What are E and PI?

E is the base of the natural logarithm and PI is mathematical value pi. 

157. Are true and false keywords?

The values true and false are not keywords. 

158. What is a void return type?

A void return type indicates that a method does not return a value. 

159. 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. 

160. What is the difference between the File and RandomAccessFile classes?

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. 

161. What happens when you add a double value to a String?

The result is a String object. 

162. What is your platform's default character encoding?

If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.. 

163. Which package is always imported by default?

The java.lang package is always imported by default. 

164. What interface must an object implement before it can be written to a stream as an object?

An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. 

Page 93: Java Interview Questions

165. How are this and super used?

this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance. 

166. What is the purpose of garbage collection?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused. 

167. What is a compilation unit?

A compilation unit is a Java source code file. 

168. What interface is extended by AWT event listeners?

All AWT event listeners extend the java.util.EventListener interface.  

169. What restrictions are 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. The overriding method may not throw any exceptions that may not be thrown by the overridden method. 

170. How can a dead thread be restarted?

A dead thread cannot be restarted. 

171. What happens if an exception is not caught?

An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown. 

172. What is a layout manager?

A layout manager is an object that is used to organize components in a container. 

173. Which arithmetic operations can result in the throwing of an ArithmeticException?

Integer / and % can result in the throwing of an ArithmeticException. 

174. 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. 

Page 94: Java Interview Questions

175. Can an abstract class be final?

An abstract class may not be declared as final. 

176. 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. 

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?

The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.  

178. What is numeric promotion?

Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int

values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required. 

179. What is the difference between a Scrollbar and a ScrollPane?

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling. 

180. What is the difference between a public and a non-public class?

A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package. 

181. To what value is a variable of the boolean type automatically initialized?

The default value of the boolean type is false. 

182. Can try statements be nested?

Try statements may be tested.  

183. What is the difference between the prefix and postfix forms of the ++ operator?

Page 95: Java Interview Questions

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. 

184. What is the purpose of a statement block?

A statement block is used to organize a sequence of statements as a single statement group. 

185. What is a Java package and how is it used?

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. 

186. What modifiers may be used with a top-level class?

A top-level class may be public, abstract, or final. 

187. What are the Object and Class classes used for?

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?

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. The remaining catch clauses are ignored. 

189. Can an unreachable object become reachable again?

An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects. 

190. When is an object subject to garbage collection?

An object is subject to garbage collection when it becomes unreachable to the program in which it is used. 

191. 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. 

Page 96: Java Interview Questions

192. What methods are used to get and set the text label displayed by a Button object?

getLabel() and setLabel() 

193. Which Component subclass is used for drawing and painting?

Canvas 

194. What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. 

195. 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. 

196. What are the problems faced by Java programmers who don't use layout managers?

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. 

197. What is the difference between an if statement and a switch statement?

The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed. 

198. What happens when you add a double value to a String?

The result is a String object. 

199. What is the List interface?

The List interface provides support for ordered collections of objects.

FAQ-JAVA-Differences-Between-JAVA-And-C-CPP The Differences Between Java, C And C++

Page 97: Java Interview Questions

This article aims to set out some of the differences between C, C++ and Java. What

it does not aim to do is conclude that one language is always the best one to use.

Language choice depends upon a range of factors including field of application

(operating systems, desktop software, web applications etc), what programming

paradigm suits the application (OOP, procedural, etc), the target platform and

available programmer expertise. What follows should help you decide where it might

be suitable to use C, C++ or Java.

Paradigm

C is geared towards procedural programming. That is, you write a number of

procedures to do certain tasks and build up a program by calling those procedures as

needed.

Java, on the other hand, is geared towards OOP (object oriented programming). With

OOP, you define classes which represent an entity (for example, a window, a button,

a string of text, a file). From one class many objects may be created, with every

object of a certain class having the fields (places to store data) and methods (named

blocks of code associated with the object) as defined by the class.

It is possible to write in an object oriented style in C and in a procedural style in

Java, but in each case the language will somewhat get in your way. C++ is designed

to support both paradigms.

Preprocessor

All C and C++ compilers implement a stage of compilation known as the

preprocessor. The preprocessor basically performs an intelligent search and replace

on identifiers that have been declared using the #define or #typedef directives.

#define can also be used to declare macros. For example, a macro MAX(x,y) could

be defined to return whichever of x or y holds the greatest value. This is not like

calling a function as the substitution is done before the code is compiled. Most of the

preprocessor definitions in C and C++ are stored in header files, which complement

the actual source code files.

Java does not have a preprocessor. Constant data members are used in place of the

#define directive and class definitions are used in lieu of the #typedef directive,

however there is no substitute for macros, which can be useful. The Java approach to

defining constants and naming types of data structures is probably conceptually

simpler for the programmer. Additionally, Java programs don't use header files; the

Java compiler builds class definitions directly from the source code files, which

contain both class definitions and method implementations.

Memory Management

Page 98: Java Interview Questions

In C and C++, any memory that is allocated on the heap (e.g. using malloc or new) must be explicitly freed by the programmer

(e.g. using free or delete). Forgetting to free memory leads to memory leaks, and in long-running programs can lead to the

memory usage of the program growing very large.

Java provides garbage collection, meaning that memory is freed automatically when

it is no longer reachable by any references. This prevents memory leaks, but can

lead to pauses in execution while the garbage collector runs. Also, there is no

promise of timely destruction in Java.

Pointers

Most developers agree that the misuse of pointers causes the majority of bugs in C

and C++ programs. Put simply, when you have pointers, you have the ability to

attempt to access memory that isn't yours and modify memory relating to a different

data structure than the one you intended by accident. C/C++ programmers regularly

use complex pointer arithmetic to create and maintain dynamic data structures. It's

powerful, but can lead to a lot of time spent hunting down complex and often subtle

bugs that arise as a result of having unguarded memory access.

The Java language does not support pointers. Instead, it provides similar

functionality by making heavy use of references. A reference can be thought of as a

"safe pointer" - the programmer can not directly manipulate the memory address.

Java passes all arrays and objects by reference. This approach prevents common

errors due to pointer mismanagement. It also makes programming easier in a lot of

ways simply because the correct usage of pointers is easily misunderstood by

inexperienced programmers.

C++ does provide references too. It considers them as aliases to another variable or object. They are safer than pointers where they can be used. Bounds Checking

An array in C or C++ is not bounds checked, so attempts to access the sixth element

of a 5-element array will appear to work - that is, no runtime error will occur. This

means the programmer needs to code very carefully, especially considering the

potential for buffer overflow attacks.

Java will bounds check arrays to prevent this from happening, of course with a little extra runtime cost. Portability And Performance

C and C++ both compile to native machine code. This means that, with a good

compiler, programs written in these languages will perform very well. However, it

also restricts them to running on the platform they were compiled to run on.

Page 99: Java Interview Questions

Java generally compiles to Java bytecode, which then runs on top of a virtual

machine (the JVM). The JVM has to turn instructions in the bytecode into instructions

that are understood by the machine that the bytecode is running on. This gives a

runtime performance penalty (although this is getting less significant as the JVM

improves and computers get faster). However, now only the virtual machine (and

standard library) have to be ported to different platforms, then the bytecode for

many Java programs can be executed on that platform. So bytecode is portable

accross different operating systems and processors.

Complex Data Types There are two types of complex data types in C: structures and unions. C++ adds classes to this list. Java only implements one of these data types: classes.

A structure can be emulated by a class - simply write a class without any methods

and make all the fields public. However, emulating a union is not always possible in

Java, and the memory saving advantages unions hold in C may not carry accross.

Java presents a simpler model but at the cost of not being able to save a little

memory. For many applications this will be a non-issue.

Strings

C has no built-in string data type. The standard technique adopted among C

programmers is that of using null-terminated arrays of characters to represent

strings. This practice if often seen in C++ programs too.

Neither C++ or Java have string as a primitive type, but they do both have string objects that are a standard part of the language.

In Java this type is called String, and in C++ it is called CString.

Multiple Inheritance

Multiple inheritance is a feature of some object oriented languages that allows you to

derive a class from multiple parent classes. Although multiple inheritance is indeed

powerful (and sometimes the logical way to define a class hierachy), it is complicated

to use correctly and can create situations where it's uncertain which method will be

executed. For example, if each of the parent classes provide a method X and the

derived class does not, it is unclear which X should be invoked. It is also complicated

to implement from the compiler perspective.

C++ supports multiple inheritance. Java provides no direct support for multiple

inheritance, but you can implement functionality similar to multiple inheritance by

using interfaces in Java. Java interfaces provide method descriptions but contain no

implementations. Therefore implementations can only be inherited from one class, so

there is no ambiguity over which method to invoke.

Operator Overloading

Page 100: Java Interview Questions

Operator overloading enables a class to define special behaviour for built-in operators

when they are applied to objects of that class. For example, if the * (multiply)

operator was to be used on two objects of type Matrix, then matrix multiplication

could be implemented. This allows object types to feel much more tightly integrated

into the language and can deliver much clearer code. However, sometimes it is not

clear what a particular operator would sensibly do for a particular type, whereas a

well-named method call would be clear.

Operator overloading is considered a prominent feature in C++. It is not supported in Java, probably in an effort to keep the

language as simple as possible and help ensure it is obvious what code does, even though it may take longer to type and read.

Automatic Coercions

Feature C C++ Java Paradigms Procedural Procedural, OOP, Generic Programming

OOP, GenericProgramming (from Java5)

Form of Compiled Source Executable

Native Code Executable Native Code Java bytecode