Search

Core Java Interview Questions


1.       An identifier in java must begin with a letter , a dollar sign($), or an underscore
(-); subsequent characters may be letters, dollar signs, underscores, or digits.
2.       There are three top-level elements that may appear in a file. None of these elements is required. If they are present, then they must appear in the following order:
-package declaration
-import statements
-class definitions
3.       A static method can't be overridden to non-static and vice versa.
4.       The variables in java can have the same name as method or class.
5.       All the static variables are initialized when the class is loaded.
6.       An interface can extend more than one interface, while a class can extend only one class.
7.       The variables in an interface are implicitly final and static.If the interface , itself, is declared as public the methods and variables are implicitly public.
8.       A final class cannot have abstract methods.
9.       All methods of a final class are automatically final.
10.    While casting one class to another subclass to superclass is allowed without any type casting.
e.g.. A extends B , B b = new A(); is valid but not the reverse.
11.    The String class in java is immutable. Once an instance is created, the string it contains cannot be changed.
e.g. String s1 = new String("test"); s1.concat("test1"); Even after calling concat() method on s1, the value of s1 will remain to be "test". What actually happens is a new instance is created.
But the StringBuffer class is mutable.
12.    The short circuit logical operators && and || provide logical AND and OR operations on boolean types and unlike & and | , these are not applicable to integral types. The valuable additional feature provided by these operators is the right operand is not evaluated if the result of the operation can be determined after evaluating only the left operand.
13.    The difference between x = ++y; and x = y++;
In the first case y will be incremented first and then assigned to x. In second case first y will be assigned to x then it will be incremented.
14.    The initialization values for different data types in java is as follows
byte = 0, int = 0, short = 0, char = '\u0000', long = 0L, float = 0.0f, double = 0.0d, boolean = false,
object referenece(of any object) = null.
15.    An overriding method may not throw a checked exception unless the overridden method also throws that exception or a superclass of that exception.
16.    Interface methods can't be native, static, synchronized, final, private, protected or abstract.
17.    The String class is a final class, it can't be subclassed.
18.    The Math class has a private constructor, it can't be instantiated.
19.    The two kinds of exceptions in java are : Compile time (Checked ) and Run time (Unchecked) exceptions. All subclasses of Exception except the RunTimeException and its subclasses are checked exceptions.
Examples of Checked exception : IOException, ClassNotFoundException.
Examples of Runtime exception :ArrayIndexOutOfBoundsException,NullPointerException, ClassCastException, ArithmeticException, NumberFormatException.
20.    The various methods of Java.lang.Object are
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString and wait.
21.    Garbage collection in java cannot be forced. The methods used to call garbage collection thread are System.gc() and Runtime.gc()
22.    Inner class may be private, protected, final, abstract or static.
23.    To refer to a field or method in the outer class instance from within the inner class, use Outer.this.fieldname .
24.    Inner classes may not declare static initializers or static members unless they are compile time constants i.e. static final var = value;
25.    A nested class cannot have the same name as any of its enclosing classes.









26.    An example of creation of instance of an inner class from some other class:
class Outer
{
public class Inner{}
}
class Another
{
public void amethod()
{
Outer.Inner i = new Outer().new Inner();
}
}
27.    The range of Thread priority in java is 1-10. The minimum priority is 1 and the maximum is 10. The default priority of any thread in java is 5.
28.    Using the synchronized keyword in the method declaration, requires a thread obtain the lock for this object before it can execute the method.
29.    A synchronized method can be overridden to be not synchronized and vice versa.
30.    There are two ways to mark code as synchronized:
a.) Synchronize an entire method by putting the synchronized modifier in the method's declaration.
b.) Synchronize a subset of a method by surrounding the desired lines of code with curly brackets ({}).
31.    The notify() mthod moves one thread, that is waiting on this object's monitor, into the Ready state. This could be any of the waiting threads.
32.    The notifyAll() method moves all threads, waiting on this object's monitor into the Ready state.
33.    The argument to switch can be either byte, short , char or int.
34.    Breaking to a label (using break <labelname>;) means that the loop at the label will be terminated and any outer loop will keep iterating. While a continue to a label (using continue <lablename>;) continues execution with the next iteration of the labeled loop.
35.    To ensure that assertions don't become performance liability, you can disable them when your program is started. Also by default, assertions are disabled.
36.    An assertion is a statement in the Java language that enables you to test your assumptions about your program.
37.    Some of the advantages of writing assertions while programming are:
a.) Detect and correct bugs
b.) Enhance maintainability as writing assertions helps you document the inner workings of your code
38.    In order for the javac compiler to accept code containing assertions, you must use the -source 1.4 command-line option as in the below example:
javac -source 1.4 TestClass.java
39.    The setClassAssertionStatus returns a boolean instead of throwing an exception if it is invoked when it's too late to set the assertion status (i.e., if the named class has already been initialized)
40.    A static method can only call static variables or other static methods, without using the instance of the class. e.g. main() method can't directly access any non static method or variable, but using the instance of the class it can.
41.    The if() statement in java takes only boolean as an argument. Please note that if (a=true){}, provided a is of type boolean is a valid statement and the code inside the if block will be executed.
42.    The (-0.0 == 0.0) will return true, while (5.0==-5.0) will return false.
43.    An abstract class may not have even a single abstract method but if a class has an abstract method it has to be declared as abstract.
44.    The valueOf() method converts data from its internal format into a human-readable form. It is a static method that is overloaded within String class for all of Java's built-in types, so that each type can be converted properly into a string.
45.    The main difference between Vector and ArrayList is that Vector is synchronized while the ArrayList is not.
46.    The statement float f = 5.0; will give compilation error as default type for floating values is double and double can't be directly assigned to float without casting.


