java introduction questions and answers

Upload: mayank280488

Post on 13-Apr-2018

254 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 Java Introduction Questions and Answers

    1/107

    Java concepts

    Ramachandra Kamath A

    12/9/2011

    This documents covers all important concepts of core java and basic concept of JSP

  • 7/27/2019 Java Introduction Questions and Answers

    2/107

    2

    1. Introduction to Java 12

    What are different types of access modifiers in Java? 12

    What is the use of final keyword? 12

    What is use of synchronized keyword? 13

    What is volatile keyword? 13

    What is a transient variable? 13

    What is a strictfp modifier? 14

    What is a static variable? 14

    What is a static method? 15

    Why static methods cannot access non static variables or methods? 16

    What is static class ? 16

    What is throw keyword? 16

    What is use of throws keyword? 17

    2. Key Concepts in Java 17

    Why is main() method static? 17

    What is the difference between static methods and instance methods? 17

    Can static block throw exception? 17

    What is difference between abstract class and interface? 18

    Explain with example to describe when to use abstract class and interface? 18

    Does java support multiple interitance? Why? 19

    Can this keyword be assigned null value? 20

    What are the different types of references in java? 20

    How to change the heap size of a JVM? 20

    What is difference between instanceof and isInstance(Object obj)? 21

    Java supports pass by value or pass by reference? 21

    What is memory leak? 22

    What is the difference between equals() and ==? 22

    How to make sure that Childclass method actually overrides the method of the superclass? 23

    How to find the size of an object? 23

    Can an abstract class have a static method? 23

    Can an abstract class have a constructor? 24

    Why static methods cannot access non static variables or methods? 24

  • 7/27/2019 Java Introduction Questions and Answers

    3/107

    3

    What is difference between stringbuffer and stringbuilder? 24

    Consider a scenario in which the admin want to sure that if some one has written System.exit() at some part of

    application then before system shutdown all the resources should be released. How is it possible? 24

    What is the difference between final, finally and finalize() in Java? 25

    How does Java allocate stack and heap memory? 25

    Explain re-entrant, recursive and idempotent methods/functions? 25

    Can a private variable or method of a class can be accessed? 26

    What is difference between static block and the init block? Or Difference between Static {} and {} 26

    Why inner class can access only final variable? 26

    What is fully abstract class? 27

    What is dynamic binding and static binding? 27

    What is Java Reflection? 27

    When an obj is passed through a function , one can set the properties but cannot set a new memory location?

    28

    3. OOPS Concept 28

    What is polymorphism? 28

    What is inheritance? 29

    What is multiple inheritance and does java support? 30

    What is abstraction? 30

    What is encapsulation? 30

    What is Association? 30

    What is Aggregation? 31

    What is Composition? 31

    4. Collections Questions 31

    What is difference between ArrayList and vector? 31

    How can Arraylist be synchronized without using Vector? 31

    If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the

    basis of the employeeID of Employee class. What are the steps? 32

    What is difference between HashMap and HashTable? 32

    What are the classes implementing List interface? 32

    Which all classes implement Set interface? 33

    What is difference between List and a Set? 33

    What is difference between Arrays and ArrayList ? 33

  • 7/27/2019 Java Introduction Questions and Answers

    4/107

    4

    When to use ArrayList or LinkedList ? 34

    Consider a scenario. If an ArrayList has to be iterate to read data only, what are the possible ways and which

    is the fastest? 34

    Now another question with respect to above question is if accessing through iterator is slow then why do we

    need it and when to use it. 34

    Which design pattern Iterator follows? 34

    Why is it preferred to declare: List list = new ArrayList(); instead of ArrayList = new

    ArrayList(); 35

    What is difference between iterator access and index access? 35

    How to sort list in reverse order? 36

    Can a null element added to a Treeset or HashSet? 36

    How to sort list of strings - case insensitive? 36

    How to make a List (ArrayList,Vector,LinkedList) read only? 36

    What is ConcurrentHashMap? 36

    Which is faster to iterate LinkedHashSet or LinkedList? 36

    Which data structure HashSet implements 36

    Arrange in the order of speed - HashMap,HashTable, Collections.synchronizedMap,concurrentHashmap 37

    What is identityHashMap? 37

    What is WeakHashMap? 37

    5. Exceptions Questions 37

    What is an Exception? 37

    Exceptions are defined in which java package? 37

    How are the exceptions handled in java? 37

    Explain the exception hierarchy in java. 37

    What is Runtime Exception or unchecked exception? 38

    What is checked exception? 38

    What is difference between Error and Exception? 38

    What is difference between ClassNotFoundException and NoClassDefFoundError? 38

    What is throw keyword? 39

    What is use of throws keyword? 39

    What are the possible combination to write try, catch finally block? 40

    How to create custom Exception? 40

    When to make a custom checked Exception or custom unchecked Exception? 41

  • 7/27/2019 Java Introduction Questions and Answers

    5/107

    5

    What is StackOverflowError? 41

    Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown

    within its scope? 41

    Once the control switches to the catch block does it return back to the try block to execute the balance code?41

    Where is the clean up code like release of resources is put in try-catch-finally block and why? 41

    Is it valid to have a try block without catch or finally? 42

    Is it valid to place some code in between try the catch/finally block that follows it? 42

    What happens if the exception is never caught and throws down the method stack? 42

    How do you get the descriptive information about the Exception occurred during the program execution? 42

    Can you catch more than one exceptions in a single catch block? 42

    Why is not considered as a good practice to write a single catchall handler to catch all the exceptions? 43

    What is exception matching? 43

    What happens if the handlers for the most specific exceptions is placed above the more general exceptions

    handler? 43

    Does the order of the catch blocks matter if the Exceptions caught by them are not subtype or supertype of

    each other? 44

    What happens if a method does not throw an checked Exception directly but calls a method that does? What

    does 'Ducking' the exception mean? 44

    Is an empty catch block legal? 45

    Can a catch block throw the exception caught by itself? 46

    6. Threads Questions 46

    What is a Thread? 46

    What is difference between thread and process? 46

    What are the advantages or usage of threads? 47

    What are the two ways of creating thread? 48

    What are the different states of a thread's lifecycle? 48

    What is use of synchronized keyword? 49

    What is the difference when the synchronized keyword is applied to a static method or to a non static method?

    49

    What is a volatile keyword? 49

    What is the difference between yield() and sleep()? 50

    What is the difference between wait() and sleep()? 50

    What is difference between notify() and notfiyAll()? 50

    What happens if a start method is not invoked and the run method is directly invoked? 50

  • 7/27/2019 Java Introduction Questions and Answers

    6/107

    6

    What happens when start() is called? 50

    If code running is a thread creates a new thread what will be the initial priority of the newly created thread?

    51

    When jvm starts up, which thread will be started up first? 51

    What are the daemon threads? 51

    What all constructors are present in the Thread class? 51

    Can the variables or classes be Synchronized? 51

    How many locks does an object have? 51

    Can a class have both Synchronized and non-synchronized methods? 51

    If a class has a synchronised method and non-synchronised method, can multiple threads execute the non-

    synchronised methods? 52

    If a thread goes to sleep does it hold the lock? 52

    Can a thread hold multiple locks at the same time? 52

    Can a thread call multiple synchronized methods on the object of which it hold the lock? 52

    Can static methods be synchronized? 52

    Can two threads call two different static synchronized methods of the same class? 52

    Does a static synchronized method block a non-static synchronized method? 52

    Once a thread has been started can it be started again? 52

    When does deadlock occur and how to avoid it? 53

    What is a better way of creating multithreaded application? Extending Thread class or implementing

    Runnable? 53

    Can the start() method of the Thread class be overridden? If yes should it be overridden? 53

    What are the methods of the thread class used to schedule the threads? 53

    Which thread related methods are available in Object class? 53

    Which thread related methods are available in Thread class? 53

    List the methods which when called the thread does not release the locks held? 54

    List the methods which when called on the object the thread releases the locks held on that object? 54

    Does each thread has its own thread stack? 54

    What is thread starvation? 54

    What is threadLocal variable? 54

    7. Inner Class Questions 55

    What is an inner class? 55

    What are the different types of inner classes? 55

  • 7/27/2019 Java Introduction Questions and Answers

    7/107

    7

    What is static member class? 55

    What are non static inner classes? 56

    Does a static nested class have access to the enclosing class' non-static methods or instance variables? 58

    What are the advantages of Inner classes? 58

    What are disadvantages of using inner classes? 59

    What are different types of anonymous classes? 59

    If you compile a file containing inner class how many .class files are created and what are all of them

    accessible in usual way? 60

    How to access the inner class from code within the outer class? 60

    How to create an inner class instance from outside the outer class instance code? 61

    How to refer to the outer this i.e. outer classs current instance from inside the inner class? 61

    Which modifiers can be applied to the inner class? 61

    Can the method local inner class object access methods local variables? 62

    Can a method local inner class access the local final variables?Why? 62

    Which modifiers can be applied to the method local inner class? 62

    Can a local class declared inside a static method have access to the instance members of the outer class? 62

    Can a method which is not in the definition of the superclass of an anonymous class be invoked on that

    anonymous class reference? 62

    Can an anonymous class define method of its own? 63

    Can an anonymous class implement multiple interfaces directly? 63

    Can an anonymous class implement an interface and also extend a class at the same time? 63

    8. Serialization Questions 63

    What is Serialization? 63

    What is use of serialVersionUID? 64

    What is the need of Serialization? 64

    Other than Serialization what are the different approach to make object Serializable? 65

    Do we need to implement any method of Serializable interface to make an object serializable? 65

    What happens if the object to be serialized includes the references to other serializable objects? 65

    What happens if an object is serializable but it includes a reference to a non-serializable object? 65

    Are the static variables saved as the part of serialization? 66

    What is a transient variable? 66

    What will be the value of transient variable after de-serialization? 67

  • 7/27/2019 Java Introduction Questions and Answers

    8/107

    8

    Does the order in which the value of the transient variables and the state of the object using the

    defaultWriteObject() method are saved during serialization matter? 68

    How can one customize the Serialization process? or What is the purpose of implementing the writeObject()

    and readObject() method? 68

    If a class is serializable but its superclass in not , what will be the state of the instance variables inherited from

    super class after deserialization? 69

    To serialize an array or a collection all the members of it must be serializable. True /False? 70

    9. Immutable Class Questions 70

    What is an immutable class? 70

    How to create an immutable class? 71

    Immutable objects are automatically thread-safe true/false? 71

    Which classes in java are immutable? 71

    What are the advantages of immutability? 72

    10. Cloning questions 72

    What are different types of cloning in Java? 72

    What is Shallow copy? 72

    What is deep copy and how it can be acheived? 72

    What is difference between deep and shallow cloning? 74

    What are the characteristics of a shallow clone? 74

    What are the disadvantages of deep cloning? 74

    11. Garbage Collections Questions 74

    Which part of the memory is involved in Garbage Collection? Stack or Heap? 74

    What is responsiblity of Garbage Collector? 74

    Is garbage collector a dameon thread? 75

    Garbage Collector is controlled by whom? 75

    When does an object become eligible for garbage collection? 75

    What are the different ways to make an object eligible for Garbage Collection when it is no longer needed? 75

    Can the Garbage Collection be forced by any means? 77

    How can the Garbage Collection be requested? 77

    What is the purpose of overriding finalize() method? 77

    If an object becomes eligible for Garbage Collection and its finalize() method has been called and inside this

    method the object becomes accessible by a live thread of execution and is not garbage collected. Later at some

    point the same object becomes eligible for Garbage collection, will the finalize() method be called again? 77

  • 7/27/2019 Java Introduction Questions and Answers

    9/107

    9

    How many times does the garbage collector calls the finalize() method for an object? 77

    What 77

    What are different ways to call garbage collector? 77

    How to enable/disable call of finalize() method of exit of the application 77

    12. JSP questions 78

    What is a JSP? What is it used for? What do you understand by the term JSP translation phase or compilation

    phase? 78

    Explain the life cycle methods of a JSP? 78

    What are different type of scripting elements? 78

    What are the different scope values or what are the different scope values for "jsp:usebean"? 79

    What are the differences between static and a dynamic include? 79

    Is JSP variable declaration thread safe? 80

    Explain JSP URL mapping? What is URL hiding or protecting the JSP page? 80

    What are custom tags? Explain how to build custom tags? 80

    What is the difference between custom JSP tags and JavaBeans? 82

    What is a Expression? 82

    Difference between forward and sendRedirect? 82

    What are implicit objects? List them? 82

    How do I prevent the output of my JSP or Servlet pages from being cached by the browser? 83

    How to implement a thread-safe JSP page? What are the advantages and Disadvantages of using it? 83

    Why to use the HttpServlet Init method to perform expensive operations that need only be done once? 84

    Why is it not a good practice to create HttpSessions in JSPs by default? 84

    What are the standard actions available in JSP? 84

    13. JDBC questions and answers 84

    What are the steps involved in establishing a JDBC connection? 84

    How can you load the drivers? 84

    What will Class.forName do while loading drivers? 85

    How can you make the connection? 85

    How can you create JDBC statements and what are they? 85

    How can you retrieve data from the ResultSet? 85

    What are the different types of Statements? 86

    How can you use PreparedStatement? 86

  • 7/27/2019 Java Introduction Questions and Answers

    10/107

    10

    What does setAutoCommit do? 86

    How do you call a stored procedure from JDBC? 87

    How do I retrieve warnings? 87

    How can you move the cursor in scrollable result sets? 88

    Whats the difference between TYPE_SCROLL_INSENSITIVE,and TYPE_SCROLL_SENSITIVE? 88

    How to Make Updates to Updatable Result Sets? 89

    14. Reading XML in JAVA 90

    15. Reading properties file in JAVA 91

    16. DataSource in JAVA 92

    17. StringTokenizer in JAVA 92

    18. Collection in details 92

    19. Collection Subtypes 93

    20. Adding and Removing Elements 94

    21. Checking if a Collection Contains a Certain Element 96

    22. Collection Size 96

    23. Iterating a Collection 96

    24. List Implementations 97

    25. Adding and Accessing Elements 97

    26. Removing Elements 99

    27. Generic Lists 99

    28. Set Implementations 99

    29. Adding and Accessing Elements 100

    30. Removing Elements 101

    31. Generic Sets 101

    32. Map Implementations 102

    33. Adding and Accessing Elements 102

  • 7/27/2019 Java Introduction Questions and Answers

    11/107

    11

    34. Removing Elements 103

    35. Generic Maps 103

    36. Array list 104

    37. Hash Map 105

  • 7/27/2019 Java Introduction Questions and Answers

    12/107

    12

    1. Introduction to Java

    What are different types of access modifiers in Java?

    Ans) There are four different types of modifiers:

    Modifer Accessible in the same package Accessible in different package

    Private No No

    Protected Yes Yes, only if the class extendsthe main class

    Default Yes No

    Public Yes Yes

    What is the use of final keyword?

    Ans) The final keyword can be assigned to

    1. Class level variable2. method3. class4. Objects

    If a final is assigned to a variable, the variable behaves as a constant. It means that the valueof variable once set cannot be changed.

    final int i=1;i =5; // error

    If a final is assigned to a method then it cannot be overridden in its child class.

    class Parent {

    final void print(){

    System.out.println(Inside);

    }

    }

    class Child extends Parent{

    public final void print(){ // error cannot override final method

  • 7/27/2019 Java Introduction Questions and Answers

    13/107

    13

    System.out.println(Inside);}

    }

    If a class is made as final, then no other class can extend it and make it as parent class. E.g.String Class.

    Final objects are instantiated only once. i.e

    final Map map = new HashMap();

    map.put(key,value);

    map = new HashMap(); // error

    What is use of synchronized keyword?

    Ans) This keyword is used to prevent concurrency. Synchronized keyword can be appliedto static/non-static methods or a block of code. Only one thread at a time can accesssynchronized methods and if there are multiple threads trying to access the same methodthen other threads have to wait for the execution of method by one thread. Synchronizedkeyword provides a lock on the object and thus prevents race condition. E.g.

    public void synchronized method(){}public void synchronized staticmethod(){}public void myMethod(){

    synchronized (this){ // synchronized keyword on block of code}

    }

    What is volatile keyword?

    Ans) In general each thread has its own copy of variable, such that one thread is notconcerned with the value of same variable in the other thread. But sometime this may notbe the case. Consider a scenario in which the count variable is holding the number of times

    a method is called for a given class irrespective of any thread calling, in this caseirrespective of thread access the count has to be increased. In this case the count variable isdeclared as volatile. The copy of volatile variable is stored in the main memory, so everytime a thread access the variable even for reading purpose the local copy is updated eachtime from the main memory. The volatile variable also have performance issues.

    What is a transient variable?

  • 7/27/2019 Java Introduction Questions and Answers

    14/107

    14

    Ans) If some of the properties of a class are not required to be serialized then the varaiblesare marked as transient. When an object is deserialized the transient variables retains thedefault value depending on the type of variable declared and hence lost its original value.

    What is a strictfp modifier?

    Ans) Strictfp is used with variable only . It is used to restrict floating point calculations ( fp )to ensure portability ( platform Independent ). When this modifier is specified, the JVMadheres to the Java specifications ( IEEE-754 floating-point specification ) and returns theconsistent value independent of the platform. That is, if you want the answers from yourcode (which uses floating point values) to be consistent in all platforms, then you need tospecify the strictfp modifier.

    What is a static variable?

    Ans) Static keyword can be used with the variables and methods but not with the class but

    there are static class. Anything declared as static is related to class and not objects.

    Static variable: Multiples objects of a class shares the same instance of a staticvariable.Consider the example:

    public class Counter{

    private static int count=0;

    private int nonStaticcount=0;

    public void incrementCounter(){

    count++;

    nonStaticcount++;

    }

    public int getCount(){

    return count;

    }

    public int getNonStaticcount(){

    return nonStaticcount;

    }

  • 7/27/2019 Java Introduction Questions and Answers

    15/107

    15

    public static void main(String args[]){

    Counter countObj1 = new Counter();

    Counter countObj2 = new Counter();

    countObj1.incrementCounter();

    countObj1.incrementCounter();

    System.out.println("Static count for Obj1: "+countObj1.getCount());

    System.out.println("NonStatic count for Obj1: "+countObj1.getNonStaticcount());

    System.out.println("Static count for Obj2: "+countObj2.getCount())

    System.out.println("NonStatic count for Obj2: "+countObj2.getNonStaticcount())

    }

    Output

    Static count for Obj1: 2

    NonStatic count for Obj1: 2

    Static count for Obj2: 2

    NonStatic count for Obj2: 0

    In the above program obj1 and obj2 share the same instance of static variable count henceif the value is incremented by one object , the incremented value will be reflected acrossthe other objects.

    What is a static method?

    Ans)A method defined as static is called static method. A static method can be accessedwithout creating the objects. Just by using the Class name the method can be accessed.

    Static method can only access static variables and not local or global non-static variables.For eg:

    public class Test{public static void printMe(){System.out.println("Hello World");}

  • 7/27/2019 Java Introduction Questions and Answers

    16/107

    16

    }public class MainClass{public static void main(String args[]){Test.printMe()

    }}

    OutPut:Hello World

    Also static method can call only static methods and not non static methods. But non-staticmethods can call static mehtods.

    Why static methods cannot access non static variables or methods?

    Ans) A static method cannot access non static variables or methods because static methods

    doesnt need the object to be accessed. So if a static method has non static variables or nonstatic methods which has instantiated variables they will no be intialized since the object isnot created and this could result in an error.

    What is static class ?

    Ans) A class cannot be declared static. But a class can be said a static class if all thevariables and methods of the class are static and the constructor is private. Making theconstructor private will prevent the class to be instantiated. So the only possibility toaccess is using Class name only

    What is throw keyword?

    Ans) Throw keyword is used to throw the exception manually. It is mainly used when theprogram fails to satisfy the given condition and it wants to warn the application.Theexception thrown should be subclass of Throwable.

    public void parent(){try{child();}catch(MyCustomException e){ }}

    public void child{String iAmMandatory=null;if(iAmMandatory == null){throw (new MyCustomException("Throwing exception using throw keyword");}}

  • 7/27/2019 Java Introduction Questions and Answers

    17/107

    17

    What is use of throws keyword?

    Ans) If the function is not capable of handling the exception then it can ask the callingmethod to handle it by simply putting the throws clauseat the function declaration.

    public void parent(){try{child();}catch(MyCustomException e){ }}

    public void child throws MyCustomException{//put some logic so that the exception occurs.}

    2. Key Concepts in Java

    Why is main()method static?

    Ans) To access the static method the object of the class is not needed. The method can beaccess directly with the help of ClassName. So when a program is started the jvm search forthe class with main method and calls it without creating an object of the class.

    What is the difference between staticmethodsand instancemethods?

    Ans) instance method belongs to the instance of a class therefore it requires an instancebefore it can be invoked, whereas static method belongs to the class itself and not to anyclass instance so it doesnt need an instance to be invoked.Instance methods use dynamic (late) binding, whereas static methods use static (early)binding.When the JVM invokes a class instance method, it selects the method to invoke based on thetype of the object reference, which is always known at run-time. On the other hand, whenthe JVM invokes a static method, it selects the method to invoke based on the actual class ofthe object, which may only be known at compile time.

    Can static block throw exception?

    Ans) Yes, static block can throw only Runtime exception or can use a try-catch block tocatch checked exception.Typically scenario will be if JDBC connection is created in static block and it fails thenexception can be caught, logged and application can exit. If System.exit() is not done, thenapplication may continue and next time if the class is referred JVM will throwNoClassDefFounderror since the class was not loaded by the Classloader.

  • 7/27/2019 Java Introduction Questions and Answers

    18/107

    18

    What is difference between abstract class and interface?

    Ans) 1) A class is called abstractwhen it contains at least one abstract method. It can alsocontain n numbers of concrete method.Interfacecan contain only abstract( nonimplemented) methods.

    2) The abstract classcan have public,private,protect or default variables and alsoconstants. In interfacethe variable is by defaultpublic final. In nutshell the interfacedoesnt have any variables it only has constants.3) A class can extend only one abstract classbut a class can implement multipleinterfaces.4) If an interface is implemented its compulsory to implement all of its methods but if anabstract class is extended its not compulsory to implement all methods. 5) The problemwith an interface is, if you want to add a new feature (method) in its contract, then youMUST implement those method in all of the classes which implement that interface.However, in the case of an abstract class, the method can be simply implemented in theabstract class and the same can be called by its subclass.

    Explain with example to describe when to use abstract class and interface?

    Ans) Consider a scenario where all Cars will have 4 tyres and other features can bedifferent.In this case any subclass of Car has to have 4 tyres. This is a case where abstract class willbe used and a default implementaion for tyres will be provided.

    public abstract class Car{

    public abstract String getCarName();

    public final int getNoOfTyres(){

    return 4;

    }

    }

    Consider a scenario where Cars can have any number of tyres and other features can alsobe different. In this case interface will be created.

    public interface Car{

    public abstract String getCarName();

    public abstract int getNoOfTyres();

    }

  • 7/27/2019 Java Introduction Questions and Answers

    19/107

    19

    Does java support multiple interitance? Why?

    Ans) Java doesnt support multiple inheritance but it provide a way through which it canenact it.Consider the scenario is C++

    Class A{

    public void add(){

    // some text

    }

    }

    Class B{

    public void add(){

    // some text

    }

    }

    Class C extends A,B{

    public static void main(String arg[]){

    C objC = new C();

    objC.add(); // problem, compiler gets confused and cant

    decide to call Class A or B method.}

    This problem is called Diamond problem.

    This problem in java is taken care with the use of interfacesIn Java similar problem would look like:

    interface A{

    add();

    }

    interface B{

    add();

    }

    class C implements A,B{

  • 7/27/2019 Java Introduction Questions and Answers

    20/107

    20

    add(){

    // doesnt matter which interface it belong to

    }

    }

    Can thiskeyword be assigned null value?

    Ans) No

    What are the different types of referencesin java?

    Ans) Java has a more expressive system of reference than most other garbage-collectedprogramming languages, which allows for special behavior for garbage collection. A normalreference in Java is known as a strong reference. The java.lang.ref package defines threeother types of referencessoft, weak, andphantomreferences. Each type of reference isdesigned for a specific use.

    A SoftReferencecan be used to implement a cache. An object that is not reachable by astrong reference (that is, not strongly reachable), but is referenced by a soft reference iscalled softly reachable. A softly reachable object may be garbage collected at the discretionof the garbage collector. This generally means that softly reachable objects will only begarbage collected when free memory is low, but again, it is at the discretion of the garbagecollector. Semantically, a soft reference means "keep this object unless the memory isneeded."

    A WeakReferenceis used to implement weak maps. An object that is not strongly or softlyreachable, but is referenced by a weak reference is called weakly reachable. A weakly

    reachable object will be garbage collected during the next collection cycle. This behavior isused in the class java.util.WeakHashMap. A weak map allows the programmer to putkey/value pairs in the map and not worry about the objects taking up memory when thekey is no longer reachable anywhere else. Another possible application of weak referencesis the string intern pool. Semantically, a weak reference means "get rid of this object whennothing else references it."

    A PhantomReferenceis used to reference objects that have been marked for garbagecollection and have been finalized, but have not yet been reclaimed. An object that is notstrongly, softly or weakly reachable, but is referenced by a phantom reference is called

    phantom reachable. This allows for more flexible cleanup than is possible with thefinalization mechanism alone. Semantically, a phantom reference means "this object is nolonger needed and has been finalized in preparation for being collected."

    How to change the heap size of a JVM?

  • 7/27/2019 Java Introduction Questions and Answers

    21/107

    21

    Ans) The old generation's default heap size can be overridden by using the -Xms and -Xmxswitches to specify the initial and maximum sizes respectively:java -Xms -Xmx programFor example:java -Xms64m -Xmx128m program

    What is difference between instanceof and isInstance(Object obj)?

    Ans) Differences are as follows:

    1) instanceof is a reserved word of Java, but isInstance(Object obj) is a method ofjava.lang.Class.

    if (obj instanceof MyType) {...}else if (MyType.class.isInstance(obj)) {

    ...}

    2) instanceof is used of identify whether the object is type of a particular class or itssubclass but isInstance(obj) is used to identify object of a particular class.

    Java supports pass by value or pass by reference?

    Ans) Java supports only pass by value. The arguments passed as a parameter to a method ismainly primitive data types or objects. For the data type the actual value is passed.Java passes the references by value just like any other parameter. This means the

    references passed to the method are actually copies of the original references.Java copiesand passes the reference by value, not the object. Thus, method manipulation will alter theobjects, since the references point to the original objects.Consider the example:

    public void tricky(Point arg1, Point arg2)

    {

    arg1.x = 100;

    arg1.y = 100;

    Point temp = arg1;

    arg1 = arg2;

    arg2 = temp;

    }

    public static void main(String [] args)

    {

    Point pnt1 = new Point(0,0);

    Point pnt2 = new Point(0,0);

    System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);

    System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);

  • 7/27/2019 Java Introduction Questions and Answers

    22/107

    22

    System.out.println(" ");

    tricky(pnt1,pnt2);

    System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);

    System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);

    }

    OutPut:

    X: 0 Y: 0

    X: 0 Y: 0

    X: 100 Y: 100

    X: 0 Y: 0

    The method successfully alters the value of pnt1, even though it is passed by value;however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main()method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 andpnt2 to the tricky() method, Java passes the references by value just like any other

    parameter. This means the references passed to the method are actually copies of theoriginal references.

    What is memory leak?

    Ans) A memory leak is where an unreferenced object that will never be used again stillhangs around in memory and doesnt get garbage collected.

    What is the difference between equals() and ==?

    Ans) == operator is used to compare the references of the objects.public bollean equals(Object o)is the method provided by the Object class. The defaultimplementation uses == operator to compare two objects.But since the method can be overriden like for String class. equals() method can be used tocompare the values of two objects.

    String str1 = "MyName";

    String str2 = "MyName";

    String str3 = str2;

    if(str1 == str2){

    System.out.println("Objects are equal")}else{

    System.out.println("Objects are not equal")

    }

    if(str1.equals(str2)){

    System.out.println("Objects are equal")

    }else{

  • 7/27/2019 Java Introduction Questions and Answers

    23/107

    23

    System.out.println("Objects are not equal")

    }

    Output:

    Objects are not equalObjects are equal

    String str2 = "MyName";

    String str3 = str2;

    if(str2 == str3){

    System.out.println("Objects are equal")

    }else{

    System.out.println("Objects are not equal")

    }

    if(str3.equals(str2)){

    System.out.println("Objects are equal")

    }else{

    System.out.println("Objects are not equal")

    }

    OutPut:

    Objects are equal

    Objects are equal

    How to make sure that Childclass method actually overrides the method of thesuperclass?

    Ans) The @Override annotation can be added to the javadoc for the new method. If youaccidently miss an argument or capitalize the method name wrong, the compiler willgenerate a compile-time error.

    How to find the size of an object?

    Ans)The heap size of an object can be found using -

    Runtime.totalMemory()-Runtime.freeMemory() .

    Can an abstract class have a static method?

  • 7/27/2019 Java Introduction Questions and Answers

    24/107

    24

    Ans) Yes an abstract class have a static method and it can be accessed by any otherclass(even not a concrete class).

    Can an abstract class have a constructor?

    Ans) Yes an abstract class have a default and parameterized constructors.

    Why static methods cannot access non static variables or methods?

    Ans) A static method cannot access non static variables or methods because static methodsdoesnt need the object to be accessed. So if a static method has non static variables or nonstatic methods which has instantiated variables they will no be intialized since the object isnot created and this could result in an error.

    What is difference between stringbuffer and stringbuilder?

    Ans) The only difference between StringBuffer and StringBuilder is that StringBuilder isunsynchronized whereas StringBuffer is synchronized. So when the application needs to berun only in a single thread then it is better to use StringBuilder. StringBuilder is moreefficient than StringBuffer.

    Criteria to choose among StringBuffer and StringBuilder

    1)If your text can change and will only be accessed from a single thread, use a StringBuilder2)because StringBuilder is unsynchronized.

    If your text can changes, and will be accessed from multiple threads, use a StringBuffer

    because StringBuffer is synchronous.

    Consider a scenario in which the admin want to sure that if some one has written

    System.exit() at some part of application then before system shutdown all the

    resources should be released. How is it possible?

    Ans) This is possible using Runtime.getRuntime().addShutdownHook(Thread hook).

    Straight from Java Spec:This method registers a new virtual-machine shutdown hook.

    The Java virtual machine shuts down in response to two kinds of events:

    1. The program exits normally, when the last non-daemon thread exits or when theexit (equivalently, System.exit) method is invoked, or2. The virtual machine is terminated in response to a user interrupt, such as typing^C, or a system-wide event, such as user logoff or system shutdown.

  • 7/27/2019 Java Introduction Questions and Answers

    25/107

    25

    A shutdown hook is simply an initialized but unstarted thread. When the virtual machinebegins its shutdown sequence it will start all registered shutdown hooks in someunspecified order and let them run concurrently. When all the hooks have finished it willthen run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtualmachine will halt. Note that daemon threads will continue to run during the shutdown

    sequence, as will non-daemon threads if shutdown was initiated by invoking the exitmethod.Once the shutdown sequence has begun it can be stopped only by invoking the halt method,which forcibly terminates the virtual machine.

    What is the difference between final, finally and finalize() in Java?

    Ans)final- constant declaration. A final variable act as constant, a final class is immutableand a final method cannot be ovrriden.

    finally - handles exception. The finally block is optional and provides a mechanism to

    clean up regardless of what happens within the try block (except System.exit(0) call).Use the finally block to close files or to release other system resources like databaseconnections, statements etc.

    finalize()- method helps in garbage collection. A method that is invoked before anobject is discarded by the garbage collector, allowing it to clean up its state. Should notbe used to release non-memory resources like file handles, sockets, databaseconnections etc because Java has only a finite number of these resources and you do notknow when the garbage collection is going to kick in to release these non-memoryresources through the finalize() method.

    How does Java allocate stack and heap memory?

    Ans) Each time an object is created in Java it goes into the area of memory known asheap. The primitive variables like int and double are allocated in thestack, if they arelocal method variables and in the heapif they are member variables (i.e. fields of aclass). In Java methods local variables are pushed intostackwhen a method is invokedand stack pointer is decremented when a method call is completed.In a multi-threaded application each thread will have its own stack but will share thesame heap. This is why care should be taken in your code to avoid any concurrentaccess issues in the heap space. The stack is threadsafe (each thread will have its ownstack) but the heap is not threadsafe unless guarded with synchronisation through yourcode.

    Explain re-entrant, recursive and idempotent methods/functions?

    Ans) A method in stack is re-entrantallowing multiple concurrent invocations that donot interfere with each other.A function is recursiveif it calls itself. Given enough stack space, recursive method callsare perfectly valid in Java though it is tough to debug. Recursive functions are useful inremoving iterations from many sorts of algorithms.Allrecursive functions are re-entrant

  • 7/27/2019 Java Introduction Questions and Answers

    26/107

    26

    but not all re-entrant functions are recursive.Idempotent methods are methods, whichare written in such a way that repeated calls to the same method with the samearguments yield same results. For example clustered EJBs, which are written withidempotent methods, can automatically recover from a server failure as long as it canreach another server.

    Can a private variable or method of a class can be accessed?

    Ans) Yes its possible using reflection.

    What is difference between static block and the init block?

    Or

    Difference between

    Static {} and {}

    Ans) The static block is loaded when the class is loaded by the JVM for the 1st time only

    whereas init {} block is loaded every time class is loaded. Also first the static block is loadedthen the init block.

    public class LoadingBlocks {

    static{System.out.println("Inside static");}

    {System.out.println("Inside init");

    }public static void main(String args[]){new LoadingBlocks();new LoadingBlocks();new LoadingBlocks();}

    }

    Output:

    Inside static

    Inside initInside initInside init

    Why inner class can access only final variable?

    Ans) Local classes can most definitely reference instance variables. The reason they cannotreference non final local variables is because the local class instance can remain in memory

  • 7/27/2019 Java Introduction Questions and Answers

    27/107

    27

    after the method returns. When the method returns the local variables go out of scope, so acopy of them is needed. If the variables weren't final then the copy of the variable in themethod could change, while the copy in the local class didn't, so they'd be out of synch.Anonymous inner classes require final variables because of the way they are implementedin Java. An anonymous inner class (AIC) uses local variables by creating a private instance

    field which holds a copy of the value of the local variable. The inner class isn't actuallyusing the local variable, but a copy. It should be fairly obvious at this point that a "BadThing" can happen if either the original value or the copied value changes; there will besome unexpected data synchronization problems. In order to prevent this kind of problem,Java requires you to mark local variables that will be used by the AIC as final (i.e.,unchangeable). This guarantees that the inner class' copies of local variables will alwaysmatch the actual values.

    What is fully abstract class?

    Ans) An abstract class which has all methods as abstract and all fields are public static final.

    What is dynamic binding and static binding?

    Ans) Method invocationThe Java programming language provides two basic kinds of methods: instancemethods and class (or static) methods. The difference are:1. Instance methods require an instance before they can be invoked, whereas classmethods do not.2. Instance methods use dynamic (late) binding, whereas class methods usestatic (early)binding.When the Java virtual machine invokes a class method, it selects the method to invoke

    based on the type of the object reference, which is always known at compile-time. Onthe other hand, when the virtual machine invokes an instance method, it selects themethod to invoke based on the actual class of the object, which may only be known atrun time.

    What is Java Reflection?

    Ans)Reflection is commonly used by programs which require the ability to examine ormodify the runtime behavior of applications running in the Java virtual machine.Drawbacks of Reflection:Reflection is powerful, but should not be used indiscriminately.If it is possible to perform an operation without using reflection, then it is preferable to

    avoid using it. The following concerns should be kept in mind when accessing code viareflection.Performance Overhead:Because reflection involves types that are dynamically resolved,certain Java virtual machine optimizations can not be performed. Consequently,reflective operations have slower performance than their non-reflective counterparts,and should be avoided in sections of code which are called frequently in performance-sensitive applications.

    Security Restrictions:Reflection requires a runtime permission which may not be

  • 7/27/2019 Java Introduction Questions and Answers

    28/107

    28

    present when running under a security manager. This is in an important considerationfor code which has to run in a restricted security context, such as in an Applet.Exposure of Internals:Since reflection allows code to perform operations that would beillegal in non-reflective code, such as accessing private fields and methods, the use ofreflection can result in unexpected side-effects, which may render code dysfunctional

    and may destroy portability. Reflective code breaks abstractions and therefore maychange behavior with upgrades of the platform.

    When an obj is passed through a function , one can set the properties but cannot set a

    new memory location?

    Ans) It is because when u pass an object the address value is passed and stored in somenew address . like if address 1234 is passed , it is stored in 4567 location. So if u change inthe value of an object it will take the address from 4567 and do 1234.setXXX(). If u set theobject to null it will set 4567=null.

    3. OOPS Concept

    What is polymorphism?

    Ans) Polymorphismgives us the ultimate flexibility in extensibility. The abiltiy to definemore than one function with the same name is called Polymorphism. In java,c++ there aretwo type of polymorphism: compile time polymorphism (overloading) and runtimepolymorphism (overriding).

    When you override methods, JVM determines the proper methods to call at the programs

    run time, not at the compile time. Overriding occurs when a class method has the samename and signature as a method in parent class.

    Overloading occurs when several methods have same names with

    Overloading is determined at the compile time.Different method signature and different number or type of parameters.Same method signature but different number of parameters.Same method signature and same number of parameters but of different type

    Example of Overloading

    int add(int a,int b)float add(float a,int b)float add(int a ,float b)void add(float a)int add(int a)void add(int a) //error conflict with the method int add(int a)

    Example: Overloading

  • 7/27/2019 Java Introduction Questions and Answers

    29/107

    29

    Class BookDetails{String title;String publisher;float price;

    setBook(String title){}setBook(String title, String publisher){}setBook(String title, String publisher,float price){}

    }

    Example: Overriding

    class BookDetails{String title;

    setBook(String title){ }

    }

    class ScienceBook extends BookDetails{

    setBook(String title){} //overriding

    setBook(String title, String publisher,float price){ } //overloading

    }

    What is inheritance?

    Ans) Inheritance is the property which allows a Child class to inherit some properties fromits parent class. In Java this is achieved by using extends keyword. Only properties withaccess modifier public and protected can be accessed in child class.

    public class Parent{

    public String parentName;public int parentage;public String familyName;}

    public class Child extends Parent{

  • 7/27/2019 Java Introduction Questions and Answers

    30/107

    30

    public String childName;public int childAge;

    public void printMyName(){System.out.println( My name is + chidName+ +familyName)

    }

    }

    In above example the child has inherit its family name from the parent class just byinheriting the class.

    What is multiple inheritance and does java support?

    Ans) If a child class inherits the property from multiple classes is known as multipleinheritance.

    Java does not allow to extend multiple classes but to overcome this problem it allows toimplement multiple Interfaces.

    What is abstraction?

    Ans) Abstraction is way of converting real world objects in terms of class. For examplecreating a class Vehicle and injecting properties into it. E.g

    public class Vehicle {

    public String colour;

    public String model;}

    What is encapsulation?

    Ans) The encapsulation is achieved by combining the methods and attribute into a class.The class acts like a container encapsulating the properties. The users are exposed mainlypublic methods.The idea behind is to hide how thinigs work and just exposing the requestsa user can do.

    What is Association?

    Ans) Association is arelationship between two classes. In this relationship the object ofone instance perform an action on behalf of the other class. The typical behaviour can beinvoking the method of other class and using the member of the other class.

    public class MyMainClass{

    public void init(){

  • 7/27/2019 Java Introduction Questions and Answers

    31/107

    31

    new OtherClass.init();

    }

    }

    What is Aggregation?

    Ans) Aggregation has arelationship between two classes. In this relationship the object ofone class is a member of the other class. Aggregation always insists for a direction.

    public class MyMainClass{

    OtherClass otherClassObj = new OtherClass();

    }

    What is Composition?

    Ans) Composition is a special type of aggregation relationship with a difference that its thecompulsion for the OtherClassobject (in previous example) to exist for the existence ofMyMainClass.

    4. Collections Questions

    What is difference between ArrayList and vector?

    Ans: )

    1) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vectorclass each method like add(), get(int i) is surrounded with a synchronized block and thusmaking Vector class thread-safe.

    2) Data growth - Internally, both the ArrayList and Vector hold onto their contents using anArray. When an element is inserted into an ArrayList or a Vector, the object will need toexpand its internal array if it runs out of room. A Vector defaults to doubling the size of itsarray, while the ArrayList increases its array size by 50 percent.

    How can Arraylist be synchronized without using Vector?

    Ans) Arraylist can be synchronized using:

    Collection.synchronizedList(List list)

    Other collections can be synchronized:

  • 7/27/2019 Java Introduction Questions and Answers

    32/107

    32

    Collection.synchronizedMap(Map map)

    Collection.synchronizedCollection(Collection c)

    If an Employee class is present and its objects are added in an arrayList. Now I want

    the list to be sorted on the basis of the employeeID of Employee class. What are thesteps?

    Ans) 1) Implement Comparable interface for the Employee class and override thecompareTo(Object obj) method in which compare the employeeID

    2) Now call Collections.sort() method and pass list as an argument.

    Now consider that Employee class is a jar file.

    1) Since Comparable interface cannot be implemented, create Comparator and override the

    compare(Object obj, Object obj1) method .

    2) Call Collections.sort() on the list and pass comparator as an argument.

    What is difference between HashMap and HashTable?

    Ans) Both collections implements Map. Both collections store value as key-value pairs. Thekey differences between the two are

    1. Hashmap is not synchronized in nature but hshtable is.

    2. Another difference is that iterator in the HashMap is fail-safe while the enumerator forthe Hashtable isn't.Fail-safe- if the Hashtable is structurally modified at any time after the iterator iscreated, in any way except through the iterator's own remove method, the iterator willthrow a ConcurrentModificationException?

    3. HashMap permits null values and only one null key, while Hashtable doesn't allow key orvalue as null.

    What are the classes implementing List interface?

    Ans)There are three classes that implement List interface:1)ArrayList: It is a resizable array implementation. The size of the ArrayList can beincreased dynamically also operations like add,remove and get can be formed once theobject is created. It also ensures that the data is retrieved in the manner it was stored. TheArrayList is not thread-safe.

    2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around

  • 7/27/2019 Java Introduction Questions and Answers

    33/107

    33

    a synchronized block.

    3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First InFirst Out) operation for add operation. It is faster if than ArrayList if it performs insertionand deletion of elements from the middle of a list.

    Which all classes implement Set interface?

    Ans) A Set is a collection that contains no duplicate elements. More formally, sets containno pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.HashSet,SortedSet and TreeSetare the commnly used class which implements Setinterface.

    SortedSet- It is an interface which extends Set. A the name suggest , the interface allowsthe data to be iterated in the ascending order or sorted on the basis of Comparator orComparable interface. All elements inserted into the interface must implement Comparable

    or Comparator interface.

    TreeSet- It is the implementation of SortedSet interface.This implementation providesguaranteed log(n) time cost for the basic operations (add, remove and contains). The classis not synchronized.

    HashSet:This class implements the Set interface, backed by a hash table (actually aHashMap instance). It makes no guarantees as to the iteration order of the set; inparticular, it does not guarantee that the order will remain constant over time. This classpermits the null element. This class offers constant time performance for the basicoperations (add, remove, contains and size), assuming the hash function disperses the

    elements properly among the buckets

    What is difference between List and a Set?

    Ans)1) List can contain duplicate values but Set doesnt allow. Set allows only to uniqueelements.2) List allows retrieval of data to be in same order in the way it is inserted but Set doesntensures the sequence in which data can be retrieved.(Except HashSet)

    What is difference between Arrays and ArrayList ?

    Ans) Arrays are created of fix size whereas ArrayList is of not fix size. It means that oncearray is declared as :

    1. int [] intArray= new int[6];2. intArray[7] // will give ArraysOutOfBoundException.

    Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.

  • 7/27/2019 Java Introduction Questions and Answers

    34/107

    34

    2.

    Once the array is created elements cannot be added or deleted from it. But with ArrayListthe elements can be added and deleted at runtime.

    List list = new ArrayList();

    list.add(1);

    list.add(3);list.remove(0) // will remove the element from the 1st location.

    3.

    ArrayList is one dimensional but array can be multidimensional.

    int[][][] intArray= new int[3][2][1]; // 3 dimensional array

    4.

    To create an array the size should be known or initalized to some value. If not initializedcarefully there could me memory wastage. But arrayList is all about dynamic creation andthere is no wastage of memory.

    When to use ArrayList or LinkedList ?

    Ans) Adding new elements is pretty fast for either type of list. For the ArrayList, doingrandom lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's noefficient way to index into the middle of a linked list. When removing elements, usingArrayList is slow. This is because all remaining elements in the underlying array of Objectinstances must be shifted down for each remove operation. But here LinkedList is fast,because deletion can be done simply by changing a couple of links. So an ArrayList worksbest for cases where you're doing random access on the list, and a LinkedList works betterif you're doing a lot of editing in the middle of the list.

    Source :Read More - from java.sun

    Consider a scenario. If an ArrayList has to be iterate to read data only, what are thepossible ways and which is the fastest?

    Ans) It can be done in two ways, using for loop or using iterator of ArrayList. The firstoption is faster than using iterator. Because value stored in arraylist is indexed access. Sowhile accessing the value is accessed directly as per the index.

    Now another question with respect to above question is if accessing through iterator

    is slow then why do we need it and when to use it.

    Ans) For loop does not allow the updation in the array(add or remove operation) inside theloop whereas Iterator does. Also Iterator can be used where there is no clue what type ofcollections will be used because all collections have iterator.

    Which design pattern Iterator follows?

    http://java.sun.com/developer/TechTips/1999/tt0809.htmlhttp://java.sun.com/developer/TechTips/1999/tt0809.htmlhttp://java.sun.com/developer/TechTips/1999/tt0809.html
  • 7/27/2019 Java Introduction Questions and Answers

    35/107

    35

    Ans) It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. TheIterator pattern is one, which allows you to navigate through a collection of data using acommon interface without knowing about the underlying implementation. Iterator shouldbe implemented as an interface. This allows the user to implement it anyway its easier forhim/her to return data. The benefits of Iterator are about their strength to provide a

    common interface for iterating through collections without bothering about underlyingimplementation.

    Example of Iteration design pattern - Enumeration The class java.util.Enumeration is anexample of the Iterator pattern. It represents and abstract means of iterating over acollection of elements in some sequential order without the client having to know therepresentation of the collection being iterated over. It can be used to provide a uniforminterface for traversing collections of all kinds.

    Why is it preferred to declare: List list = new ArrayList(); instead ofArrayList = new ArrayList();

    Ans) It is preferred because:

    1. If later on code needs to be changed from ArrayList to Vector then only at thedeclaration place we can do that.

    2. The most important one If a function is declared such that it takes list. E.g voidshowDetails(List list);When the parameter is declared as List to the function it can be called by passingany subclass of List like ArrayList,Vector,LinkedList making the function moreflexible

    What is difference between iterator access and index access?

    Ans) Index based access allow access of the element directly on the basis of index. Thecursor of the datastructure can directly goto the 'n' location and get the element. It doesnottraverse through n-1 elements.

    In Iterator based access, the cursor has to traverse through each element to get the desiredelement.So to reach the 'n'th element it need to traverse through n-1 elements.

    Insertion,updation or deletion will be faster for iterator based access if the operations areperformed on elements present in between the datastructure.

    Insertion,updation or deletion will be faster for index based access if the operations areperformed on elements present at last of the datastructure.

    Traversal or search in index based datastructure is faster.

    ArrayList is index access and LinkedList is iterator access.

  • 7/27/2019 Java Introduction Questions and Answers

    36/107

    36

    How to sort list in reverse order?

    Ans) To sort the elements of the List in the reverse natural order of the strings, get areverse Comparator from the Collections class with reverseOrder(). Then, pass the reverseComparator to the sort() method.

    List list = new ArrayList();

    Comparator comp = Collections.reverseOrder();

    Collections.sort(list, comp)

    Can a null element added to a Treeset or HashSet?

    Ans) A null element can be added only if the set contains one element because when asecond element is added then as per set defination a check is made to check duplicate value

    and comparison with null element will throw NullPointerException.HashSet is based on hashMap and can contain null element.

    How to sort list of strings - case insensitive?

    Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

    How to make a List (ArrayList,Vector,LinkedList) read only?

    Ans) A list implemenation can be made read only usingCollections.unmodifiableList(list). This method returns a new list. If a user tries to

    perform add operation on the new list; UnSupportedOperationException is thrown.

    What is ConcurrentHashMap?

    Ans) A concurrentHashMap is thread-safe implementation of Map interface. In this classput and remove method are synchronized but not get method. This class is different fromHashtable in terms of locking; it means that hashtable use object level lock but this classuses bucket level lock thus having better performance.

    Which is faster to iterate LinkedHashSet or LinkedList?

    Ans) LinkedList.

    Which data structure HashSet implements

    Ans) HashSet implements hashmap internally to store the data. The data passed to hashsetis stored as key in hashmap with null as value.

  • 7/27/2019 Java Introduction Questions and Answers

    37/107

    37

    Arrange in the order of speed - HashMap,HashTable,

    Collections.synchronizedMap,concurrentHashmap

    Ans) HashMap is fastest, ConcurrentHashMap,Collections.synchronizedMap,HashTable.

    What is identityHashMap?

    Ans) The IdentityHashMap uses == for equality checking instead of equals(). This can beused for both performance reasons, if you know that two different elements will never beequals and for preventing spoofing, where an object tries to imitate another.

    What is WeakHashMap?

    Ans) A hashtable-based Map implementation with weak keys. An entry in a WeakHashMapwill automatically be removed when its key is no longer in ordinary use. More precisely,the presence of a mapping for a given key will not prevent the key from being discarded by

    the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a keyhas been discarded its entry is effectively removed from the map, so this class behavessomewhat differently than other Map implementations.

    5. Exceptions Questions

    What is an Exception?

    Ans) The exception is said to be thrown whenever an exceptional event occurs in javawhich signals that something is not correct with the code written and may give unexpected

    result. An exceptional event is a occurrence of condition which alters the normal programflow. Exceptional handler is the code that does something about the exception.

    Exceptions are defined in which java package?

    Ans)All the exceptions are subclasses of java.lang.Exception

    How are the exceptions handled in java?

    Ans)When an exception occurs the execution of the program is transferred to anappropriate exception handler.The try-catch-finally block is used to handle the exception.

    The code in which the exception may occur is enclosed in a try block, also called as aguarded region.The catch clause matches a specific exception to a block of code which handles thatexception.And the clean up code which needs to be executed no matter the exception occurs or not isput inside the finally block

    Explain the exception hierarchy in java.

  • 7/27/2019 Java Introduction Questions and Answers

    38/107

    38

    Ans) The hierarchy is as follows:

    Throwable is a parent class off all Exception classes. They are two types of Exceptions:Checked exceptions and UncheckedExceptions. Both type of exceptions extends Exceptionclass.

    What is Runtime Exception or unchecked exception?

    Ans) Runtime exceptions represent problems that are the result of a programmingproblem. Such problems include arithmetic exceptions, such as dividing by zero; pointerexceptions, such as trying to access an object through a null reference; and indexingexceptions, such as attempting to access an array element through an index that is too largeor too small. Runtime exceptions need not be explicitly caught in try catch block as it can

    occur anywhere in a program, and in a typical one they can be very numerous. Having toadd runtime exceptions in every method declaration would reduce a program's clarity.Thus, the compiler does not require that you catch or specify runtime exceptions (althoughyou can). The solution to rectify is to correct the programming logic where the exceptionhas occurred or provide a check.

    What is checked exception?

    Ans) Checked exception are the exceptions which forces the programmer to catch themexplicitly in try-catch block. It is a subClass of Exception. Example: IOException.

    What is difference between Error and Exception?

    Ans) An error is an irrecoverable condition occurring at runtime. Such as OutOfMemoryerror. These JVM errors and you can not repair them at runtime.Though error can becaught in catch block but the execution of application will come to a halt and is notrecoverable.

    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 aNullPointerException will take place if you try using a null reference. In most of the cases itis possible to recover from an exception (probably by giving user a feedback for entering

    proper values etc.)

    What is difference between ClassNotFoundException and NoClassDefFoundError?

    Ans) A ClassNotFoundException is thrown when the reported class is not found by theClassLoader in the CLASSPATH. It could also mean that the class in question is trying to beloaded from another class which was loaded in a parent classloader and hence the classfrom the child classloader is not visible.

  • 7/27/2019 Java Introduction Questions and Answers

    39/107

    39

    Consider if NoClassDefFoundError occurs which is something like

    java.lang.NoClassDefFoundError

    src/com/TestClass

    does not mean that the TestClass class is not in the CLASSPATH. It means that the classTestClass was found by the ClassLoader however when trying to load the class, it ran intoan error reading the class definition. This typically happens when the class in question hasstatic blocks or members which use a Class that's not found by the ClassLoader. So to findthe culprit, view the source of the class in question (TestClass in this case) and look forcode using static blocks or static members.

    What is throw keyword?

    Ans) Throw keyword is used to throw the exception manually. It is mainly used when the

    program fails to satisfy the given condition and it wants to warn the application.Theexception thrown should be subclass of Throwable.

    public void parent(){

    try{

    child();

    }catch(MyCustomException e){ }

    }

    public void child{

    String iAmMandatory=null;

    if(iAmMandatory == null){

    throw (new MyCustomException("Throwing exception using throw keyword");

    }

    }

    What is use of throws keyword?

    Ans) If the function is not capable of handling the exception then it can ask the callingmethod to handle it by simply putting the throws clauseat the function declaration.

    public void parent(){

    try{

    child();

    }catch(MyCustomException e){ }

    }

  • 7/27/2019 Java Introduction Questions and Answers

    40/107

    40

    public void child throws MyCustomException{

    //put some logic so that the exception occurs.

    }

    What are the possible combination to write try, catch finally block?

    Ans)

    1) try{

    //lines of code that may throw an exception

    }catch(Exception e){

    //lines of code to handle the exception thrown in try block

    }finally{

    //the clean code which is executed always no matter the exception occurs or not.

    }

    2 try{

    }finally{}

    3 try{

    }catch(Exception e){

    //lines of code to handle the exception thrown in try block

    }

    The catch blocks must always follow the try block. If there are more than one catch blocksthey all must follow each other without any block in between. The finally block must followthe catch block if one is present or if the catch block is absent the finally block must followthe try block.

    How to create custom Exception?

    Ans) To create you own exception extend the Exception class or any of its subclasses.

    e.g.

  • 7/27/2019 Java Introduction Questions and Answers

    41/107

    41

    1 class New1Exception extends Exception { } // this will create Checked Exception

    2 class NewException extends IOExcpetion { } // this will create Checked exception

    3 class NewException extends NullPonterExcpetion { } // this will create UnChecked

    exception

    When to make a custom checked Exception or custom unchecked Exception?

    Ans) If an application can reasonably be expected to recover from an exception, make it achecked exception. If an application cannot do anything to recover from the exception,make it an unchecked exception.

    What is StackOverflowError?

    Ans) The StackOverFlowError is an Error Object thorwn by the Runtime System when it

    Encounters that your application/code has ran out of the memory. It may occur in case ofrecursive methods or a large amount of data is fetched from the server and stored in someobject. This error is generated by JVM.

    e.g. void swap(){

    swap();

    }

    Why did the designers decide to force a method to specify all uncaught checked

    exceptions that can be thrown within its scope?

    Ans) Any Exception that can be thrown by a method is part of the method's publicprogramming interface. Those who call a method must know about the exceptions that amethod can throw so that they can decide what to do about them. These exceptions are asmuch a part of that method's programming interface as its parameters and return value.

    Once the control switches to the catch block does it return back to the try block to

    execute the balance code?

    Ans) No. Once the control jumps to the catch block it never returns to the try block but it

    goes to finally block(if present).

    Where is the clean up code like release of resources is put in try-catch-finally block

    and why?

    Ans) The code is put in a finally block because irrespective of try or catch block executionthe control will flow to finally block. Typically finally block contains release of connections,closing of result set etc.

  • 7/27/2019 Java Introduction Questions and Answers

    42/107

    42

    Is it valid to have a try block without catch or finally?

    Ans) NO. This will result in a compilation error. The try block must be followed by a catchor a finally block. It is legal to omit the either catch or the finally block but not both.

    e.g. The following code is illegal.

    try{int i =0;}int a = 2;System.out.println(a = +a);

    Is it valid to place some code in between try the catch/finally block that follows it?

    Ans) No. There should not be any line of code present between the try and the catch/finally

    block. e.g. The following code is wrong.

    try{}String str = ABC;System.out.println(str = +str);catch(Exception e){}

    What happens if the exception is never caught and throws down the method stack?

    Ans) If the exception is not caught by any of the method in the methods stack till you get to

    the main() method, the main method throws that exception and the JVM halts its execution.

    How do you get the descriptive information about the Exception occurred during the

    program execution?

    Ans) All the exceptions inherit a method printStackTrace() from the Throwable class. Thismethod prints the stack trace from where the exception occurred. It prints the mostrecently entered method first and continues down, printing the name of each method as itworks its way down the call stack from the top.

    Can you catch more than one exceptions in a single catch block?

    Ans)Yes. If the exception class specified in the catch clause has subclasses, any exceptionobject that is a subclass of the specified Exception class will be caught by that single catchblock.

    E.g..

    try {

  • 7/27/2019 Java Introduction Questions and Answers

    43/107

    43

    // Some code here that can throw an IOException

    }

    catch (IOException e) {

    e.printStackTrace();

    }

    The catch block above will catch IOException and all its subclasses e.g.FileNotFoundException etc.

    Why is not considered as a good practice to write a single catchall handler to catch allthe exceptions?

    Ans) You can write a single catch block to handle all the exceptions thrown during theprogram execution as follows :

    try {

    // code that can throw exception of any possible type

    }catch (Exception e) {

    e.printStackTrace();

    }

    If you use the Superclass Exception in the catch block then you will not get the valuableinformation about each of the exception thrown during the execution, though you can findout the class of the exception occurred. Also it will reduce the readability of the code as theprogrammer will not understand what is the exact reason for putting the try-catch block.

    What is exception matching?

    Ans) Exception matching is the process by which the the jvm finds out the matching catchblock for the exception thrown from the list of catch blocks. When an exception is thrown,

    Java will try to find by looking at the available catch clauses in the top down manner. If itdoesn't find one, it will search for a handler for a supertype of the exception. If it does notfind a catch clause that matches a supertype for the exception, then the exception ispropagated down the call stack. This process is called exception matching.

    What happens if the handlers for the most specific exceptions is placed above themore general exceptions handler?

  • 7/27/2019 Java Introduction Questions and Answers

    44/107

    44

    Ans) Compilation fails. The catch block for handling the most specific exceptions mustalways be placed above the catch block written to handle the more general exceptions.

    e.g. The code below will not compile.

    1 try {

    // code that can throw IOException or its subtypes

    } catch (IOException e) {

    // handles IOExceptions and its subtypes

    } catch (FileNotFoundException ex) {

    // handle FileNotFoundException only

    }

    The code below will compile successfully :-

    try {// code that can throw IOException or its subtypes} catch (FileNotFoundException ex) {// handles IOExceptions and its subtypes} catch (IOException e){// handle FileNotFoundException only

    }

    Does the order of the catch blocks matter if the Exceptions caught by them are not

    subtype or supertype of each other?

    Ans) No. If the exceptions are siblings in the Exception classs hierarchy i.e. If one Exception

    class is not a subtype or supertype of the other, then the order in which theirhandlers(catch clauses) are placed does not matter.

    What happens if a method does not throw an checked Exception directly but calls a

    method that does? What does 'Ducking' the exception mean?

    Ans) If a method does not throw an checked Exception directly but calls a method thatthrows an exception then the calling method must handle the throw exception or declarethe exception in its throws clause. If the calling method does not handle and declares theexception, the exceptions is passed to the next method in the method stack. This is called asducking the exception down the method stack.

  • 7/27/2019 Java Introduction Questions and Answers

    45/107

    45

    e.g. The code below will not compile as the getCar() method has not declared theCarNotFoundException which is thrown by the getColor () method.

    void getCar() {

    getColor();

    }

    void getColor () {

    throw new CarNotFoundException();

    }

    Fix for the above code is

    void getCar() throws CarNotFoundException {

    getColor();

    }

    void getColor () {

    throw new CarNotFoundException();

    }

    Is an empty catch block legal?

    Ans) Yes you can leave the catch block without writing any actual code to handle theexception caught.

    e.g. The code below is legal but not appropriate, as in this case you will nt get anyinformation about the exception thrown.

    try{

    //code that may throw the FileNotFoundException

    }catch(FileNotFound eFnf){

    //no code to handle the FileNotFound exception

    }

  • 7/27/2019 Java Introduction Questions and Answers

    46/107

    46

    Can a catch block throw the exception caught by itself?

    Ans) Yes. This is called rethrowing of the exception by catch block.

    e.g. the catch block below catches the FileNotFound exception and rethrows it again.

    void checkEx() throws FileNotFoundException {

    try{

    //code that may throw the FileNotFoundException

    }catch(FileNotFound eFnf){

    throw FileNotFound();

    }

    }

    6. Threads Questions

    What is a Thread?

    Ans) In Java, "thread" means two different things:

    An instance of class java.lang.Thread.A thread of execution.

    An instance of Thread is justan object. Like any other object in Java, it has variables and

    methods, and lives and dies on the heap. But a thread of execution is an individual process(a "lightweight" process) that has its own call stack. In Java, there is one thread per callstackor, to think of it in reverse, one call stack per thread. Even if you don't create anynew threads in your program, threads are back there running.

    The main() method, that starts the whole ball rolling, runs in one thread, called(surprisingly) the main thread. If you looked at the main call stack (and you can, any timeyou get a stack trace from something that happens after main begins, but not withinanother thread), you'd see that main() is the first method on the stackthe method at thebottom. But as soon as you create a new thread, a new stack materializes and methodscalled from that thread run in a call stack that's separate from the main() call stack.

    What is difference between thread and process?

  • 7/27/2019 Java Introduction Questions and Answers

    47/107

    47

    Ans) Differences between threads and processes are:-1. Threads share the address space of the process that created it; processes have their ownaddress.

    2. Threads have direct access to the data segment of its process; processes have their own

    copy of the data segment of the parent process.

    3. Threads can directly communicate with other threads of its process; processes must useinterprocess communication to communicate with sibling processes.

    4. Threads have almost no overhead; processes have considerable overhead.

    5. New threads are easily created; new processes require duplication of the parent process.

    6. Threads can exercise considerable control over threads of the same process; processescan only exercise control over child processes.

    7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior ofthe other threads of the process; changes to the parent process do not affect childprocesses.

    What are the advantages or usage of threads?

    Ans)Threads support concurrent operations. For example,

    Multiple requests by a client on a server can be handled as an individual client thread. Long computations or high-latency disk and network operations can be handled in the

    background without disturbing foreground computations or screen updates.

    Threads often result in simpler programs.

    In sequential programming, updating multiple displays normally requires a big while-loop that performs small parts of each display update. Unfortunately, this loop basicallysimulates an operating system scheduler. In Java, each view can be assigned a thread toprovide continuous updates. Programs that need to respond to user-initiated events can set up service routines tohandle the events without having to insert code in the main routine to look for theseevents.

    Threads provide a high degree of control. Imagine launching a complex computation that occasionally takes longer than is

    satisfactory. A "watchdog" thread can be activated that will "kill" the computation if itbecomes costly, perhaps in favor of an alternate, approximate solution. Note that sequentialprograms must muddy the computation with termination code, whereas, a Java programcan use thread control to non-intrusively supervise any operation.

    Threaded applications exploit parallelism.

  • 7/27/2019 Java Introduction Questions and Answers

    48/107

    48

    A computer with multiple CPUs can literally execute multiple threads on different

    functional units without having to simulating multi-tasking ("time sharing"). On some computers, one CPU handles the display while another handles computations or

    database accesses, thus, providing extremely fast user interface response times.

    What are the two ways of creating thread?

    Ans) There are two ways to create a new thread.

    1)Extend the Thread classand override the run() method in your class. Create aninstance of the subclass and invoke the start() method on it, which will create a new threadof execution. e.g.

    public class NewThread extends Thread{

    public void run(){

    // the code that has to be executed in a separate new thread goes here}public static void main(String [] args){NewThread c = new NewThread();c.start();}

    }

    2)Implements the Runnable interface.The class will have to implement the run() methodin the Runnable interface. Create an instance of this class. Pass the reference of this

    instance to the Thread constructor a new thread of execution will be created. e.g. class

    public class NewThread implements Runnable{

    public void run(){// the code that has to be executed in a separate new thread goes here}public static void main(String [] args){NewThread c = new NewThread();Thread t = new Thread(c);t.start();

    }

    }

    What are the different states of a thread's lifecycle?

    Ans) The different states of threads are as follows:

  • 7/27/2019 Java Introduction Questions and Answers

    49/107

    49

    1) NewWhen a thread is instantiated it is in New state until the start() method is calledon the thread instance. In this state the thread is not considered to be alive.2) RunnableThe thread enters into this state after the start method is called in thethread instance. The thread may enter into the Runnable state from Running state. In thisstate the thread is considered to be alive.

    3) RunningWhen the thread scheduler picks up the thread from the Runnable threadspool, the thread starts running and the thread is said to be in Running state.4)Waiting/Blocked/SleepingIn these states the thread is said to be alive but not

    runnable. The thread switches to this state because of reasons like wait method called orsleep method has been called on the running thread or thread might be waiting for somei/o resource so blocked. 5) Dead When the thread finishes its execution i.e. the run()method execution completes, it is said to be in dead state. A dead state can not be startedagain. If a start() method is invoked on a dead thread a runtime exception will occur.

    What is use of synchronized keyword?

    Ans) synchronized keyword can be applied to static/non-static methods or a block of code.Only one thread at a time can access synchronized methods and if there are multiplethreads trying to access the same method then other threads have to wait for the executionof method by one thread. Synchronized keyword provides a lock on the object and thusprevents race condition. E.g.

    public void synchronized method(){}public void synchronized staticmethod(){}public void myMethod(){

    synchronized (this){ // synchronized keyword on block of code

    }

    }

    What is the difference when the synchronized keyword is applied to a static methodor to a non static method?

    Ans) When a synch non static method is called a lock is obtained on the object. When asynch static method is called a lock is obtained on the class and not on the object. The lockon the object and the lock on the class dont interfere with each other. It means, athread accessing a synch non static method, then the other thread can access the synch

    static method at the same time but cant access the synch non static method.

    What is a volatile keyword?

    Ans) In general each thread has its own copy of variable, such that one thread is notconcerned with the value of same variable in the other thread. But sometime this may notbe the case. Consider a scenario in which the count variable is holding the number of timesa method is called for a given class irrespective of any thread calling, in this case

  • 7/27/2019 Java Introduction Questions and Answers

    50/107

    50

    irrespective of thread access the count has to be increased so the count variable is declaredas volatile. The copy of volatile variable is stored in the main memory, so every time athread access the variable even for reading purpose the local copy is updated each timefrom the main memory. The volatile variable also have performance issues.

    What is the difference between yield() and sleep()?

    Ans) yield() allows the current the thread to release its lock from the object and schedulergives the lock of the object to the other thread with same priority.sleep() allows th