47.    The equals() method in String class compares the values of two Strings while == compares the memory address of the objects being compared.
e.g. String s = new String("test"); String s1 = new String("test");
s.equals(s1) will return true while s==s1 will return false.
48.    The example of array declaration along with initialization - int k[] = new int[]{1,2,3,4,9};
49.    The octal number in java is preceded by 0 while the hexadecimal by 0x (x may be in small case or upper case)
e.g.                          octal :022                                              hexadecimal :0x12
50.    A constructor cannot be native, abstract, static, synchronized or final.


  1. What is meant by Java ?                                                                  
  2. What is meant by a class ?
  3. What is meant by a method ?                          
  4. What are the OOPS concepts in Java ?
  5. What is meant by encapsulation ? Explain with an example
  6. What is meant by inheritance ? Explain with an example
  7. What is meant by polymorphism ? Explain with an example
  8. Is multiple inheritance allowed in Java ? Why ?
  9. What is meant by Java interpreter ?                                               
  10. What is meant by JVM ?
  11. What is a compilation unit ?                                                            
  12. What is meant by identifiers ?
  13. What are the different types of modifiers ?
  14. What are the access modifiers in Java ?
  15. What are the primitive data types in Java ?
  16. What is meant by a wrapper class ?
  17. What is meant by static variable and static method ?
  18. What is meant by Garbage collection ?         
  19. What is meant by abstract class
  20. What is meant by final class, methods and variables ?
  21. What is meant by interface ?                                           
  22. What is meant by a resource leak ?
  23. What is the difference between interface and abstract class ?
  24. What is the difference between public private, protected and static
  25. What is meant by method overloading ?
  26. What is meant by method overriding ?          
  27. What is singleton class ?
  28. What is the difference between an array and a vector ?
  29. What is meant by constructor ?                                       
  30. What is meant by casting ?
  31. What is the difference between final, finally and finalize ?
  32. What is meant by packages ?                                          
  33. What are all the packages ?
  34. Name 2 calsses you have used ?
  35. Name 2 classes that can store arbitrary number of objects ?
  36. What is the difference between java.applet.* and java.applet.Applet ?
  37. What is a default package ?
  38. What is meant by a super class and how can you call a super class ?
  39. What is anonymous class ?                                              
  40. Name interfaces without a method ?
  41. What is the use of an interface ?                     
  42. What is a serializable interface ?
  43. How to prevent field from serialization ?      
  44. What is meant by exception ?
  45. How can you avoid the runtime exception ?
  46. What is the difference between throw and throws ?
  47. What is the use of finally ?
  48. Can multiple catch statements be used in exceptions ?
  49. Is it possible to write a try within a try statement ?
50.What is the method to find if the object exited or not ?
51.What is meant by a Thread ?                     
52.What is meant by multi-threading ?
52.What is the 2 way of creating a thread ? Which is the best way and why ?
53.What is the method to find if a thread is active or not ?
54.What are the thread-to-thread communcation ?
55.What is the difference between sleep and suspend ?
56.Can thread become a member of another thread ?
57.What is meant by deadlock ?
58.How can you avoid a deadlock ?
59.What are the three typs of priority ?
59.What is the use of synchronizations ?
60.Garbage collector thread belongs to which priority ?
61.What is meant by time-slicing ?                 
62.What is the use of ‘this’ ?
63.How can you find the length and capacity of a string buffer ?
64.How to compare two strings ?
65.What are the interfaces defined by Java.lang ?
66.What is the purpose of run-time class and system class
67.What is meant by Stream and Types ?
68.What is the method used to clear the buffer ?
69.What is meant by Stream Tokenizer ?
70.What is serialization and de-serialisation ? What is meant by Applet ?
71.How to find the host from which the Applet has originated ?
72.What is the life cycle of an Applet ?
73.How do you load an HTML page from an Applet ?
74.What is meant by Applet Stub Interface ?
75.What is meant by getCodeBase and getDocumentBase method ?
76.How can you call an applet from a HTML file ?
77.What is meant by Applet Flickering ?       
78.What are the different types of Layouts ?  
What is meant by CardLayout ?
What is the difference between GridLayout and GridBagLayout
What is the difference between menuitem and checkboxmenu item.
What is meant by vector class,dictionary class,hash table,and property class ?
Which class has no duplicate elements ?                       
What is resource bundle ?
What is an enumeration class ?                                       
What is meant by Swing ?
What is the difference between AWT and Swing ?
What is the difference between an applet and a Japplet
What are all the components used in Swing ?
What is meant by tab pans ?                                                           
What is the use of JTree ?
How can you add and remove nodes in Jtree.
What is the method to expand and collapse nodes in a Jtree ?
What is the use of JTable ?                                                               
What is meant by JFC ?
What is the class in Swing to change the appearance of the Frame in Runtime.
How to reduce flicking in animation ?                           
What is JDBC ?
How do you connect to the database ? What are the steps ?
What are the drivers available in JDBC ? Explain
How can you load the driver ?
What are the different types of statement s ?
How can you created JDBC statements ?
How will you perform transactions using JDBC ?
What are the two drivers for web apllication?
What are the different types of 2 tier and 3 tier architecture ?
How can you retrieve warning in JDBC ?
What is the exception thrown by JDBC ?
What is meants by PreparedStatement ?
What is difference between PreparedStatement and Statement ?
How can you call the stored procedures ?           
What is meant by a ResultSet ?
What is the difference between ExecuteUpdate and ExecuteQuery ?
How do you know which driver is connected to a database ?
What is DSN and System DSN and differentiate these two ?
What is meant by TCP, IP, UDP ?
What is the difference between TCP and UDP ?
What is a proxy server ?                                                    

What is meant by URL

What is the use of parameter tag ?
What is audio clip Interface and what are all the methods in it ?
What is the difference between getAppletInfo and getParameterInfo ?
How to communicate between applet and an applet ?
What is meant by event handling ?
1.       What are all the listeners in java and explain ?
2.       What is meant by an adapter class ?
3.       What are the types of mouse event listeners ?
4.       What are the types of methods in mouse listeners ?
5.        What is the difference between panel and frame ?
6.        What is the default layout of the panel and frame ?
7.        What is meant by controls and types ?
8.        What is the difference between a scroll bar and a scroll panel.
9.        What is the difference between list and choice ?
10.     How to place a component on Windows ?
11.    What is a socket and server sockets ?
12.    When MalformedURLException and UnknownHost Exception throws ?
13.    What is InetAddress ?
14.    What is datagram and datagram packets and datagram sockets ?
15.    Write the range of multicast socket IP address ?
16.    What is meant by a servlet ?                            
17.    What are the types of servlets ? Explain
18.    What is the different between a Servlet and a CGI.
19.    What is the difference between 2 types of Servlets ?
20.    What is the type of method for sending request from HTTP server ?
21.    What are the exceptions thrown by Servlets ? Why ?
22.    What is the life cycle of a servlet ?
23.    What is meant by cookies ?             
24.    What is HTTP Session ?    
25.    What is the difference between GET and POST methods ?
26.    How can you run a Servlet Program ?
27.    How to commuincate between an applet and a servlet ?
28.    What is a Servlet-to-Servlet communcation ?
29.    What is Session Tracking ?                               
30.    What are the security issues in Servlets ?
31.    What is HTTP Tunneling ?                               
32.    How do you load an image in a Servlet ?
33.    What is Servlet Chaining ?                                
34.    What is URL Rewriting ?
35.    What is context switching ?                              
36.    What is meant by RMI ?                  
37.    Explain RMI Architecture ?                             
38.    What is meant by a stub ?                
39.    What is meant by a skelotn ?
40.    What is meant by serialisation and deserialisation ?
41.    What is meant by RRL ?                                                  
42.    What is the use of TL ?
43.    What is RMI Registry ?                                                     
44.    What is rmic ?
45.    How will you pass parameter in RMI ?
46.    What exceptions are thrown by RMI ?
47.    What are the steps involved in RMI ?
48.    What is meant by bind(), rebind(), unbind() and lookup() methods
49.    What are the advanatages of RMI ?
50.    What is JNI ?                                       
51.    What is Remote Interface ?
52.    What class is used to create Server side object ?
53.    What class is used to bind the server object with RMI Registry ?
54.    What is the use of getWriter method ?
55.    What is meant by Javabeans ?        
56.    What is JAR file ?
57.    What is meant by manifest files ?   
58.    What is Introspection ?
59.    What are the steps involved to create a bean ?
60.    Say any two properties in Beans ?
61.    What is persistence ?                                          
62.    What is the use of beaninfo ?
63.    What are the interfaces you used in Beans ?
64.    What are the classes you used in Beans ?

1. What are the difference between Java and C++?
C++ does not have Garbage collector where as Java have Garbage collector & Hence Memory management is easy in Java.Java is Platform independent & hence it is portable among different platforms.There is no multiple inheritance in Java & it can be implemented with interfaces.
2. What is Method Signature?
The combination of method name and parameter list is called the method signature.
3. What are Packages?
Packages are libraries of related classes and interfaces that are grouped together.
4. What is an Abstract class?
Abstract classes are classes from which no object can be initiated. Abstract classes cannot have objects of their own. Abstract class can be subclassed which in turn can instantiate and have objects of their own.
5. What are Interfaces?
Interfaces contain a collection of methods that are implemented elsewhere. Methods in an interface class are public and abstract. Therefore interface cannot be instantiated. · Provide security for application · An interface can extend any number of interfaces · A class can implement any number of interfaces · An interface can be implemented in a class by using the keyword implements · Most often interfaces are used to bring about a relationship between different classes.
6. What is an Encapsulation?
Encapsulation is the mechanism that binds together code and the data it manipulates and keeps both safe from outside interface and misuse.
7. What is inheritance?
It is the process by which one object acquires the properties of other objects.
8. What is polymorphism?
The capability of the method to react differently on different objects is called polymorphism.
9. What are constructors?
A constructor instantiates an object immediately upon creation. It has the same name as the class in which it resides. And it is syntactically similar to a method.
10. What is the difference between Methods and constructors?
· Constructor has the same name as class in which it resides, where as methods can have any name. · Constructor will be executed at the time of object instantiation, where as method executes when ever it is called. · Constructor will not have any return type. But methods may have return type. If method doesn't have any return type, we have to declare that as 'void'.
11. What is garbage collection in Java?
When no reference to an object exists, that object assumed to be no longer needed, and the memory occupied by the object can be reclaimed. Garbage collection only occurs sporadically during the execution of the program.
12. What is the use of Finalize Method?
Sometimes an object will need to perform some action when it destroyed. For example, if an object is holding some non-Java resources such as a file handle or then you might want to make sure these resources are freed before an object destroy. To handle such situations, Java provides a mechanism called finalization. By using finalization we can define specific actions that will occur when an object is just about to reclaim by the garbage collector.
13. What for transient keyword is used?
Transient keyword is used for security purpose and when we use this keyword for any object that particular object cannot be serializable.
14. What is the difference between overloading of methods and overriding of methods?
When we use multiple methods with same name but with different parameters we call it as Overloading of methods (these multiple methods has to be created prior to their usage). And if we just use a predefined method and write our own method then that is called as overriding of methods.
15. What is the difference between String and StringBuffer?

String objects are said to be immutable, which means that they cannot be changed. To change the string referenced by string variable we have to throw away the reference to the old string & replace it with a reference to a new one. But StringBuffer object can be altered directly and they are called mutable Strings.
16. Define instanceof operator and equals() method?
The instanceof operator returns true or false based on whether the object is an instance of the named class or any of that class's subclasses. It is possible to have two different String objects that contain the same values. If we use == operator to compare these objects, they are considered to be unequal. Although their contents match, they are not the same objects. In order to see whether two String objects have the same values, a method called equals() is used.
17. What is an inner class?
If we define a class inside a class, then that is called an inner class. These inner classes can have access to variables and methods within the scope of a top-level class that they would not have as a separate class. Rules governing the scope of an inner class closely match those governing the variables. An inner class's name is not visible outside its scope, except in a fully qualified name, which helps in structuring classes within a package.

18. What is meant by synchronized method?
When different threads act upon one common object a problem arises. A thread could be Interrupted when it is attempting to modify an object, and then another thread actually modifies that particular object. Consequently the first thread is made to run again, and this time the object is modified once more, which leads to errors. These type of problems can be avoided by using synchronized method. With this method, one thread can finish execution before another thread as per the priority can act upon the same object.
19. What are the different types of initiating a thread?
There are two ways to initiate a thread, they are 1. Create a class that extends the Thread class or 2. Create a class that implements the Runnable interface.
20. What is meant by serializable interface?
An object indicates that it can be used with streams by implementing the Serializable interface. The sole purpose of Serializable interface is to indicate that objects of that class can be stored and retrieved in serial form. Serialization enables object persistence because the stored object continues to serve a purpose even when no Java program is running. It contains information that can be restored in a program so that it can resume functioning.
21. What does try…catch…finally block will do?
The function of try … catch … finally block is "try this bit of code that might cause an exception. If it executes okay, go on with the program. If it doesn't, catch the exception deal with it and also execute the code in finally clause either code in the try … catch block cause an exception or not."
22. What is difference between throw and throws?
If you write method that might throw an exception, then you must declare the possibility, using throws statement. And if you don't handle the exception in some way the method has no way to complete successfully. For this situation we use throw statement. i.e. we throw an exception with a statement that consists of keyword throw, followed by an exception object. This means we can throw our own exception. For this we have to use try … catch block. Or we can also create an exception object and throw it in single statement. For example throw new DreadfulProblemException("Terrible difficulties")
23. What are the differences between an interface and an abstract class?
Some use a semantic distinction: an abstract superclass models the "is" relationship, while an interface models the "has" relationship. The rule would thus be, if it's a subtype, inherit; otherwise, implement. But where the object boundaries are themselves at stake, it's circular to state this unless there are real-world metaphors to distinguish the objects from their properties and parents. So where there are no real-world metaphors, you have to understand the practical differences in Java (esp. vs. C++). Most differences between interfaces and abstract classes stem from three characteristics: · Both define method signatures that a derived class will have. · An abstract class can also define a partial implementation. · A class can implement many interfaces, but inherit from only one class.
24. What is the difference between Swing and AWT?
1. Swing let you specify which look and feel your progra's GUI uses. AWT components always have the look and feel of the native platform.
2. Swing components are implemented with absolute with no native code.
3. Swing components are in javax.swing package where as AWT components are in java.awt package.
25. what is the difference among Arrays, Vectors and Hash maps?
Arrays
Vectors
Hash Maps
  • Can store any one type of data.
  • Can store objects also
  • Cannot be growable
  • Can store any combination of data (like strings, integers, etc.)
  • Only objects can be stored
  • Vectors are growable.
  • All the properties of this is similar to vectors.
  • This will have key, value pair
  • Retrieve the elements faster.



Strings


Q - Java provides two different string classes from which string objects can be instantiated. What
are they?

A - The two classes are:

     String
     StringBuffer

Q - The StringBuffer class is used for strings that are not allowed to change. The String class is
used for strings that are modified by the program: True or False. If false, explain why.

A - False. This statement is backwards. The String class is used for strings that are not allowed to change. The
StringBuffer class is used for strings that are modified by the program.

Q - While the contents of a String object cannot be modified, a reference to a String object can be
caused to point to a different String object: True or False. If false, explain why.

A - True.

Q - The use of the new operator is required for instantiation of objects of type String: True or
False? If false, explain your answer.

A - False. A String object can be instantiated using either of the following statements:

     String str1 = new String("String named str2");

   

     String str2 = "String named str1";



Q - The use of the new operator is required for instantiation of objects of type StringBuffer: True
or False? If false, explain your answer.

A - True.

Q - Provide a code fragment that illustrates how to instantiate an empty StringBuffer object of a
default length and then use a version of the append() method to put some data into the object.

A - See code fragment below:

     StringBuffer str5 = new StringBuffer();//accept default initial length

     str5.append("StringBuffer named str5");//modify length as needed



Q - Without specifying any explicit numeric values, provide a code fragment that will instantiate an
empty StringBuffer object of the correct initial length to contain the string "StringBuffer named str6"
and then store that string in the object.

A - See the following code fragment:

     StringBuffer str6 = new StringBuffer("StringBuffer named str6".length());

     str6.append("StringBuffer named str6");




Q - Provide a code fragment consisting of a single statement showing how to use the Integer wrapper class to convert a string containing digits to an integer and store it in a variable of type int.

A - See code fragment below

     int num = new Integer("3625").intValue();

Q - Explain the difference between the capacity() method and the length() methods of the StringBuffer class.

A - The capacity() method returns the amount of space currently allocated for the StringBuffer object. The
length() method returns the amount of space used.

Q - The following is a valid code fragment: True or False? If false, explain why.

 StringBuffer str6 = new StringBuffer("StringBuffer named str6".length());
A - True.

Q - Which of the following code fragments is the most efficient, first or second?

 String str1 = "THIS STRING IS NAMED str1";
 String str1 = new String("THIS STRING IS NAMED str1");

A - The first code fragment is the most efficient.
  

System


Java provides the System class which provides a platform-dependent interface between your program and various system resources: True or False? If false, explain why.

A - False. Java provides the System class which provides a platform-independent interface between your program and those resources.

Q - You must instantiate an object of the System class in order to use it: True or False? If false, explain why.

A - False. You don't need to instantiate an object of the System class to use it, because all of its variables and methods are class variables and methods.

Q - The following code fragment can be used to instantiate an object of the System class: True or False? If false, explain why.

 System mySystemObject = new System();
  
A - False. You cannot instantiate an object of the System class. It is a final class, and all of its constructors are private.

Q - What is the purpose of the write() method of the PrintStream class?

A - The write() method is used to write bytes to the stream. You can use write() to write data which is not intended to be interpreted as text (such as bit-mapped graphics data).

Exceptions


Q - The exception-handling capability of Java makes it possible for you to monitor for exceptional conditions within your program, and to transfer control to special exception-handling code which you design. List five keywords that are used for this purpose.

A - try, throw, catch, finally, and throws

Q - All exceptions in Java are thrown by code that you write: True or False? If false, explain why.

A - False. There are situations where an exceptional condition automatically transfers control to special exception-handling code which you write (cases where you don't provide the code to throw the exception object).

Q - When an exceptional condition causes an exception to be thrown, that exception is an object derived, either directly, or indirectly from the class Exception: True or False? If false, explain why.
 A - False. When an exceptional condition causes an exception to be thrown, that exception is an object derived, either directly, or indirectly from the class Throwable.

Q - All exceptions other than those in the RuntimeException class must be either caught, or declared in a throws clause of any method that can throw them: True or False? If false, explain why.

A - True.

Q - What method of which class would you use to extract the message from an exception object?

A - The getMessage() method of the Throwable class.

Q - Normally, those exception handlers designed to handle exceptions closest to the root of the exception class hierarchy should be placed first in the list of exception handlers: True or False? If false, explain why.

A - False. The above statement has it backwards. Those handlers designed to handle exceptions furthermost from the root of the hierarchy tree should be placed first in the list of exception handlers.

Q - Explain why you should place exception handlers furthermost from the root of the exception hierarchy tree first in the list of exception handlers.

A - An exception hander designed to handle a specialized "leaf" object may be preempted by another handler whose exception object type is closer to the root of the exception hierarchy tree if the second exception handler appears earlier in the list of exception handlers.

Q - In addition to writing handlers for very specialized exception objects, the Java language allows you to write general exception handlers that handle multiple types of exceptions: True or False? If false, explain why.

A - True.

Q - Your exception handler can be written to handle any class that inherits from Throwable. If you write a handler for a node class (a class with no subclasses), you've written a specialized handler: it will only handle exceptions of that specific type. If you write a handler for a leaf class (a class with subclasses), you've written a general handler: it will handle any exception whose type is the node class or any of its subclasses. True or False? If false, explain why.

A - False. "Leaf" and "node" are reversed in the above statement. If you write a handler for a "leaf" class (a class with no subclasses), you've written a specialized handler: it will only handle exceptions of that specific type. If you write a handler for a "node" class (a class with subclasses), you've written a general handler: it will handle any exception whose type is the node class or any of its subclasses."

Q - Java's finally block provides a mechanism that allows your method to clean up after itself regardless of what happens within the try block. True or False? If false, explain why.

A - True.

Q - Explain how you would specify that a method throws one or more exceptions.

A - To specify that a method throws one or more exceptions, you add a throws clause to the method signature for the method. The throws clause is composed of the throws keyword followed by a comma-separated list of all the exceptions thrown by that method.

Q - Provide a code fragment that illustrates how you would specify that a method throws more than one exception.

A - See code fragment below.

 void myMethod() throws InterruptedException, MyException,
       HerException, UrException
  {
  //method body
  }
  
Q - What type of argument is required by the throw statement?

A - The throw statement requires a single argument, which must be an object derived either directly or indirectly
from the class Throwable.

Q - Some exception objects are automatically thrown by the system. It is also possible for you to define your own exception classes, and to cause objects of those classes to be thrown whenever an exception occurs. True or False? If false, explain why.

A - True.
  
=======

Threads


Q - What is the definition of multi-threaded programming according to Patrick Naughton?

A - According to The Java Handbook, by Patrick Naughton,

"Multi-threaded programming is a conceptual paradigm for programming where you divide programs into two or more processes which can be run in parallel."

Q - Multithreading refers to two or more programs executing, "apparently" concurrently, under control of the operating system. The programs need have no relationship with each other, other than the fact that you want to start and run them all concurrently. True or False? If false, explain why.

A - False. That is a description of multiprocessing, not multithreading. Multithreading refers to two or more tasks executing, "apparently" concurrently, within a single program.

Q - According to current terminology, the term blocked means that the thread is waiting for something to happen and is not consuming computer resources. True or False? If false, explain why.

A - True.

Q - What are the two ways to create threaded programs in Java?

A - In Java, there are two ways to create threaded programs:

     Implement the Runnable interface
     Extend the Thread class

Q - What two steps are required to spawn a thread in Java?

A - The two steps necessary to spawn a thread in Java are:

     instantiate an object of type Thread and  invoke its run() method.

Q - How do you start a thread actually running in Java?

A - Invoke the start() method on object of the Thread class or of a subclass of the Thread class.

Q - It is always possible to extend the Thread class in your Java applications and applets. True or False? If false, explain why.

A - False. Sometimes it is not possible to extend the Thread class, because you must extend some other class and Java does not support multiple inheritance.

Q - Although multithreaded programming in Java is possible, it is also possible to write Java programs that do not involve threads: True or False? If false, explain why.

A - False. The main method itself runs in a thread which is started by the interpreter.

Q - What is the name of the method that can be used to determine if a thread is alive?

A - The name of the method is isAlive().

Q - Once you start two or more threads running, unless you specify otherwise, they run synchronously and independently of one another: True or False? If false, explain why.

A - False. Once you start two or more threads running, unless you specify otherwise, they run asynchronously and independently of one another.

Q - The process of keeping one thread from corrupting the data while it is being processed by another thread is known as synchronization: True or False? If false, explain why.

A - True.

Q - Java allows you to specify the absolute priority of each thread: True or False? If false, explain why.

A - False. Java allows you to specify the priority of each thread relative to other threads but not on an absolute basis.

Q - Thread synchronization can be achieved using wait(), notify(), and notifyAll() which are methods of the Thread class: True or False? If false, explain why.

A - False. wait(), notify(), and notifyAll() are not methods of the Thread class, but rather are methods of the Object class.

Q - When you implement a threaded program, you will always override the _____________ method of the Thread class and build the functionality of your threaded program into that method. What is the name of the method?

A - The run() method.

Q - In a multithreaded program, you will start a thread running by invoking the __________ method on your Thread object which will in turn invoke the ___________ method. What are the names of the missing methods, and what are the required parameters for each method?

A - In a multithreaded program, you will start a thread running by invoking the start() method on your Thread object which will in turn invoke the run() method. Neither method takes any parameters.

Q - What do Campione and Walrath list as the four possible states of a thread?

A -
     New Thread
     Runnable
     Not Runnable
     Dead

Q - What methods can be invoked on a thread object which is in the state that Campione and Walrath refer to as a New Thread and what will happen if you invoke any other method on the thread?

A - When a thread is in this state, you can only start the thread or stop it. Calling any method other than start() or stop() will cause an IllegalThreadStateException.

Q - What, according to Campione and Walrath, will cause a thread to become Not Runnable?

A - a thread becomes Not Runnable when one of the following four events occurs:

     Someone invokes its sleep() method.
     Someone invokes its suspend() method.
     The thread uses its wait() method to wait on a condition variable.
     The thread is blocking on I/O.

Q1 - Three keywords are used in Java to specify access control. What are they?
A - The three keywords used to specify access control in Java are public, private, and protected.
Q2 - In Java, special access privileges are afforded to other members of the same package: True or False? If false, explain your answer.
A - True. In Java, special access privileges are afforded to other members of the same package.
Q3 - In Java, class variables are often used with the __________ keyword to create variables that act like constants.
A - The final keyword.
Q4 - In Java, the ___________ keyword is used to declare a class variable.
A - The static keyword.
Q5 - In Java, the ___________ keyword is used to declare a class method.
A - The static keyword.
Q6 - When you include a method in a Java class definition without use of static keyword, this will  result in objects of that class containing an instance method: True or False? If false, explain why.
A 7- True.
Q8 - Normally each object contains its own copy of each instance method: True or False?
A - False, multiple copies of the method do not normally exist in memory.
Q9- When you invoke an instance method using a specific object, if that method refers to instance variables of the class, that method is caused to refer to the specific instance variables of the specific object for which it was invoked: True or False? If false, explain why.
A - True.
Q10 - Instance methods are invoked in Java using the name of the object, the colon, and the name of  the method as shown below: True or False? If false, explain why.
     myObject:myInstanceMethod( )
A - False. Use the period or dot operator, not the colon.
Q11 - Instance methods have access to both instance variables and class variables in Java: True or False. If false, explain why.
A - True.
Q12 - Class methods have access to both instance variables and class variables in Java: True or False. If false, explain why.
A - False. Class method can only access other class members.
Q13 - What are the two most significant characteristics of class methods?
A - 1. Class methods can only access other class members. 2. Class methods can be accessed using only the name of the class. An object of the class is not required to access class methods.
Q14 - In Java, a class method can be invoked using the name of the class, the colon, and the name of  the method as shown below: True or False? If false, explain why.
     MyClass:myClassMethod()
A - False. You must use the period or dot operator, not the colon.
Q15 - What is meant by overloaded methods?
A - The term overloaded methods means that two or more methods may have the same name so long as they have different argument lists.
Q16 - If you overload a method name, the compiler determines at run time, on the basis of the arguments provided to the invocation of the method, which version of the method to call in that instance: True or False? If false, explain why.
A - False. The determination is made at compile time.
Q16 - A constructor is a special method which is used to construct an object. A constructor always has the same name as the class in which it is defined, and has no return type specified. True or False? If false, explain why.
A - True.
Q17 - Constructors may be overloaded, so a single class may have more than one constructor, all of which have the same name, but different argument lists: True or False. If false, explain why.
A - True
Q18 - What is the purpose of a parameterized constructor?
A - The purpose of a parameterized constructor is to initialize the instance variables of an object when the object is instantiated.
Q 19 - The same set of instance variables can often be initialized in more than one way using overloaded constructors: True or False? If false, explain why.
A - True.
Q20  - It is not necessary to provide a constructor in Java. True or False? If false, explain why.
A - True. .
Q 21 You can think of the default constructor as a constructor which doesn't take any parameters: True or False? If false, explain why.
A - True.
Q 22- In Java, if you provide any constructors, the default constructor is no longer provided automatically: True or False? If false, explain why.
A - True.
Q 23- In Java, if you need both a parameterized constructor and a constructor which doesn't take parameters (often called a default constructor), you must provide them both: True or False? If false,explain why.
A - True.

Q 24- In Java, you can instantiate objects in static memory at compile time, or you can use the new operator to request memory from the operating system at runtime and use the constructor to instantiate the object in that memory: True or False? If false, explain why.
A - False. In Java, objects can only be instantiated on the heap at runtime.
Q25 - Provide a code fragment consisting of a single statement that illustrates how the constructor is typically used in Java to declare, instantiate, and initialize an object. Assume a parameterized constructor with three parameters of type int.
A - MyClass myObject = new MyClass(1,2,3);
Q26 - Provide a code fragment consisting of a single statement that illustrates how the default constructor is typically used in Java to declare and instantiate an object.
A - MyClass myObject = new MyClass();
Q 27- What are the three actions performed by the following statement?
MyClass myObject = new MyClass(1,2,3);
A - This statement performs three actions in one.
     The object is declared by notifying the compiler of the name of the object.
     The object is instantiated by using the new operator to allocate memory space to contain the new object.
     The object is initialized by making a call to the constructor named MyClass.
Q 28- In Java, if you attempt to instantiate an object and the Java Virtual Machine cannot allocate the
requisite memory, the system will: ________________________________________.
A - Throw an OutOfMemoryError.
Q 29- The following is a valid method call: True or False. If false, explain why.  obj.myFunction(new myClassConstructor(1,2,3) );//Java version
A - True.
Q30 - In Java, when a method begins execution, all of the parameters are created as local automatic
variables: True or False? If false, explain why.
A - True.
Q31 - In the following statement, an object is instantiated and initialized and passed as a parameter to a
function. What will happen to that object when the function terminates?  obj.myFunction(new myClassConstructor(1,2,3) );//Java version
A - It will become eligible for garbage collection.
Q 32- In Java, you declare and implement a constructor just like you would implement any other method in your class, except that: _______________________________________________
A - you do not specify a return type and must not include a return statement.
Q33 - The name of the constructor must be the same as the name of the ___________________.
A - class.
Q 34- Usually in cases of inheritance, you will want the subclass to cause the constructor for the superclass to execute last to initialize those instance variables which derive from the superclass:True or False? If false, explain why.
A - False. You will want the subclass to cause the constructor for the superclass to execute first.
Q 35- Provide a code fragment that you would include at the beginning of your constructor for a subclass to cause the constructor for the superclass to be invoked prior to the execution of the body of the constructor.
A - super(optional parameters);
Q 36- Every object has a finalize method which is inherited from the class named ________________.
A - object.
Q 37- Before an object is reclaimed by the garbage collector, the _______________ method for the
object is called.
A - finalize
Q 38- In Java, the destructor is always called when an object goes out of scope: True or False? If false, explain why.
A - False. Java does not support the concept of a destructor.
=====
Q 39- The class at the top of the inheritance hierarchy is the Object class and this class is defined in the package named java.Object: True or False? If false, explain why.
A - False. The Object class is defined in the package named java.lang.
Q40 - We say that an object has state and behavior: True or False? If false, explain why.
A - True.
Q 41- In Java, a method can be defined as an empty method, normally indicating that it is intended to be overridden: True or False? If false, explain why.
A - True.
Q 42- Including an empty method in a class definition will make it impossible to instantiate an object of that class: True or False.
A - False.
Q 43- A subclass can invoke the constructor for the immediate superclass by causing the last line of of the subclass constructor to contain the keyword super followed by a parameter list as though calling a function named super() and the parameter list must match the method signature of the superclass constructor: True or False? If false, explain why.
A - False. This can only be accomplished by causing the first line of the constructor to contain the keyword super followed by a parameter list as though calling a function named super(). The parameter list must match the method signature of the superclass constructor.




Q 43 The equals() method is used to determine if two reference variables point to the same object: True or False? If false, explain why.
A- False. You can use the equals() method to compare two objects for equality. You can use the equality operator (==) to determine if two reference variables point to the same object.
Q 44- The equals() method is used to determine if two separate objects are of the same type and contain the same data. The method returns false if the objects are equal and true otherwise. True or False? If false, explain why.
A - False. The method returns true if the objects are equal and false otherwise.
Q 45 - The equals() method is defined in the Object class: True or False? If false, explain why.
A - True.
Q 46- Your classes can override the equals() method to make an appropriate comparison between two objects of a type that you define: True or False? If false, explain why.
A - True.
Q 47- You must override the equals() method to determine if two string objects contain the same data: True or False? If false, explain why.
A - False. The system already knows how to apply the equals() method to all of the standard classes and objects of which the compiler has knowledge. For example, you can already use the method to test two String objects or two array objects for equality.
Q 48- Given an object named obj1, provide a code fragment that shows how to obtain the name of the class from which obj1 was instantiated and the name of the superclass of that class.
A - See code fragment below:
     System.out.println("Name of class for obj1: "           + obj1.getClass().getName());

     System.out.println("Name of superclass for obj1: "          + obj1.getClass().getSuperclass());
Q 49- Given an object named obj2, provide a code fragment that shows how to use the newInstance() method to create a new object of the same type
A - See code fragment below:
         obj2 = obj1.getClass().newInstance();
Q 50- By overriding the getClass() method, you can use that method to determine the name of the class from which an object was instantiated: True or False? If false, explain why.
A - False. The getClass() method is a final method and cannot be overridden.
Q 51- You must use the new operator to instantiate an object of type Class: True or False? If false,explain why.
A - False. There is no public constructor for the class Class. Class objects are constructed automatically by the
Java Virtual Machine as classes are loaded and or by calls to the defineClass method in the class loader.
Q 52- The Class class provides a toString() method which can be used to convert all objects known to the compiler to some appropriate string representation. The actual string representation depends on the type of object: True or False? If false, explain why.
A - False. The Object class (not the Class class) provides a toString() method which can be used to convert all objects known to the compiler to some appropriate string representation. The actual string representation depends on the type of object.
Q 53- You can override the toString() method of the Class class to cause it to convert objects of your design to strings: True or False? If false, explain why.
A - False. The toString() method is a method of the Object class, not the Class class.
Q 54- By default, all classes in Java are either direct or indirect descendants of the Class class which is at the top of the inheritance hierarchy: True or False? If false, explain why.
A - False. By default, all classes in Java are either direct or indirect descendants of the Object class (not the Class class) which is at the top of the inheritance hierarchy.
=====
Q 55 - To a limited extent, the interface concept allows you to treat a number of objects, instantiated from different classes, as if they were all of the same type: True or False? If false, explain why.
A - True.
Q 56- At its simplest level, an interface definition has a name, and declares one or more methods: True or False? If false, explain why.
A - True.
Q57- In an interface definition, both the method signatures and the actual implementations (bodies) of the methods are provided: True or False? If false, explain why.
A - False. Only the method signatures are provided. The actual implementations (bodies) of the methods are not provided.
Q 58- An interface definition can contain only method declarations: True or False? If false, explain why.
A - False. In addition to method declarations, an interface can also declare constants. Nothing else may be included inside the body of an interface definition.
Q59 - If classes P, D, and Q all implement interface X, a reference variable for an object of class P, D, or Q could be assigned to a reference variable of type X: True or False? If false, explain why.
A - True.

Q 60- If classes P, D, and Q all implement interface X, then all of the methods declared in X must be exactly the same in classes P, D, and Q: True or False? If false, explain why.
A - False. The interface simply declares the signatures for methods. Classes that implement the interface are free to provide a body for those methods which best suits the needs of the class.
Q 61- If classes P, D, and Q all implement interface X a reference variable for an object of class P, D, or Q could be assigned to a reference variable of type X and that reference variable could be used to access all of the methods of the class (which are not excluded using public, private, or protected): True or False? If false, explain why.
A - False. If one or more of the classes P, D, and Q, define instance methods which are not declared in the interface X, then a variable of type X cannot be used to access those instance methods. Those methods can only be accessed using a reference variable of the class in which the method is defined. Reference variables of the type X can only be used to access methods declared in the interface X (or one of its superinterfaces).
Q 61 - The new operator must be used to instantiate an object which is of the type of an interface: True or False? If false, explain why.
A - False. Even though you can consider the interface name as a type for purposes of storing references to objects, you cannot instantiate an object of the interface type itself.
Q 63- One of the difficulties of implementing interfaces is the requirement to coordinate the definition of interface methods among the classes that implement the interface: True or False? If false, explain why.
A - False. In defining interface methods, each class defines the methods in a manner that is appropriate to its own class without concern for how it is defined in other classes.
Q 64- As with classes, multiple interface definitions can be combined into the same source file: True or False? If false, explain why.
A- False. The compiler requires interface definitions to be in separate files.
Q 65- List four ways in which interfaces are useful:
A - See the following list:
To a limited extent, the interface concept allows you to treat a number of objects, instantiated from  different classes, as if      they were all of the same type
     Capturing similarities between unrelated classes without forcing a class relationship
     Declaring methods that one or more classes are expected to implement
     Revealing an object's programming interface without revealing its class (objects such as these are called
     anonymous objects and can be useful when shipping a package of classes to other developers)
Q 66- A minimum interface declaration contains the Java keyword interface, the name of the interface, and the name of the interface that it extends: True or False? If false, explain why.
A - False. A minimum interface declaration contains the Java keyword interface and the name of the interface. There is no requirement to specify the name of the interface that it extends, because it may not extend another interface.
Q 67 - An interface can extend any number of other interfaces: True or False? If false, explain why.
A - True.
Q 68- Just like a class definition can extend any number of other classes, an interface can extend any number of other interfaces: True or False? If false, explain why.
A - False. A class can extend only one other class.
Q 69- An interface can extend any number of other interfaces but not more than one class: True or False? If false, explain why.
A - False. An interface cannot extend a class.
Q 70- An interface inherits all constants and methods from its superinterface: True or False? If false, explain why.
A - False. See reasons below:
An interface inherits all constants and methods from its superinterface unless:
     the interface hides a constant with another of the same name, or   redeclares a method with a new method declaration.
Q 71- The method declaration in an interface consists of the method signature followed by a pair of
empty curly braces: True or False? If false, explain why.
A - False. The method declaration is terminated by a semicolon and no body (no curly braces) is provided for the method.
Q 72- The keyword private is used to restrict access to the members of an interface only to classes within the same package: True or False? If false, explain why.
A - False. You may not use private in a member declaration in an interface.
Q 73- All methods declared in an interface are implicitly public and abstract: True or False? If false, explain why.
A - True.
Q 74- In addition to declaring methods, the body of the interface may also define constants. Constant values defined in an interface are implicitly public, static, and final: True or False? If false, explain why.
A - True.
Q 75- You use an interface by defining a class that extends the interface by name: True or False? If false, explain why.
A - False. You use an interface by defining a class that implements (not extends) the interface by name.



Q 76- When a class claims to implement an interface, it must provide a full definition for all the methods declared in the interface as well as all of the methods declared in all of the superinterfaces of that interface: True or False? If false, explain why.
A - True.
Q 77- A class can implement more than one interface by including several interface names in a comma-separated list of interface names, and by providing a full definition for all of the methods declared in all of the interfaces listed as well as all of the superinterfaces of those interfaces: True or False? If false, explain why.
A - True.
Q 78- Whenever a class implements an interface, it is allowed to define only those methods declared in the interface: True or False? If false, explain why.
A - False. Whenever a class implements an interface, the class must define all of the methods declared in the interface, but is also free to define other methods as well.
Q 79- The definition of an interface is a definition of a new reference data type. You can use interface names just about anywhere that you would use other type names, except that you cannot ____________________.
A - You cannot instantiate objects of the interface type.
Q 80- Explain in your own words the "bottom line" benefits of the use of an interface.
A - The interface makes it possible for a method in one class to invoke methods on objects of other classes,

without the requirement to know the true class of those objects, provided that those objects are all instantiated from classes that implement one or more specified interfaces. In other words, objects of classes that implement specified interfaces can be passed into methods of other objects as the generic type Object, and the methods of the other objects can invoke methods on the incoming objects by first casting them as the interface type.

No comments:

Post a Comment