Java - 400+ Interview Questions and Answers on Core Java

Q1. Can we reduce the visibility of the overridden method ?show Answer

Ans. No

Q2. What are different types of inner classes ?show Answer

Ans. Simple Inner Class, Local Inner Class, Anonymous Inner Class , Static Nested Inner Class.

Q3. Difference between TreeMap and HashMap ?show Answer

Ans. They are different the way they are stored in memory. TreeMap stores the Keys in order whereas HashMap stores the key value pairs randomly.

Q4. What is the difference between List, Set and Map ?show Answer

Ans. List - Members are stored in sequence in memory and can be accessed through index.
Set - There is no relevance of sequence and index. Sets doesn't contain duplicates whereas multiset can have duplicates. Map - Contains Key , Value pairs.

Q5. Difference between Public, Private, Default and Protected ?


show Answer

Ans. Private - Not accessible outside object scope.
Public - Accessible from anywhere.
Default - Accessible from anywhere within same package.
Protected - Accessible from object and the sub class objects.

Q6. What is servlet Chaining ?show Answer

Ans. Multiple servlets serving the request in chain.

Q7. What are the Wrapper classes available for primitive types ?show Answer

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

Q8. What are concepts introduced with Java 5 ?show Answer

Ans. Generics , Enums , Autoboxing , Annotations and Static Import.

Q9. Does Constructor creates the object ?show Answer

Ans. New operator in Java creates objects. Constructor is the later step in object creation. Constructor's job is to initialize the members after the object has reserved memory for itself.

Q10. Can static method access instance variables ?show Answer

Ans. Though Static methods cannot access the instance variables directly, They can access them using instance handler.

Q11. Does Java support Multiple Inheritance ?show Answer

Ans. Interfaces does't facilitate inheritance and hence implementation of multiple interfaces doesn't make multiple inheritance. Java doesn't support multiple inheritance.

Q12. Difference between == and .equals() ?show Answer

Ans. "equals" is the member of object class which returns true if the content of objects are same whereas "==" evaluate to see if the object handlers on the left and right are pointing to the same object in memory.

Q13. Difference between Checked and Unchecked exceptions ?show Answer

Ans. Checked exceptions and the exceptions for which compiler throws an errors if they are not checked whereas unchecked exceptions and caught during run time only and hence can't be checked.

Q14. What is a Final Variable ?show Answer

Ans. Final variable is a variable constant that cannot be changed after initialization.

Q15. Which class does not override the equals() and hashCode() methods, inheriting them directly from class Object?show Answer

Ans. java.lang.StringBuffer.

Q16. What is a final method ?show Answer

Ans. Its a method which cannot be overridden. Compiler throws an error if we try to override a method which has been declared final in the parent class.

Q17. Which interface does java.util.Hashtable implement?show Answer

Ans. Java.util.Map

Q18. What is an Iterator?show Answer

Ans. Iterator is an interface that provides methods to iterate over any Collection.

Q19. Which interface provides the capability to store objects using a key-value pair?show Answer

Ans. java.util.map

Q20. Difference between HashMap and Hashtable?show Answer

Ans. Hashtable is synchronized whereas HashMap is not.

HashMap allows null values whereas Hashtable doesn’t allow null values.




Q21. Does java allow overriding static methods ?show Answer

Ans. No. Static methods belong to the class and not the objects. They belong to the class and hence doesn't fit properly for the polymorphic behavior.

Q22. When are static variables loaded in memory ?show Answer

Ans. They are loaded at runtime when the respective Class is loaded.

Q23. Can we serialize static variables ?show Answer

Ans. No. Only Object and its members are serialized. Static variables are shared variables and doesn't correspond to a specific object.

Q24. What will this code print ?

String a = new String ("TEST");
String b = new String ("TEST");

if(a == b) {
System.out.println ("TRUE");
} else {
System.out.println ("FALSE");
}show Answer

Ans. FALSE.

== operator compares object references, a and b are references to two different objects, hence the FALSE. .equals method is used to compare string object content.

Q25. There are two objects a and b with same hashcode. I am inserting these two objects inside a hashmap.

hMap.put(a,a);
hMap.put(b,b);

where a.hashCode()==b.hashCode()

Now tell me how many objects will be there inside the hashmap?show Answer

Ans. There can be two different elements with the same hashcode. When two elements have the same hashcode then Java uses the equals to further differentation. So there can be one or two objects depending on the content of the objects.

Q26. Difference between long.Class and Long.TYPE ?show Answer

Ans. They both represent the long primitive type. They are exactly the same.

Q27. Does Java provides default copy constructor ?show Answer

Ans. No

Q28. What are the common uses of "this" keyword in java ?show Answer

Ans. "this" keyword is a reference to the current object and can be used for following -

1. Passing itself to another method.
2. Referring to the instance variable when local variable has the same name.
3. Calling another constructor in constructor chaining.

Q29. What are the difference between Threads and Processes ?show Answer

Ans. 1. when an OS wants to start running program it creates new process means a process is a program that is currently executing and every process has at least one thread running within it.
2). A thread is a path of code execution in the program, which has its own local variables, program counter(pointer to current execution being executed) and lifetime.
3. When the JavaVirtual Machine (JavaVM, or just VM) is started by the operating system, a new process is created. Within that process, many threads can be created.
4. Consider an example : when you open Microsoft word in your OS and you check your task manger then you can see this running program as a process. now when you write something in opened word document, then it performs more than one work at same time like it checks for the correct spelling, it formats the word you enter , so within that process ( word) , due to different path execution(thread) all different works are done at same time.
5. Within a process , every thread has independent path of execution but there may be situation where two threads can interfere with each other then concurrency and deadlock come is picture.
6. like two process can communicate ( ex:u open an word document and file explorer and on word document you drag and drop another another file from file explorer), same way two threads can also communicate with each other and communication with two threads is relatively low.
7. Every thread in java is created and controlled by unique object of java.lang.Thread class.
8. prior to jdk 1.5, there were lack in support of asynchronous programming in java, so in that case it was considered that thread makes the runtime environment asynchronous and allow different task to perform concurrently.

Q30. How can we run a java program without making any object?show Answer

Ans. By putting code within either static method or static block.

Q31. Explain multithreading in Java ?show Answer

Ans. 1. Multithreading provides better interaction with the user by distribution of task
2. Threads in Java appear to run concurrently, so it provides simulation for simultaneous activities.
The processor runs each thread for a short time and switches among the threads to simulate sim-ultaneous execution (context-switching) and it make appears that each thread has its own processor.By using this feature, users can make it appear as if multiple tasks are occurring simultaneously when, in fact, each is
running for only a brief time before the context is switched to the next thread.
3. We can do other things while waiting for slow I/O operations.
In the java.iopackage, the class InputStreamhas a method, read(), that blocks until a byte is read from the stream or until an IOExceptionis thrown. The thread that executes this method cannot do anything elsewhile awaiting the arrival of another byte on the stream.



Q32. Can constructors be synchronized in Java ?show Answer

Ans. No. Java doesn't allow multi thread access to object constructors so synchronization is not even needed.

Q33. can we create a null as a key for a map collection ?show Answer

Ans. Yes , for Hashtable. Hashtable implements Map interface.

Q34. What is the use of hashcode in Java ?show Answer

Ans. Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc. The value received from hashcode() is used as bucket number for storing elements. This bucket number is the address of the element inside the set/map. when you do contains() then it will take the hashcode of the element, then look for the bucket where hashcode points to and if more than 1 element is found in the same bucket (multiple objects can have the same hashcode) then it uses the equals() method to evaluate if object are equal, and then decide if contain() is true or false, or decide if element could be added in the set or not.

Q35. Why java doesn't support multiple Inheritence ?show Answer

Ans. class A {
void test() {
System.out.println("test() method");
}
}

class B {
void test() {
System.out.println("test() method");
}
}

Suppose if Java allows multiple inheritance like this,

class C extends A, B {
}

A and B test() methods are inheriting to C class.

So which test() method C class will take? As A & B class test() methods are different , So here we would Facing Ambiguity.


Q36. Why threads block or enters to waiting state on I/O?show Answer

Ans. Threads enters to waiting state or block on I/O because other threads can execute while the I/O operations are performed.

Q37. What are transient variables in java?show Answer

Ans. Transient variables are variable that cannot be serialized.

Q38. What is the difference between yield() and sleep()?show Answer

Ans. When a object invokes yield() it returns to ready state. But when an object invokes sleep() method enters to not ready state.

Q39. What are wrapper classes ?show Answer

Ans. They are wrappers to primitive data types. They allow us to access primitives as objects.

Q40. What is the initial state of a thread when it is created and started?show Answer

Ans. Ready state.

Q41. What one should take care of, while serializing the object?

show Answer

Ans. One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializable Exception.

Q42. What is a String Pool ?show Answer

Ans. String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

Q43. Why is String immutable in Java ?show Answer

Ans. 1. String Pool

When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

2. To Cache its Hashcode

If string is not immutable, One can change its hashcode and hence not fit to be cached.

3. Security

String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.


Q44. what is the use of cookie and session ? and What is the difference between them ?show Answer

Ans. Cookie and Session are used to store the user information. Cookie stores user information on client side and Session does it on server side. Primarily, Cookies and Session are used for authentication, user preferences, and carrying information across multiple requests. Session is meant for the same purpose as the cookie does. Session does it on server side and Cookie does it on client side. One more thing that quite differentiates between Cookie and Session. Cookie is used only for storing the textual information. Session can be used to store both textual information and objects.

Q45. Which are the different segments of memory ?

show Answer

Ans. 1. Stack Segment - contains local variables and Reference variables(variables that hold the address of an object in the heap)
2. Heap Segment - contains all created objects in runtime, objects only plus their object attributes (instance variables)
3. Code Segment - The segment where the actual compiled Java bytecodes resides when loaded

Q46. Which memory segment loads the java code ?show Answer

Ans. Code segment.

Q47. which containers use a border Layout as their default layout ?show Answer

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

Q48. Can a lock be acquired on a class ?show Answer

Ans. Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

Q49. What state does a thread enter when it terminates its processing?show Answer

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

Q50. Does garbage collection guarantee that a program will not run out of memory?show Answer

Ans. Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection

Q51. What is an object's lock and which object's have locks?
show Answer

Ans. An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

Q52. What is casting?
show Answer

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

Q53. What restrictions are placed on method overriding?show Answer

Ans. Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.

Q54. How does a try statement determine which catch clause should be used to handle an exception?show Answer

Ans. When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.

Q55. Describe what happens when an object is created in Java ?show Answer

Ans. 1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses. This process continues until the constructor for java.lang.Object is called,
as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

Q56. What is the difference between StringBuffer and String class ?show Answer

Ans. A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. The String class represents character strings. All string literals in Java programs, such as "abc" are constant and implemented as instances of this class; their values cannot be changed after they are created.

Q57. Describe, in general, how java's garbage collector works ?show Answer

Ans. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is known as garbage collection. The Java runtime environment supports a garbage collector that periodically frees the memory used by
objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that scans Java's dynamic memory areas for objects, marking those that are referenced. After all possible paths to objects are investigated, those objects that are not marked (i.e. are not referenced) are known to be garbage and are collected.

Q58. What is RMI ?show Answer

Ans. RMI stands for Remote Method Invocation. Traditional approaches to executing code on other machines across a network have been confusing as well as tedious and error-prone to implement. The nicest way to think about this problem is that some object happens to live on another machine, and that you can send a message to the remote object and get a result as if the object lived on your local machine. This simplification is exactly what Java Remote Method Invocation (RMI) allows you to do.

Q59. What is JDBC? Describe the steps needed to execute a SQL query using JDBC.show Answer

Ans. The JDBC is a pure Java API used to execute SQL statements. It provides a set of classes and interfaces that can be used by developers to write database applications.

The steps needed to execute a SQL query using JDBC:

1. Open a connection to the database.
2. Execute a SQL statement.
3. Process th results.
4. Close the connection to the database.

Q60. Are constructors inherited? Can a subclass call the parent's class constructor? When?show Answer

Ans. You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it's superclasses. One of the main reasons is because you probably don't want to override the superclasses constructor, which would be possible if they were inherited. By giving the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language.

Q61. What are the methods of Object Class ?show Answer

Ans. clone() - Creates and returns a copy of this object.
equals() - Indicates whether some other object is "equal to" this one.
finalize() - Called by the garbage collector on an object when garbage collection determines that there are no more references to the object
getClass() - Returns the runtime class of an object.
hashCode() - Returns a hash code value for the object.
toString() - Returns a string representation of the object.
notify(), notifyAll(), and wait() - Play a part in synchronizing the activities of independently running threads in a program.

Q62. Explain JMS ( Java Messaging Services ) ?show Answer

Ans. JMS Provides high-performance asynchronous messaging. It enables Java EE applications to communicate with non-Java systems on top of various transports.

Q63. Explain EJB (Enterprise Java Beans) ?show Answer

Ans. EJB Provides a mechanism that make easy for Java developers to use advanced features in their components, such as remote method invocation (RMI), object/ relational mapping (that is, saving Java objects to a relational database), and distributed transactions across multiple data sources.

Q64. What is an API ( Application Programming Interface ) ?show Answer

Ans. An API is a kind of technical contract which defines functionality that two parties must provide: a service provider (often called an implementation) and an application. an API simply defines services that a service provider (i.e., the implementation) makes available to applications.

Q65. What are the default or implicitly assigned values for data types in java ?show Answer

Ans. boolean ---> false
byte ----> 0
short ----> 0
int -----> 0
long ------> 0l
char -----> /u0000
float ------> 0.0f
double ----> 0.0d
any object reference ----> null

Q66. What is difference between Encapsulation And Abstraction?show Answer

Ans. 1.Abstraction solves the problem at design level while encapsulation solves the problem at implementation level

2.Abstraction is used for hiding the unwanted data and giving relevant data. while Encapsulation means hiding the code and data into a single unit to protect the data from outside world.

3. Abstraction lets you focus on what the object does instead of how it does it while Encapsulation means hiding the internal details or mechanics of how an object does something.

4.For example: Outer Look of a Television, like it has a display screen and channel buttons to change channel it explains Abstraction but Inner Implementation detail of a Television how CRT and Display Screen are connect with each other using different circuits , it explains Encapsulation.

Q67. Can I import same package/class twice? Will the JVM load the package twice at runtime?show Answer

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

Q68. Explain static blocks in Java ?show Answer

Ans. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static {
// whatever code is needed for initialization goes here
}

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.


Q69. Which access specifier can be used with Class ?show Answer

Ans. For top level class we can only use "public" and "default". We can use private with inner class.

Q70. Explain use of nested or inner classes ?show Answer

Ans. Sometime we just need classes or class objects just to be used as part of a particular class or objects. Making them non nested won't make any difference as far as functionality is concerner but making them Nested provide a level of convenience and protection fro, being used anywhere else. Moreover it helps reducing the Code.

Q71. Explain Annotations ?show Answer

Ans. Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate. Annotations have a number of uses, among them:
• Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
• Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
• Runtime processing — Some annotations are available to be examined at runtime.


Q72. Give an Example of Annotations ?show Answer

Ans. Suppose that a software group traditionally starts the body of every class with comments providing important information:
public class Generation3List extends Generation2List {

// Author: John Doe
// Date: 3/17/2002
// Current revision: 6
// Last modified: 4/12/2004
// By: Jane Doe
// Reviewers: Alice, Bill, Cindy

// class code goes here

}
To add this same metadata with an annotation, you must first define the annotation type. The syntax for doing this is:
@interface ClassPreamble {
String author();
String date();
int currentRevision() default 1;
String lastModified() default "N/A";
String lastModifiedBy() default "N/A";
// Note use of array
String[] reviewers();
}
The annotation type definition looks similar to an interface definition where the keyword interface is preceded by the at sign (@) (@ = AT, as in annotation type). Annotation types are a form of interface, which will be covered in a later lesson. For the moment, you do not need to understand interfaces.
The body of the previous annotation definition contains annotation type element declarations, which look a lot like methods. Note that they can define optional default values.
After the annotation type is defined, you can use annotations of that type, with the values filled in, like this:
@ClassPreamble (
author = "John Doe",
date = "3/17/2002",
currentRevision = 6,
lastModified = "4/12/2004",
lastModifiedBy = "Jane Doe",
// Note array notation
reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {

// class code goes here

}


Q73. What are few of the Annotations pre defined by Java?show Answer

Ans. @Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation.

@Override annotation informs the compiler that the element is meant to override an element declared in a superclass.

@SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate.

@SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not perform potentially unsafe operations on its varargsparameter. When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.

@FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.


Q74. What are meta Annotations ?show Answer

Ans. Annotations that apply to other annotations are called meta-annotations.

Q75. Name few meta-annotations ?show Answer

Ans. @Retention annotation specifies how the marked annotation is stored:

@Documented annotation indicates that whenever the specified annotation is used those elements should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.)

@Target annotation marks another annotation to restrict what kind of Java elements the annotation can be applied to.

@Inherited annotation indicates that the annotation type can be inherited from the super class. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class' superclass is queried for the annotation type. This annotation applies only to class declarations.

@Repeatable annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use. For more information, see Repeating Annotations.


Q76. Difference between Abstract and Concrete Class ?show Answer

Ans. Abstract classes are only meant to be sub classed and not meant to be instantiated whereas concrete classes are meant to be instantiated.

Q77. Difference between Overloading and Overriding ?show Answer

Ans. Overloading - Similar Signature but different definition , like function overloading.

Overriding - Overriding the Definition of base class in the derived class.

Q78. Difference between Vector and ArrayList ?show Answer

Ans. Vectors are synchronized whereas Array lists are not.

Q79. Different ways of implementing Threads in Java ?show Answer

Ans. Threads in Java can be implement either by Extending Thread class or implementing runnable interface.

Q80. What is Volatile keyword used for ?show Answer

Ans. Volatile is a declaration that a variable can be accessed by multiple threads and hence shouldn't be cached.

Q81. What is Serialization ?show Answer

Ans. Storing the state of an object in a file or other medium is called serialization.

Q82. What is the use of Transient Keyword ?show Answer

Ans. It in Java is used to indicate that a field should not be serialized.

Q83. What is a final variable ?show Answer

Ans. Final variable is a constant variable. Variable value can't be changed after instantiation.

Q84. What is a Final Method ?show Answer

Ans. A Method that cannot be overriden in the sub class.

Q85. What is a Final Class ?show Answer

Ans. A Class that cannot be sub classed.

Q86. What is an Immutable Object ?show Answer

Ans. Object that can't be changed after instantiation.

Q87. What is an immutable class ?show Answer

Ans. Class using which only immutable (objects that cannot be changed after initialization) objects can be created.

Q88. How to implement an immutable class ?show Answer

Ans. We can make a class immutable by

1. Making all methods and variables as private.
2. Setting variables within constructor.

Public Class ImmutableClass{
private int member;
ImmutableClass(int var){
member=var;
}
}

and then we can initialize the object of the class as

ImmutableClass immutableObject = new ImmutableClass(5);

Now all members being private , you can't change the state of the object.


Q89. Does Declaring an object "final" makes it immutable ?show Answer

Ans. Only declaring primitive types as final makes them immutable. Making objects final means that the object handler cannot be used to target some other object but the object is still mutable.

Q90. Difference between object instantiation and construction ?show Answer

Ans. Though It's often confused with each other, Object Creation ( Instantiation ) and Initialization ( Construction ) are different things in Java. Construction follows object creation.

Object Creation is the process to create the object in memory and returning its handler. Java provides New keyword for object creation.

Initialization is the process of setting the initial / default values to the members. Constructor is used for this purpose. If we don't provide any constructor, Java provides one default implementation to set the default values according to the member data types.


Q91. Can we override static methods ? Why ?show Answer

Ans. No.

Static methods belong to the class and not the objects. They belong to the class and hence doesn't fit properly for the polymorphic behavior.

A static method is not associated with any instance of a class so the concept of overriding for runtime polymorphism using static methods is not applicable.

Q92. Can we access instance variables within static methods ?show Answer

Ans. Yes.

we cannot access them directly but we can access them using object reference.

Static methods belong to a class and not objects whereas non static members are tied to an instance. Accessing instance variables without the instance handler would mean an ambiguity regarding which instance the method is referring to and hence its prohibited.

Q93. Can we reduce the visibility of the inherited or overridden method ?show Answer

Ans. No.

Q94. Give an Example of checked and unchecked exception ?show Answer

Ans. ClassNotFoundException is checked exception whereas NoClassDefFoundError is a unchecked exception.

Q95. Name few Java Exceptions ?show Answer

Ans. IndexOutofBound , NoClassDefFound , OutOfMemory , IllegalArgument.

Q96. Which of the following is tightly bound ? Inheritance or Composition ?show Answer

Ans. Inheritence.

Q97. How can we make sure that a code segment gets executed even in case of uncatched exceptions ?show Answer

Ans. By putting it within finally.

Q98. Explain the use of "Native" keyword ?show Answer

Ans. Used in method declarations to specify that the method is not implemented in the same Java source file, but rather in another language

Q99. What is "super" used for ?

show Answer

Ans. Used to access members of the base class.

Q100. What is "this" keyword used for ?

show Answer

Ans. Used to represent an instance of the class in which it appears.

Q101. Difference between boolean and Boolean ?show Answer

Ans. boolean is a primitive type whereas Boolean is a class.

Q102. What is a finalize method ?show Answer

Ans. finalize() method is called just before an object is destroyed.

Q103. What are Marker Interfaces ? Name few Java marker interfaces ?
show Answer

Ans. These are the interfaces which have no declared methods.

Serializable and cloneable are marker interfaces.

Q104. Is runnable a Marker interface ?show Answer

Ans. No , it has run method declared.

Q105. Difference between Process and Thread ?show Answer

Ans. Process is a program in execution whereas thread is a separate path of execution in a program.

Q106. What is a Deadlock ?

show Answer

Ans. When two threads are waiting each other and can’t precede the program is said to be deadlock.

Q107. Difference between Serialization and Deserialization ?

show Answer

Ans. Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

Q108. Explain Autoboxing ?


show Answer

Ans. Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes

Q109. What is an Enum type ?

show Answer

Ans. An enum type is a special data type that enables for a variable to be a set of predefined constants

Q110. What are Wrapper Classes ? What are Primitive Wrapper Classes ?

show Answer

Ans. A wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or component. A Wrapper Class that wraps or encapsulates the primitive data type is called Primitive Wrapper Class.

Q111. What Design pattern Wrapper Classes implement ?show Answer

Ans. Adapter.

Q112. What is "Import" used for ?

show Answer

Ans. Enables the programmer to abbreviate the names of classes defined in a package.

Q113. Different types of memory used by JVM ?show Answer

Ans. Class , Heap , Stack , Register , Native Method Stack.

Q114. What is a class loader ? What are the different class loaders used by JVM ?show Answer

Ans. Part of JVM which is used to load classes and interfaces.

Bootstrap , Extension and System are the class loaders used by JVM.

Q115. Can we declare interface methods as private ?show Answer

Ans. No.

Q116. What is a Static import ?
show Answer

Ans. By static import , we can access the static members of a class directly without prefixing it with the class name.

Q117. Difference between StringBuffer and StringBuilder ?show Answer

Ans. StringBuffer is synchronized whereas StringBuilder is not.

Q118. Difference between Map and HashMap ?

show Answer

Ans. Map is an interface where HashMap is the concrete class.

Q119. What is a Property class ?show Answer

Ans. The properties class is a subclass of Hashtable that can be read from or written to a stream.

Q120. Explain the scenerios to choose between String , StringBuilder and StringBuffer ?show Answer

Ans. If the Object value will not change in a scenario use String Class because a String object is immutable.

If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster).

If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).

Q121. Explain java.lang.OutOfMemoryError ?

show Answer

Ans. This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

Q122. Can we have multiple servlets in a web application and How can we do that ?show Answer

Ans. Yes by making entries in web.xml

Q123. Is JVM, a compiler or interpretor ?

show Answer

Ans. Its an interpretor.

Q124. Difference between implicit and explicit type casting ?

show Answer

Ans. An explicit conversion is where you use some syntax to tell the program to do a conversion whereas in case of implicit type casting you need not provide the data type.

Q125. Difference between loadClass and Class.forName ?
show Answer

Ans. loadClass only loads the class but doesn't initialize the object whereas Class.forName initialize the object after loading it.

Q126. Should we override finalize method ?

show Answer

Ans. Finalize is used by Java for Garbage collection. It should not be done as we should leave the Garbage Collection to Java itself.

Q127. What is assert keyword used for ?show Answer

Ans. The assert keyword is used to make an assertion—a statement which the programmer believes is always true at that point in the program. This keyword is intended to aid in testing and debugging.

Q128. Difference between Factory and Abstract Factory Design Pattern ?show Answer

Ans. Factory Pattern deals with creation of objects delegated to a separate factory class whereas Abstract Factory patterns works around a super-factory which creates other factories.

Q129. Difference between Factory and Builder Design Pattern ?show Answer

Ans. Builder pattern is the extension of Factory pattern wherein the Builder class builds a complex object in multiple steps.

Q130. Difference between Proxy and Adapter ?show Answer

Ans. Adapter object has a different input than the real subject whereas Proxy object has the same input as the real subject. Proxy object is such that it should be placed as it is in place of the real subject.

Q131. Difference between Adapter and Facade ?

show Answer

Ans. The Difference between these patterns in only the intent. Adapter is used because the objects in current form cannot communicate where as in Facade , though the objects can communicate , A Facade object is placed between the client and subject to simplify the interface.

Q132. Difference between Builder and Composite ?

show Answer

Ans. Builder is a creational Design Pattern whereas Composite is a structural design pattern. Composite creates Parent - Child relations between your objects while Builder is used to create group of objects of predefined types.

Q133. Example of Chain of Responsibility Design Pattern ?

show Answer

Ans. Exception Handling Throw mechanism.

Q134. Example of Observer Design Pattern ?

show Answer

Ans. Listeners.

Q135. Difference between Factory and Strategy Design Pattern ?show Answer

Ans. Factory is a creational design pattern whereas Strategy is behavioral design pattern. Factory revolves around the creation of object at runtime whereas Strategy or Policy revolves around the decision at runtime.

Q136. Shall we use abstract classes or Interfaces in Policy / Strategy Design Pattern ?show Answer

Ans. Strategy deals only with decision making at runtime so Interfaces should be used.

Q137. Which kind of memory is used for storing object member variables and function local variables ?
show Answer

Ans. Local variables are stored in stack whereas object variables are stored in heap.

Q138. Why do member variables have default values whereas local variables don't have any default value ?

show Answer

Ans. member variable are loaded into heap, so they are initialized with default values when an instance of a class is created. In case of local variables, they are stored in stack until they are being used.

Q139. What is a Default Constructor ?show Answer

Ans. The no argument constructor provided by Java Compiler if no constructor is specified.

Q140. Will Compiler creates a default no argument constructor if we specify only multi argument constructor ?
show Answer

Ans. No, Compiler will create default constructor only if we don't specify any constructor.

Q141. Can we overload constructors ?

show Answer

Ans. Yes.

Q142. What will happen if we make the constructor private ?show Answer

Ans. We can't create the objects directly by invoking new operator.

Q143. How can we create objects if we make the constructor private ?show Answer

Ans. We can do so through a static public member method or static block.

Q144. What will happen if we remove the static keyword from main method ?

show Answer

Ans. Program will compile but will give a "NoSuchMethodError" during runtime.

Q145. Why Java don't use pointers ?
show Answer

Ans. Pointers are vulnerable and slight carelessness in their use may result in memory problems and hence Java intrinsically manage their use.

Q146. Can we use both "this" and "super" in a constructor ?show Answer

Ans. No, because both this and super should be the first statement.

Q147. Do we need to import java.lang.package ?show Answer

Ans. No, It is loaded by default by the JVM.

Q148. Is it necessary that each try block to be followed by catch block ? show Answer

Ans. It should be followed by either catch or finally block.

Q149. Can finally block be used without catch ?show Answer

Ans. Yes but should follow "try" block then.

Q150. What is exception propogation ?show Answer

Ans. Passing the exception object to the calling method.

Q151. Difference between nested and inner classes ?show Answer

Ans. Inner classes are non static nested classes.

Q152. What is a nested interface ?

show Answer

Ans. Any interface declared inside a class or an interface. It is static by default.

Q153. What is an Externalizable interface ?show Answer

Ans. Externalizable interface is used to write the state of an object into a byte stream in compressed format.


Q154. Difference between serializable and externalizable interface ?show Answer

Ans. Serializable is a marker interface whereas externalizable is not.

Q155. What is reflection ?show Answer

Ans. It is the process of examining / modifying the runtime behaviour of an object at runtime.

Q156. Can we instantiate the object of derived class if parent constructor is protected ?

show Answer

Ans. No

Q157. Can we declare an abstract method private ?

show Answer

Ans. No Abstract methods can only be declared protected or public.

Q158. What are the design considerations while making a choice between using interface and abstract class ?show Answer

Ans. Keep it as a Abstract Class if its a "Is a" Relationsship and should do subset/all of the functionality. Keep it as Interface if its a "Should Do" relationship.

Q159. What is suspend() method used for ?show Answer

Ans. suspend() method is used to suspend the execution of a thread for a period of time. We can then restart the thread by using resume() method.

Q160. Difference between suspend() and stop() ?show Answer

Ans. Suspend method is used to suspend thread which can be restarted by using resume() method. stop() is used to stop the thread, it cannot be restarted again.

Q161. What are the benefits of using Spring Framework ?show Answer

Ans. Spring enables developers to develop enterprise-class applications using POJOs. The benefit of using only POJOs is that you do not need an EJB container product.

Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you have to worry only about ones you need and ignore the rest.

Spring does not reinvent the wheel instead, it truly makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, other view technologies.

Testing an application written with Spring is simple because environment-dependent code is moved into this framework. Furthermore, by using JavaBean-style POJOs, it becomes easier to use dependency injection for injecting test data.

Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.

Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.

Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on computers with limited memory and CPU resources.

Spring provides a consistent transaction management interface that can scale down to a local transaction

Q162. what is the difference between collections class vs collections interface ?show Answer

Ans. Collections class is a utility class having static methods for doing operations on objects of classes which implement the Collection interface. For example, Collections has methods for finding the max element in a Collection.

Q163. Will this code give error if i try to add two heterogeneous elements in the arraylist. ? and Why ?

List list1 = new ArrayList<>();
list1.add(5);
list1.add("5");show Answer

Ans. If we don't declare the list to be of specific type, it treats it as list of objects.

int 1 is auto boxed to Integer and "1" is String and hence both are objects.

Q164. Difference between Java beans and Spring Beans ?show Answer

Ans. Java Beans managed by Spring IoC are called Spring Beans.

Q165. What is the difference between System.console.write and System.out.println ?show Answer

Ans. System.console() returns null if your application is not run in a terminal (though you can handle this in your application)

System.console() provides methods for reading password without echoing characters

System.out and System.err use the default platform encoding, while the Console class output methods use the console encoding

Q166. What are various types of Class loaders used by JVM ?show Answer

Ans. Bootstrap - Loads JDK internal classes, java.* packages.

Extensions - Loads jar files from JDK extensions directory - usually lib/ext directory of the JRE

System - Loads classes from system classpath.

Q167. How are classes loaded by JVM ?show Answer

Ans. Class loaders are hierarchical. The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running.

Q168. Difference between C++ and Java ?show Answer

Ans. Java does not support pointers.

Java does not support multiple inheritances.

Java does not support destructors but rather adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize() method.

Java does not include structures or unions because the traditional data structures are implemented as an object oriented framework.

C++ compiles to machine language , when Java compiles to byte code .

In C++ the programmer needs to worry about freeing the allocated memory , where in Java the Garbage Collector takes care of the the unneeded / unused variables.

Java is platform independent language but c++ is depends upon operating system.

Java uses compiler and interpreter both and in c++ their is only compiler.

C++ supports operator overloading whereas Java doesn't.

Internet support is built-in Java but not in C++. However c++ has support for socket programming which can be used.

Java does not support header file, include library files just like C++ .Java use import to include different Classes and methods.

There is no goto statement in Java.

There is no scope resolution operator :: in Java. It has . using which we can qualify classes with the namespace they came from.

Java is pass by value whereas C++ is both pass by value and pass by reference.

Java Enums are objects instead of int values in C++

C++ programs runs as native executable machine code for the target and hence more near to hardware whereas Java program runs in a virtual machine.

C++ was designed mainly for systems programming, extending the C programming language whereas Java was created initially to support network computing.

C++ allows low-level addressing of data. You can manipulate machine addresses to look at anything you want. Java access is controlled.

C++ has several addressing operators . * & -> where Java has only one: the .

We can create our own package in Java(set of classes) but not in c and c++.



Q169. Difference between static vs. dynamic class loading?show Answer

Ans. static loading - Classes are statically loaded with Java’s “new” operator.

dynamic class loading - Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time.

Class.forName (Test className);

Q170. Tell something about BufferedWriter ? What are flush() and close() used for ?show Answer

Ans. A Buffer is a temporary storage area for data. The BufferedWriter class is an output stream.It is an abstract class that creates a buffered character-output stream.

Flush() is used to clear all the data characters stored in the buffer and clear the buffer.

Close() is used to closes the character output stream.

Q171. What is Scanner class used for ? when was it introduced in Java ?show Answer

Ans. Scanner class introduced in Java 1.5 for reading Data Stream from the imput device. Previously we used to write code to read a input using DataInputStream. After reading the stream , we can convert into respective data type using in.next() as String ,in.nextInt() as integer, in.nextDouble() as Double etc

Q172. Why Struts 1 Classes are not Thread Safe whereas Struts 2 classes are thread safe ?show Answer

Ans. Struts 1 actions are singleton. So all threads operates on the single action object and hence makes it thread unsafe.

Struts 2 actions are not singleton and a new action object copy is created each time a new action request is made and hence its thread safe.

Q173. What are some Java related technologies used for distributed computing ?show Answer

Ans. sockets, RMI. EJB

Q174. Whats the purpose of marker interfaces ?
show Answer

Ans. They just tell the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently.

Q175. What is the difference between final, finally and finalize() ?show Answer

Ans. final - constant variable, restricting method overloading, restricting class subclassing.

finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block. Use the finally block to close files or to release
other system resources like database connections, statements etc.

finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state.

Q176. When do you get ClassCastException?show Answer

Ans. As we only downcast class in the hierarchy, The ClassCastException is thrown to indicate that code has attempted to cast an object to a subclass of which it is not an instance.

Q177. Explain Thread States ?show Answer

Ans. Runnable - waiting for its turn to be picked for execution by the thread schedular based on thread priorities.

Running - The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn.

Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.

Sleeping - Java threads are forcibly put to sleep (suspended) with Thread.sleep. they can resume using Thread.resume method.

Blocked on I/O - Will move to runnable after I/O condition like reading bytes of data etc changes.

Blocked on synchronization - Will move to Runnable when a lock is acquired.

Dead - The thread is finished working.

Q178. What are strong, soft, weak and phantom references in Java ?show Answer

Ans. Garbage Collector won’t remove a strong reference.

A soft reference will only get removed if memory is low.

A weak reference will get removed on the next garbage collection cycle.

A phantom reference will be finalized but the memory will not be reclaimed. Can be useful when you want to be notified that an object is about to be collected.

Q179. Difference between yield() and sleeping()?
show Answer

Ans. When a task invokes yield(), it changes from running state to runnable state. When a task invokes sleep(), it changes from running state to waiting/sleeping state.

Q180. What is a daemon thread? Give an Example ?show Answer

Ans. These are threads that normally run at a low priority and provide a basic service to a program or programs when activity on a machine is reduced. garbage collector thread is daemon thread.

Q181. What is the difference between AWT and Swing?show Answer

Ans. Swing provides both additional components like JTable, JTree etc and added functionality to AWT-replacement components.

Swing components can change their appearance based on the current “look and feel” library that’s being used.

Swing components follow the MVC paradigm, and thus can provide a much more flexible UI.

Swing provides extras for components, such as icons on many components, decorative borders for components, tool tips for components etc.

Swing components are lightweight than AWT.

Swing provides built-in double buffering ,which means an off-screen buffer is used during drawing and then the resulting bits are copied onto the screen.

Swing provides paint debugging support for when you build your own component.

Q182. What is the order of method invocation in an applet?show Answer

Ans. public void init()
public void start()
public void stop()
public void destroy()

Q183. Name few tools for probing Java Memory Leaks ?show Answer

Ans. JProbe, OptimizeIt

Q184. Which memory areas does instance and static variables use ?show Answer

Ans. instance variables are stored on stack whereas static variables are stored on heap.

Q185. What is J2EE? What are J2EE components and services?show Answer

Ans. J2EE or Java 2 Enterprise Edition is an environment for developing and deploying enterprise applications. The J2EE platform consists of J2EE components, services, Application Programming Interfaces (APIs) and protocols that provide the functionality for developing multi-tiered and distributed Web based applications.

Q186. What are the components of J2EE ?show Answer

Ans. applets
Client component like Client side Java codes.
Web component like JSP, Servlet WAR
Enterprise JavaBeans like Session beans, Entity beans, Message driven beans
Enterprise application like WAR, JAR, EAR


Q187. Difference between SAX and DOM Parser ?show Answer

Ans. A DOM (Document Object Model) parser creates a tree structure in memory from an input document whereas A SAX (Simple API for XML) parser does not create any internal structure.

A SAX parser serves the client application always only with pieces of the document at any given time whereas A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client.

A SAX parser, however, is much more space efficient in case of a big input document whereas DOM parser is rich in functionality.

Use a DOM Parser if you need to refer to different document areas before giving back the information. Use SAX is you just need unrelated nuclear information from different areas.

Xerces, Crimson are SAX Parsers whereas XercesDOM, SunDOM, OracleDOM are DOM parsers.

Q188. What is XSD ?show Answer

Ans. XSD or Xml Schema Definition is an extension of DTD. XSD is more powerful and extensible than DTD

Q189. What is JAXP ?show Answer

Ans. Stands for Java API for XML Processing. This provides a common interface for creating and using SAX, DOM, and XSLT APIs in Java regardless of which vendor’s implementation is actually being used.

Q190. What is JAXB ?show Answer

Ans. Stands for Java API for XML Binding. This standard defines a mechanism for writing out Java objects as XML and for creating Java objects from XML structures.

Q191. What are LDAP servers used for ?show Answer

Ans. LDAP servers are typically used in J2EE applications to authenticate and authorise users. LDAP servers are hierarchical and are optimized for read access, so likely to be faster than database in providing read access.

Q192. What is the difference between comparable and comparator in java.util pkg?show Answer

Ans. Comparable interface is used for single sequence sorting i.e.sorting the objects based on single data member where as comparator interface is used to sort the object based on multiple data members.

Q193. Difference between socket and servlet ?show Answer

Ans. servlet is a small, server-resident program that typically runs automatically in response to user input.
A network socket is an endpoint of an inter-process communication flow across a computer network.

We can think of it as a difference between door and gate. They are similar as they both are entry points but they are different as they are put up at different areas.

Sockets are for low-level network communication whereas Servlets are for implementing websites and web services

Q194. Difference Between this() and super() ?

show Answer

Ans. 1.this is a reference to the current object in which this keyword is used whereas super is a reference used to access members specific to the parent Class.

2.this is primarily used for accessing member variables if local variables have same name, for constructor chaining and for passing itself to some method whereas super is primarily used to initialize base class members within derived class constructor.



Q195. What is Java bytecode ?show Answer

Ans. “Java bytecode” is the usual name for the machine language of the Java Virtual
Machine. Java programs are compiled into Java bytecode, which can then be executed
by the JVM.


Q196. What is a Listener ?show Answer

Ans. In GUI programming, an object that can be registered to be notified when events of
some given type occur. The object is said to “listen” for the events.

Q197. What is unicode ?show Answer

Ans. A way of encoding characters as binary numbers. The Unicode character set includes
characters used in many languages, not just English. Unicode is the character set that is
used internally by Java.

Q198. What is ThreadFactory ?show Answer

Ans. ThreadFactory is an interface that is meant for creating threads instead of explicitly creating threads by calling new Thread(). Its an object that creates new threads on demand. Using thread factories removes hardwiring of calls to new Thread, enabling applications to use special thread subclasses, priorities, etc.

Q199. What is PermGen or Permanent Generation ?show Answer

Ans. The memory pool containing all the reflective data of the java virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas. The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application. In addition, Java SE library classes and methods may be stored here.

Q200. What is metaspace ?show Answer

Ans. The Permanent Generation (PermGen) space has completely been removed and is kind of replaced by a new space called Metaspace. The consequences of the PermGen removal is that obviously the PermSize and MaxPermSize JVM arguments are ignored and you will never get a java.lang.OutOfMemoryError: PermGen error.

Q201. What is the benefit of inner / nested classes ?show Answer

Ans. You can put related classes together as a single logical group.

Nested classes can access all class members of the enclosing class, which might be useful in certain cases.

Nested classes are sometimes useful for specific purposes. For example, anonymous inner classes are useful for writing simpler event-handling code with AWT/Swing.

Q202. Explain Static nested Classes ?show Answer

Ans. The accessibility (public, protected, etc.) of the static nested class is defined by the outer class.

A static nested class is not an inner class, it's a top-level nested class.

The name of the static nested class is expressed with OuterClassName.NestedClassName syntax.

When you define an inner nested class (or interface) inside an interface, the nested class is declared implicitly public and static.

Static nested classes can be declared abstract or final.

Static nested classes can extend another class or it can be used as a base class.

Static nested classes can have static members.

Static nested classes can access the members of the outer class (only static members, obviously).

The outer class can also access the members (even private members) of the nested class through an object of nested class. If you don’t declare an instance of the nested class, the outer class cannot access nested class elements directly.

Q203. Explain Inner Classes ?show Answer

Ans. The accessibility (public, protected, etc.) of the inner class is defined by the outer class.

Just like top-level classes, an inner class can extend a class or can implement interfaces. Similarly, an inner class can be extended by other classes, and an inner interface can be implemented or extended by other classes or interfaces.

An inner class can be declared final or abstract.

Inner classes can have inner classes, but you’ll have a hard time reading or understanding such complex nesting of classes.

Q204. Explain Method Local Inner Classes ?show Answer

Ans. You can create a non-static local class inside a body of code. Interfaces cannot have local classes, and you cannot create local interfaces.

Local classes are accessible only from the body of the code in which the class is defined. The local classes are completely inaccessible outside the body of the code in which the class is defined.

You can extend a class or implement interfaces while defining a local class.

A local class can access all the variables available in the body of the code in which it is defined. You can pass only final variables to a local inner class.

Q205. Explain about anonymous inner classes ?show Answer

Ans. Anonymous classes are defined in the new expression itself, so you cannot create multiple objects of an anonymous class.

You cannot explicitly extend a class or explicitly implement interfaces when defining an anonymous class.

An anonymous inner class is always created as part of a statement; don't forget to close the statement after the class definition with a curly brace. This is a rare case in Java, a curly brace followed by a semicolon.

Anonymous inner classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface

Q206. What will happen if class implement two interface having common method?show Answer

Ans. That would not be a problem as both are specifying the contract that implement class has to follow.
If class C implement interface A & interface B then Class C thing I need to implement print() because of interface A then again Class think I need to implement print() again because of interface B, it sees that there is already a method called test() implemented so it's satisfied.

Q207. What is the advantage of using arrays over variables ?show Answer

Ans. Arrays provide a structure wherein multiple values can be accessed using single reference and index. This helps in iterating over the values using loops.

Q208. What are the disadvantages of using arrays ?show Answer

Ans. Arrays are of fixed size and have to reserve memory prior to use. Hence if we don't know size in advance arrays are not recommended to use.

Arrays can store only homogeneous elements.

Arrays store its values in contentious memory location. Not suitable if the content is too large and needs to be distributed in memory.

There is no underlying data structure for arrays and no ready made method support for arrays, for every requriment we need to code explicitly

Q209. Difference between Class#getInstance() and new operator ?show Answer

Ans. Class.getInstance doesn't call the constructor whereas if we create an object using new operator , we need to have a matching constructor or copiler should provide a default constructor.

Q210. Can we create an object if a Class doesn't have any constructor ( not even the default provided by constructor ) ?show Answer

Ans. Yes , using Class.getInstance.

Q211. What is a cloneable interface and what all methods does it contain?
show Answer

Ans. It is not having any method because it is a MARKER interface.

Q212. When you will synchronize a piece of your code?show Answer

Ans. When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.

Q213. Are there any global variables in Java, which can be accessed by other part of your program?show Answer

Ans. No. Global variables are not allowed as it wont fit good with the concept of encapsulation.

Q214. What is an applet? What is the lifecycle of an applet?show Answer

Ans. Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.

Lifecycle methods of Applet -

init( ) method - Can be called when an applet is first loaded
start( ) method - Can be called each time an applet is started
paint( ) method - Can be called when the applet is minimized or maximized
stop( ) method - Can be used when the browser moves off the applet's page
destroy( ) method - Can be called when the browser is finished with the applet

Q215. What is meant by controls and what are different types of controls in AWT / SWT?show Answer

Ans. Controls are components that allow a user to interact with your application and SWT / AWT supports the following types of controls:

Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components.

These controls are subclasses of Component.

Q216. What is a stream and what are the types of Streams and classes of the Streams?show Answer

Ans. A Stream is an abstraction that either produces or consumes information. There are two types of Streams :

Byte Streams: Provide a convenient means for handling input and output of bytes.

Character Streams: Provide a convenient means for handling input & output of characters.

Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream.

Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer.

Q217. What is connection pooling?show Answer

Ans. It's a technique to allow multiple clients to make use of a cached set of shared and reusable connection objects providing access to a database or other resource.

Q218. Advantage of Collection classes over Arrays ?show Answer

Ans. Collections are re-sizable in nature. We can increase or decrease the size as per recruitment.
Collections can hold both homogeneous and heterogeneous data's.
Every collection follows some standard data structures.
Collection provides many useful built in methods for traversing,sorting and search.

Q219. What are the Disadvantages of using Collection Classes over Arrays ?show Answer

Ans. Collections can only hold objects, It can't hold primitive data types.

Collections have performance overheads as they deal with objects and offer dynamic memory expansion. This dynamic expansion could be a bigger overhead if the collection class needs consecutive memory location like Vectors.

Collections doesn't allow modification while traversal as it may lead to concurrentModificationException.


Q220. Can we call constructor explicitly ?show Answer

Ans. Yes.

Q221. Does a class inherit the constructor of its super class?show Answer

Ans. No.

Q222. What is the difference between float and double?show Answer

Ans. Float can represent up to 7 digits accurately after decimal point, where as double can represent up to 15 digits accurately after decimal point.

Q223. What is the difference between >> and >>>?show Answer

Ans. Both bitwise right shift operator ( >> ) and bitwise zero fill right shift operator ( >>> ) are used to shift the bits towards right. The difference is that >> will protect the sign bit whereas the >>> operator will not protect the sign bit. It always fills 0 in the sign bit.

Q224. What is the difference between System.out ,System.err and System.in?show Answer

Ans. System.out and System.err both represent the monitor by default and hence can be used to send data or results to the monitor. But System.out is used to display normal messages and results whereas System.err is used to display error messages and System.in represents InputStream object, which by default represents standard input device, i.e., keyboard.

Q225. Is it possible to compile and run a Java program without writing main( ) method?show Answer

Ans. Yes, it is possible by using a static block in the Java program.

Q226. What are different ways of object creation in Java ?show Answer

Ans. Using new operator - new xyzClass()
Using factory methods - xyzFactory.getInstance( )
Using newInstance( ) method - (Class.forName(“xyzClass”))emp.newInstance( )
By cloning an already available object - (xyzClass)obj1.clone( )



Q227. What is Generalization and Specialization in terms of casting ?show Answer

Ans. Generalization or UpCasting is a phenomenon where a sub class is prompted to a super class, and hence becomes more general. Generalization needs widening or up-casting. Specialization or DownCasting is a phenomenon where a super class is narrowed down to a sub class. Specialization needs narrowing or down-casting.

Q228. Can we call the garbage collector explicitly ?

show Answer

Ans. Yes, We can call garbage collector of JVM to delete any unused variables and unreferenced objects from memory using gc( ) method. This gc( ) method appears in both Runtime and System classes of java.lang package.

Q229. How does volatile affect code optimization by compiler?show Answer

Ans. Volatile is an instruction that the variables can be accessed by multiple threads and hence shouldn't be cached. As volatile variables are never cached and hence their retrieval cannot be optimized.

Q230. Do you think that Java should have had pointers ?show Answer

Ans. Open ended Questions.

Q231. How would you go about debugging a NullPointerException?show Answer

Ans. Open ended Questions.

Q232. How does Java differ from other programming languages you've worked with?show Answer

Ans. Open ended Questions.

Q233. Should good code be self-documenting, or is it the responsibility of the developer to document it?show Answer

Ans. Open ended Questions.

Q234. What are points to consider in terms of access modifier when we are overriding any method?show Answer

Ans. 1. Overriding method can not be more restrictive than the overridden method.

reason : in case of polymorphism , at object creation jvm look for actual runtime object. jvm does not look for reference type and while calling methods it look for overridden method.

If by means subclass were allowed to change the access modifier on the overriding method, then suddenly at runtime—when the JVM invokes the true object's version of the method rather than the reference type's version then it will be problematic

2. In case of subclass and superclass define in different package, we can override only those method which have public or protected access.

3. We can not override any private method because private methods can not be inherited and if method can not be inherited then method can not be overridden.

Q235. what is covariant return type? show Answer

Ans. co-variant return type states that return type of overriding method can be subtype of the return type declared in method of superclass. it has been introduced since jdk 1.5

Q236. How compiler handles the exceptions in overriding ?show Answer

Ans. 1)The overriding methods can throw any runtime Exception , here in the case of runtime exception overriding method (subclass method) should not worry about exception being thrown by superclass method.

2)If superclass method does not throw any exception then while overriding, the subclass method can not throw any new checked exception but it can throw any runtime exception

3) Different exceptions in java follow some hierarchy tree(inheritance). In this case , if superclass method throws any checked exception , then while overriding the method in subclass we can not throw any new checked exception or any checked exception which are higher in hierarchy than the exception thrown in superclass method

Q237. Why is Java considered Portable Language ?show Answer

Ans. Java is a portable-language because without any modification we can use Java byte-code in any platform(which supports Java). So this byte-code is portable and we can use in any other major platforms.

Q238. Tell something about history of Java ?show Answer

Ans. Java was initially found in 1991 by James Gosling, Sun Micro Systems. At first it was called as "Oak". In 1995 then it was later renamed to "Java". java is a originally a platform independent language. Currently Oracle, America owns Java.

Q239. How to find if JVM is 32 or 64 bit from Java program. ?
show Answer

Ans. You can find JVM - 32 bit or 64 bit by using System.getProperty() from Java program.

Q240. Does every class needs to have one non parameterized constructor ?show Answer

Ans. No. Every Class only needs to have one constructor - With parameters or without parameters. Compiler provides a default non parameterized constructor if no constructors is defined.

Q241. Difference between throw and throws ?show Answer

Ans. throw is used to explicitly throw an exception especially custom exceptions, whereas throws is used to declare that the method can throw an exception.

We cannot throw multiple exceptions using throw statement but we can declare that a method can throw multiple exceptions using throws and comma separator.

Q242. Can we use "this" within static method ? Why ?show Answer

Ans. No. Even though "this" would mean a reference to current object id the method gets called using object reference but "this" would mean an ambiguity if the same static method gets called using Class name.

Q243. Similarity and Difference between static block and static method ?show Answer

Ans. Both belong to the class as a whole and not to the individual objects. Static methods are explicitly called for execution whereas Static block gets executed when the Class gets loaded by the JVM.

Q244. What are the platforms supported by Java Programming Language?show Answer

Ans. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc


Q245. How Java provide high Performance ?show Answer

Ans. Java uses Just-In-Time compiler to enable high performance. Just-In-Time compiler is a program that turns Java bytecode into instructions that can be sent directly to the processor.

Q246. What is IDE ? List few Java IDE ?show Answer

Ans. IDE stands of Integrated Development Environment. Few Java IDE's are WSAD ( Websphhere Application Developer ) , RAD ( Rational Application Developer ) , Eclipse and Netbeans.

Q247. What is an Object ?show Answer

Ans. Object is a run time entity whose state is stored in fields and behavior is shown via methods. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.

Q248. What is a Class ?show Answer

Ans. A class is a blue print or Mold using which individual objects are created. A class can contain fields and methods to describe the behavior of an object.

Q249. According to Java Operator precedence, which operator is considered to be with highest precedence?show Answer

Ans. Postfix operators i.e () [] . is at the highest precedence.


Q250. What data type Variable can be used in a switch statement ?show Answer

Ans. Variables used in a switch statement can only be a byte, short, int, or char.


Q251. What are the sub classes of Exception class?show Answer

Ans. The Exception class has two main subclasses : IOException class and RuntimeException Class.


Q252. How finally used under Exception Handling?show Answer

Ans. The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.


Q253. What things should be kept in mind while creating your own exceptions in Java?show Answer

Ans. All exceptions must be a child of Throwable.

If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.

You want to write a runtime exception, you need to extend the RuntimeException class.


Q254. What is Comparable Interface?show Answer

Ans. It is used to sort collections and arrays of objects using the collections.sort() and java.utils. The objects of the class implementing the Comparable interface can be ordered.


Q255. Explain Set Interface?show Answer

Ans. It is a collection of element which cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.


Q256. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?show Answer

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


Q257. Which Java operator is right associative?show Answer

Ans. The = operator is right associative.


Q258. What is the difference between a break statement and a continue statement?show Answer

Ans. Break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.


Q259. What is the purpose of the System class?show Answer

Ans. The purpose of the System class is to provide access to system resources.


Q260. Variable of the boolean type is automatically initialized as?show Answer

Ans. The default value of the boolean type is false.


Q261. Can try statements be nested?show Answer

Ans. Yes


Q262. What will happen if static modifier is removed from the signature of the main method?show Answer

Ans. Program throws "NoSuchMethodError" error at runtime .


Q263. What is the Locale class?show Answer

Ans. The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region


Q264. Define Network Programming?show Answer

Ans. It refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.


Q265. What are the advantages and Disadvantages of Sockets ?show Answer

Ans. Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. It cause low network traffic.

Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.


Q266. What environment variables do I need to set on my machine in order to be able to run Java programs?
show Answer

Ans. CLASSPATH and PATH are the two variables.


Q267. What is Externalizable interface?show Answer

Ans. Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism.


Q268. What is the difference between the size and capacity of a Vector?show Answer

Ans. The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.


Q269. What is an enum or enumeration?show Answer

Ans. An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It allows sequential access to all the elements stored in the collection.


Q270. What is constructor chaining and how is it achieved in Java?

show Answer

Ans. A child object constructor always first needs to construct its parent. In Java it is done via an implicit call to the no-args constructor as the first statement

Q271. Why Java provides default constructor ?show Answer

Ans. At the beginning of an object's life, the Java virtual machine (JVM) allocates memory on the heap to accommodate the object's instance variables. When that memory is first allocated, however, the data it contains is unpredictable. If the memory were used as is, the behavior of the object would also be unpredictable. To guard against such a scenario, Java makes certain that memory is initialized, at least to predictable default values before it is used by any code.

Q272. In a case where there are no instance variables what does the default constructor initialize?show Answer

Ans. Java expects the superclass ( Object Class ) constructor to be called while creation of any object. So super constructor is called in case there are no instance variables to initialize.

Q273. Difference between Encapsulation and Data Hiding ?show Answer

Ans. Data Hiding is a broader concept. Encapsulation is a OOP's centri concept which is a way of data hiding in OOP's.

Q274. Difference between Abstraction and Implementation hiding ?show Answer

Ans. Implementation Hiding is a broader concept. Abstraction is a way of implementation hiding in OOP's.

Q275. What are the features of encapsulation ?show Answer

Ans. Combine the data of our application and its manipulation at one place.

Encapsulation Allow the state of an object to be accessed and modified through behaviors.

Reduce the coupling of modules and increase the cohesion inside them.


Q276. What are the examples of Abstraction in Java ?show Answer

Ans. function calling - hides implementation details
wrapper classes
new operator - Creates object in memory, calls constructor

Q277. What are different ways to create String Object? Explain.show Answer

Ans. String str = new String("abc");
String str1 = "abc";

When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.

When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool.


Q278. Write a method to check if input String is Palindrome?


show Answer

Ans. private static boolean isPalindrome(String str) {
if (str == null)
return false;
StringBuilder strBuilder = new StringBuilder(str);
strBuilder.reverse();
return strBuilder.toString().equals(str);
}

Q279. Write a method that will remove given character from the String?show Answer

Ans. private static String removeChar(String str, char c) {
if (str == null)
return null;
return str.replaceAll(Character.toString(c), "");
}


Q280. Which String class methods are used to make string upper case or lower case?show Answer

Ans. toUpperCase and toLowerCase

Q281. How to convert String to byte array and vice versa?show Answer

Ans. We can use String getBytes() method to convert String to byte array and we can use String constructor new String(byte[] arr) to convert byte array to String.

Q282. Why Char array is preferred over String for storing password?

show Answer

Ans. String is immutable in java and stored in String pool. Once it’s created it stays in the pool until unless garbage collected, so even though we are done with password it’s available in memory for longer duration and there is no way to avoid it. It’s a security risk because anyone having access to memory dump can find the password as clear text.

Q283. Why String is popular HashMap key in Java?
show Answer

Ans. Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.


Q284. What ate the getter and setter methods ?show Answer

Ans. getters and setters methods are used to store and manipulate the private variables in java beans. A getters as it has name, suggest retrieves the attribute of the same name. A setters are allows you to set the values of the attributes.

Q285. public class a {
public static void main(String args[]){
final String s1="job";
final String s2="seeker";
String s3=s1.concat(s2);
String s4="jobseeker";
System.out.println(s3==s4); // Output 1
System.out.println(s3.hashCode()==s4.hashCode()); Output 2
}
}

What will be the Output 1 and Output 2 ?show Answer

Ans. S3 and S4 are pointing to different memory location and hence Output 1 will be false.

Hash code is generated to be used as hash key in some of the collections in Java and is calculated using string characters and its length. As they both are same string literals, and hence their hashcode is same.Output 2 will be true.

Q286. What is the use of HashCode in objects ?show Answer

Ans. Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc.

Q287. Difference between Compositions and Inheritance ?show Answer

Ans. Inheritance means a object inheriting reusable properties of the base class. Compositions means that an abject holds other objects.

In Inheritance there is only one object in memory ( derived object ) whereas in Composition , parent object holds references of all composed objects.

From Design perspective - Inheritance is "is a" relationship among objects whereas Composition is "has a" relationship among objects.

Q288. Will finally be called always if all code has been kept in try block ?show Answer

Ans. The only time finally won't be called is if you call System.exit() or if the JVM crashes first.

Q289. Will the static block be executed in the following code ? Why ?

class Test
{
static
{
System.out.println("Why I am not executing ");
}
public static final int param=20;
}

public class Demo
{
public static void main(String[] args)
{
System.out.println(Test.param);
}
}show Answer

Ans. No the static block won't get executed as the referenced variable in the Test class is final. Compiler replaces the content of the final variable within Demo.main method and hence actually no reference to Test class is made.

Q290. Will static block for Test Class execute in the following code ?

class Test
{
static
{
System.out.println("Executing Static Block.");
}
public final int param=20;

public int getParam(){
return param;
}
}

public class Demo
{
public static void main(String[] args)
{
System.out.println(new Test().param);
}
}
show Answer

Ans. Yes.

Q291. What does String intern() method do?show Answer

Ans. intern() method keeps the string in an internal cache that is usually not garbage collected.

Q292. Will the following program display "Buggy Bread" ?

class Test{
static void display(){
System.out.println("Buggy Bread");
}
}

class Demo{
public static void main(String... args){
Test t = null;
t.display();
}
}show Answer

Ans. Yes. static method is not accessed by the instance of class. Either you call it by the class name or the reference.

Q293. How substring() method of String class create memory leaks?show Answer

Ans. substring method would build a new String object keeping a reference to the whole char array, to avoid copying it. Hence you can inadvertently keep a reference to a very big character array with just a one character string.

Q294. Write a program to reverse a string iteratively and recursively ?show Answer

Ans. Using String method -

new StringBuffer(str).reverse().toString();

Iterative -

public static String getReverseString(String str){
StringBuffer strBuffer = new StringBuffer(str.length);
for(int counter=str.length -1 ; counter>=0;counter--){
strBuffer.append(str.charAt(counter));
}
return strBuffer;
}

Recursive -

public static String getReverseString(String str){
if(str.length <= 1){
return str;
}
return (getReverseString(str.subString(1)) + str.charAt(0);
}

Q295. If you have access to a function that returns a random integer from one to five, write another function which returns a random integer from one to seven.show Answer

Ans. We can do that by pulling binary representation using 3 bits ( random(2) ).

getRandom7() {
String binaryStr = String.valuesOf(random(2))+String.valuesOf(random(2))+String.valuesOf(random(2));
binaryInt = Integer.valueOf(binaryStr);
int sumValue=0;
int multiple = 1;
while(binaryInt > 0){
binaryDigit = binaryInt%10;
binaryInt = binaryInt /10;
sumValue = sumValue + (binaryDigit * multiple);
multiple = multiple * 2;
}
}




Q296. Write a method to convert binary to a number ?show Answer

Ans. convert(int binaryInt) {
int sumValue=0;
int multiple = 1;
while(binaryInt > 0){
binaryDigit = binaryInt%10;
binaryInt = binaryInt /10;
sumValue = sumValue + (binaryDigit * multiple);
multiple = multiple * 2;
}
return sumValue;
}

Q297. What will the following code print ?

String s1 = "Buggy Bread";
String s2 = "Buggy Bread";
if(s1 == s2)
System.out.println("equal 1");
String n1 = new String("Buggy Bread");
String n2 = new String("Buggy Bread");
if(n1 == n2)
System.out.println("equal 2"); show Answer

Ans. equal 1

Q298. Difference between new operator and Class.forName().newInstance() ?show Answer

Ans. new operator is used to statically create an instance of object. newInstance() is used to create an object dynamically ( like if the class name needs to be picked from configuration file ). If you know what class needs to be initialized , new is the optimized way of instantiating Class.

Q299. What is Java bytecode ?show Answer

Ans. Java bytecode is the instruction set of the Java virtual machine. Each bytecode is composed by one, or two bytes that represent the instruction, along with zero or more bytes for passing parameters.

Q300. How to find whether a given integer is odd or even without use of modules operator in java?show Answer

Ans. public static void main(String ar[])
{
int n=5;
if((n/2)*2==n)
{
System.out.println("Even Number ");
}
else
{
System.out.println("Odd Number ");
}
}
}

Q301. Is JVM a overhead ? show Answer

Ans. Yes and No. JVM is an extra layer that translates Byte Code into Machine Code. So Comparing to languages like C, Java provides an additional layer of translating the Source Code.

C++ Compiler - Source Code --> Machine Code
Java Compiler - Source Code --> Byte Code , JVM - Byte Code --> Machine Code

Though it looks like an overhead but this additional translation allows Java to run Apps on all platforms as JVM provides the translation to the Machine code as per the underlying Operating System.




Q302. Can we use Ordered Set for performing Binary Search ?show Answer

Ans. We need to access values on the basis of an index in Binary search which is not possible with Sets.

Q303. What is Byte Code ? Why Java's intermediary Code is called Byte Code ?show Answer

Ans. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system. Its called Byte Code because each instruction is of 1-2 bytes.

Sample instructions in Byte Code -

1: istore_1
2: iload_1
3: sipush 1000
6: if_icmpge 44
9: iconst_2
10: istore_2

Q304. Difference between ArrayList and LinkedList ?show Answer

Ans. LinkedList and ArrayList are two different implementations of the List interface. LinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically resizing array.

Q305. If you are given a choice to use either ArrayList and LinkedList, Which one would you use and Why ?show Answer

Ans. ArrayList are implemented in memory as arrays and hence allows fast retrieval through indices but are costly if new elements are to be inserted in between other elements.

LinkedList allows for constant-time insertions or removals using iterators, but only sequential access of elements

1. Retrieval - If Elements are to be retrieved sequentially only, Linked List is preferred.
2. Insertion - If new Elements are to be inserted in between other elements , Array List is preferred.
3. Search - Binary Search and other optimized way of searching is not possible on Linked List.
4. Sorting - Initial sorting could be pain but lateral addition of elements in a sorted list is good with linked list.
5. Adding Elements - If sufficiently large elements needs to be added very frequently ,Linked List is preferable as elements don't need consecutive memory location.


Q306. What are the pre-requisite for the collection to perform Binary Search ?show Answer

Ans. 1. Collection should have an index for random access.
2. Collection should have ordered elements.

Q307. Can you provide some implementation of a Dictionary having large number of words ? show Answer

Ans. Simplest implementation we can have is a List wherein we can place ordered words and hence can perform Binary Search.

Other implementation with better search performance is to use HashMap with key as first character of the word and value as a LinkedList.

Further level up, we can have linked Hashmaps like ,

hashmap {
a ( key ) -> hashmap (key-aa , value (hashmap(key-aaa,value)
b ( key ) -> hashmap (key-ba , value (hashmap(key-baa,value)
....................................................................................
z( key ) -> hashmap (key-za , value (hashmap(key-zaa,value)
}

upto n levels ( where n is the average size of the word in dictionary.



Q308. Difference between PATH and CLASSPATH ?show Answer

Ans. PATH is the variable that holds the directories for the OS to look for executables. CLASSPATH is the variable that holds the directories for JVM to look for .class files ( Byte Code ).

Q309. Name few access and non access Class Modifiers ?show Answer

Ans. private , public and protected are access modifiers.

final and abstract are non access modifiers.

Q310. Which Java collection class can be used to maintain the entries in the order in which they were last accessed?show Answer

Ans. LinkedHashMap

Q311. Is it legal to initialize List like this ?


LinkedList l=new LinkedList(); show Answer

Ans. No, Generic parameters cannot be primitives.

Q312. Which of the following syntax is correct ?

import static java.lang.System.*;

or

static import java.lang.System.*;show Answer

Ans. import static java.lang.System.*;

Q313. What will be the output of following code ?

public static void main(String[] args)
{
int x = 10;
int y;
if (x < 100) y = x / 0;
if (x >= 100) y = x * 0;
System.out.println("The value of y is: " + y);
}show Answer

Ans. The code will not compile raising an error that the local variable y might not have been initialized. Unlike member variables, local variables are not automatically initialized to the default values for their declared type.

Q314. What will be the output of following Code ?

class BuggyBread {
public static void main(String[] args)
{
String s2 = "I am unique!";
String s5 = "I am unique!";

System.out.println(s2 == s5);
}
}show Answer

Ans. true, due to String Pool, both will point to a same String object.

Q315. What will be the output of following code ?

class BuggyBread2 {

private static int counter = 0;

void BuggyBread2() {
counter = 5;
}

BuggyBread2(int x){
counter = x;
}

public static void main(String[] args) {
BuggyBread2 bg = new BuggyBread2();
System.out.println(counter);
}
}show Answer

Ans. Compile time error as it won't find the constructor matching BuggyBread2(). Compiler won't provide default no argument constructor as programmer has already defined one constructor. Compiler will treat user defined BuggyBread2() as a method, as return type ( void ) has been specified for that.

Q316. What will be the output of following code ?

class BuggyBread1 {
public String method() {
return "Base Class - BuggyBread1";
}
}

class BuggyBread2 extends BuggyBread1{

private static int counter = 0;

public String method(int x) {
return "Derived Class - BuggyBread2";
}

public static void main(String[] args) {
BuggyBread1 bg = new BuggyBread2();
System.out.println(bg.method());
}
}
show Answer

Ans. Base Class - BuggyBread1

Though Base Class handler is having the object of Derived Class but its not overriding as now with a definition having an argument ,derived class will have both method () and method (int) and hence its overloading.

Q317. What are RESTful Web Services ?show Answer

Ans. REST or Representational State Transfer is a flexible architecture style for creating web services that recommends the following guidelines -

1. http for client server communication,
2. XML / JSON as formatiing language ,
3. Simple URI as address for the services and,
4. stateless communication.


Q318. Which markup languages can be used in restful web services ? show Answer

Ans. XML and JSON ( Javascript Object Notation ).

Q319. What is database deadlock ? How can we avoid them?show Answer

Ans. When multiple external resources are trying to access the DB locks and runs into cyclic wait, it may makes the DB unresponsive.

Deadlock can be avoided using variety of measures, Few listed below -

Can make a queue wherein we can verify and order the request to DB.

Less use of cursors as they lock the tables for long time.

Keeping the transaction smaller.





Q320. what will be the output of this code ?

public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Buggy");

test(s1);

System.out.println(s1);

}

private static void test(StringBuffer s){
s.append("Bread");
}show Answer

Ans. BuggyBread

Q321. what will be the output of this code ?

public static void main(String[] args)
{
String s1=new String("Buggy");

test(s1);

System.out.println(s1);

}

private static void test(StringBuffer s){
s.append("Bread");
}show Answer

Ans. Buggy

Q322. what will be the output of this code ?

public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Buggy");

test(s1);

System.out.println(s1);

}

private static void test(StringBuffer s){
s=new StringBuffer("Bread");
}show Answer

Ans. Buggy

Q323. what will be the output ?

class Animal {
public void eat() throws Exception {
}
}

class Dog2 extends Animal {
public void eat(){}
public static void main(){
Animal an = new Dog2();
an.eat();
}
}
show Answer

Ans. Compile Time Error: Unhandled exception type Exception

Q324. What are advantages of using Servlets over CGI ?show Answer

Ans. Better Performance as Servlets doesn't require a separate process for a single request.

Servlets are platform independent as they are written in Java.

Q325. Can we add duplicate keys in a HashMap ? What will happen if we attempt to add duplicate values ?show Answer

Ans. No, We cannot have duplicate keys in HashMap. If we attempt to do so , the previous value for the key is overwritten.

Q326. Can finally block throw an exception ?show Answer

Ans. Yes.

Q327. Can we have try and catch blocks within finally ?show Answer

Ans. Yes

Q328. Which of the following is a canonical path ?

1. C:\directory\..\directory\file.txt
2. C:\directory\subDirectory1\directory\file.txt
3. \directory\file.txtshow Answer

Ans. 2nd

Q329. What will the following code print when executed on Windows ?

public static void main(String[] args){
String parent = null;
File file = new File("/file.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer

Ans. \file.txt
C:\file.txt
C:\file.txt

Q330. What will be the output of following code ?

public static void main(String[] args){
String name = null;
File file = new File("/folder", name);
System.out.print(file.exists());
}show Answer

Ans. NullPointerException at line:

"File file = new File("/folder", name);"

Q331. What will be the output of following code ?

public static void main(String[] args){
String parent = null;
File file = new File(parent, "myfile.txt");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer

Ans. It will create the file myfile.txt in the current directory.

Q332. What will be the output of following code ?

public static void main(String[] args){
String child = null;
File file = new File("/folder", child);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer

Ans. NullPointerException at line:

File file = new File("/folder", child);

Q333. What will be the output of following code, assuming that currently we are in c:\Project ?

public static void main(String[] args){
String child = null;
File file = new File("../file.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer

Ans. ..\file.txt
C:\Workspace\Project\..\file.txt
C:\Workspace\file.txt

Q334. Which is the abstract parent class of FileWriter ?show Answer

Ans. OutputStreamWriter

Q335. Which class is used to read streams of characters from a file?show Answer

Ans. FileReader

Q336. Which class is used to read streams of raw bytes from a file?show Answer

Ans. FileInputStream

Q337. Which is the Parent class of FileInputStream ?show Answer

Ans. InputStream

Q338. Which of the following code is correct ?

a.


FileWriter fileWriter = new FileWriter("../file.txt");
File file = new File(fileWriter );
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter);

b.

BufferedWriter bufferedOutputWriter = new BufferedWriter("../file.txt");
File file = new File(bufferedOutputWriter );
FileWriter fileWriter = new FileWriter(file);


c.

File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter);

d.

File file = new File("../file.txt");
BufferedWriter bufferedOutputWriter = new BufferedWriter(file);
FileWriter fileWriter = new FileWriter(bufferedOutputWriter );show Answer

Ans. c.

File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter);

Q339. Which exception should be handled in the following code ?

File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);show Answer

Ans. IOException

Q340. Which exceptions should be handled with the following code ?

FileOutputStream fileOutputStream = new FileOutputStream(new File("newFile.txt"));show Answer

Ans. FileNotFoundException

Q341. Will this code compile fine ?

ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));show Answer

Ans. Yes.

Q342. What is the problem with this code ?

class BuggyBread1 {

private BuggyBread2 buggybread2;

public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}show Answer

Ans. Though we are trying to serialize BuggyBread1 object but we haven't declared the class to implement Serializable.

This will throw java.io.NotSerializableException upon execution.

Q343. Will this code run fine if BuggyBread2 doesn't implement Serializable interface ?

class BuggyBread1 implements Serializable{

private BuggyBread2 buggybread2 = new BuggyBread2();

public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}show Answer

Ans. No, It will throw java.io.NotSerializableException.

Q344. Will this code work fine if BuggyBread2 doesn't implement Serializable ?

class BuggyBread1 extends BuggyBread2 implements Serializable{

private int x = 5;

public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}show Answer

Ans. Yes.

Q345. Can we compose the Parent Class object like this ?

class BuggyBread1 extends BuggyBread2 {

private BuggyBread2 buggybread2;

public static void main(String[] args){
buggybread2 = new BuggyBread2();
}
}show Answer

Ans. Yes.

Q346. Will this code Work ? If not , Why ?

java.util.Calendar c = new java.util.Calendar();show Answer

Ans. No. It gives the error "Cannot Instantiate the type Calendar". Calendar is an abstract class and hence Calendar object should be instantiated using Calendar.getInstance().

Q347. Is java.util.Date an abstract Class ? Is java.util.Calendar an abstract Class ?show Answer

Ans. Date is not a abstract class whereas Calendar is.

Q348. What will the following code print ?

java.util.Calendar c = java.util.Calendar.getInstance();
c.add(Calendar.MONTH, 5);
System.out.println(c.getTime());show Answer

Ans. Date and Time after 5 months from now.

Q349. Which of the following code is correct ?

a. DateFormat df = DateFormat.getInstance();
b. DateFormat df = DateFormat.getDateInstance();
c. DateFormat df = DateFormat.getInstance(DateFormat.FULL);
d. DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);show Answer

Ans. All except c are correct.

Q350. What is the use of parse method in DateFormat ?show Answer

Ans. It is used to parse String to get the Date Object with initialized date.

Q351. Which of the following is not a valid java.util.Locale initialization ?

a. new Locale ()
b. new Locale ( String language )
c. new Locale ( String language , String country )show Answer

Ans. a i.e new Locale()

Q352. Which of the following is not a valid NumberFormat initialization ?

a. NumberFormat.getInstance()
b. NumberFormat.getDateInstance()
c. NumberFormat.getCurrencyInstance()
d. NumberFormat.getNumberInstance()show Answer

Ans. b i.e NumberFormat.getDateInstance()

Q353. What will the following code print ?

public static void main(String[] args){
Integer i1 = new Integer("1");
Integer i2 = new Integer("2");
Integer i3 = Integer.valueOf("3");
int i4 = i1 + i2 + i3;
System.out.println(i4);
}show Answer

Ans. 6

Q354. Which of the following syntax are correct ?

a. LinkedList l=new LinkedList();
b. List l=new LinkedList();
c. LinkedList l=new LinkedList();
d. List l = new LinkedList();show Answer

Ans. c and d are correct.

Q355. Which of the following code is correct ?

a. Date date = DateFormat.newInstance(DateFormat.LONG, Locale.US).parse(str);

b. Date date = DateFormat.newInstance(DateFormat.LONG, Locale.US).format(str);

c. Date date = DateFormat.getDateInstance(DateFormat.LONG, Locale.US).parse(str);show Answer

Ans. c

Q356. What's wrong with this code ?

public static void main(String[] args) {
String regex = "(\\w+)*";
String s = "Java is a programming language.";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.next()) {
System.out.println("The e-mail id is: " + matcher.group());
}
}show Answer

Ans. matcher.find() should have been used instead of matcher.next() within while.

Q357. Which methods of the Pattern class have equivalent methods in the String class? show Answer

Ans. split() and macthes()

Q358. Can we compare Integers by using equals() in Java ?show Answer

Ans. Yes for the Wrapper class Integer but not for the primitive int.

Q359. What is comparator interface used for ?show Answer

Ans. The purpose of comparator interface is to compare objects of the same class to identify the sorting order. Sorted Collection Classes ( TreeSet, TreeMap ) have been designed such to look for this method to identify the sorting order, that is why class need to implement Comparator interface to qualify its objects to be part of Sorted Collections.

Q360. Which are the sorted collections ?show Answer

Ans. TreeSet and TreeMap

Q361. What is rule regarding overriding equals and hasCode method ?show Answer

Ans. A Class must override the hashCode method if its overriding the equals method.

Q362. What is the difference between Collection and Collections ?show Answer

Ans. Collection is an interface whereas Collections is a utility class.

Q363. Is Java a statically typed or dynamically typed language ?show Answer

Ans. Statically typed

Q364. What do you mean by "Java is a statically typed language" ?show Answer

Ans. It means that the type of variables are checked at compile time in Java.The main advantage here is that all kinds of checking can be done by the compiler and hence will reduce bugs.

Q365. How can we reverse the order in the TreeMap ?show Answer

Ans. Using Collections.reverseOrder()

Map tree = new TreeMap(Collections.reverseOrder());

Q366. TreeMap orders the elements on which field ?show Answer

Ans. Keys

Q367. How TreeMap orders the elements if the Key is a String ?show Answer

Ans. As String implements Comparable, It refers to the String compareTo method to identify the order relationship among those elements.

Q368. Can we add heterogeneous elements into TreeMap ?show Answer

Ans. No, Sorted collections don't allow addition of heterogeneous elements as they are not comparable.

Q369. Will it create any problem if We add elements with key as user defined object into the TreeMap ?show Answer

Ans. It won't create any problem if the objects are comparable i.e we have that class implementing Comparable interface.

Q370. Can we null keys in TreeMap ?show Answer

Ans. No, results in exception.

Q371. Can value be null in TreeMap ?show Answer

Ans. Yes.

Q372. Which interface TreeMap implements ?show Answer

Ans. TreeMap implements NavigableMap, SortedMap, Serializable and Clonable.

Q373. What is a ConcurrentHashMap ?show Answer

Ans. ConcurrentHashMap is a hashMap that allows concurrent modifications from multiple threads as there can be multiple locks on the same hashmap.

Q374. What is the use of double checked locking in createInstance() of Singleton class?

Double checked locking code:
public static Singleton createInstance() {
if(singleton == null){
synchronized(Singleton.class) {
if(singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}


Single checked locking code:
public static Singleton createInstance() {
synchronized(Singleton.class) {
if(singleton == null) {
singleton = new Singleton();
}
}
return singleton;
}

What advantage does the first code offer compared to the second ?show Answer

Ans. In First Case , Lock for the synchronized block will be received only if
singleton == null whereas in second case every thread will acquire the lock before executing the code.

The problem of synchronization with singleton will only happen when the object has not be instantiated. Once instantiated , the check singleton == null will always generate true and the same object will be returned and hence no problem. First condition will make sure that synchronized access ( acquiring locks ) will only take place if the object has not been created so far.

Q375. Why are Getter and Setter better than directly changing and retrieving fields ?show Answer

Ans. 1. Methods can participate in runtime polymorphism whereas member variables cannot.

2. Validations can be performed before setting the variables.

3. If the input format changes , that can be absorbed by making change ( wrapping ) in the setter and getter.

Q376. Can we overload main method in Java ?show Answer

Ans. Yes, but the overloaded main methods without single String[] argument doesn't get any special status by the JVM. They are just another methods that needs to be called explicitly.

Q377. What are the various Auto Wiring types in Spring ?show Answer

Ans. By Name , By Type and Constructor.

Q378. Is It Good to use Reflection in an application ? Why ?show Answer

Ans. no, It's like challenging the design of application.

Q379. Why is Reflection slower ?show Answer

Ans. Because it has to inspect the metadata in the bytecode instead of just using precompiled addresses and constants.

Q380. What is the difference between ArrayList and LinkedList ?show Answer

Ans. Underlying data structure for ArrayList is Array whereas LinkedList is the linked list and hence have following differences -

1. ArrayList needs continuous memory locations and hence need to be moved to a bigger space if new elements are to be added to a filled array which is not required for LinkedList.

2. Removal and Insertion at specific place in ArrayList requires moving all elements and hence leads to O(n) insertions and removal whereas its constant O(1) for LinkedList.

3. Random access using index in ArrayList is faster than LinkedList which requires traversing the complete list through references.

4. Though Linear Search takes Similar Time for both, Binary Search using LinkedList requires creating new Model called Binary Search Tree which is slower but offers constant time insertion and deletion.

5. For a set of integers you want to sort using quicksort, it's probably faster to use an array; for a set of large structures you want to sort using selection sort, a linked list will be faster.

Q381. What is the difference between int[] x; and int x[]; ?show Answer

Ans. No Difference. Both are the acceptable ways to declare an array.

Q382. What are the annotations used in Junit with Junit4 ?show Answer

Ans. @Test

The Test annotation indicates that the public void method to which it is attached can be run as a test case.

@Before

The Before annotation indicates that this method must be executed before each test in the class, so as to execute some preconditions necessary for the test.

@BeforeClass

The BeforeClass annotation indicates that the static method to which is attached must be executed once and before all tests in the class.

@After

The After annotation indicates that this method gets executed after execution of each test.

@AfterClass

The AfterClass annotation can be used when a method needs to be executed after executing all the tests in a JUnit Test Case class so as to clean-up the set-up.

@Ignores

The Ignore annotation can be used when you want temporarily disable the execution of a specific test.

Q383. What is asynchronous I/O ?show Answer

Ans. It is a form of Input Output processing that permits other processing to continue before the I/O transmission has finished.

Q384. If there is a conflict between Base Class Method definition and Interface Default method definition, Which definition is Picked ?show Answer

Ans. Base Class Definition.

Q385. What are new features introduced with Java 8 ?show Answer

Ans. Lambda Expressions , Interface Default and Static Methods , Method Reference , Parameters Name , Optional , Streams, Concurrency.

Q386. Can we have a default method without a Body ?show Answer

Ans. No. Compiler will give error.

Q387. Does java allow implementation of multiple interfaces having Default methods with Same name and Signature ?show Answer

Ans. No. Compilation error.

Q388. What are Default Methods ?show Answer

Ans. With Java 8, We can provide method definitions in the Interfaces that gets carried down the classes implementing that interface in case they are not overridden by the Class. Keyword "default" is used to mark the default method.

Q389. Can we have a default method definition in the interface without specifying the keyword "default" ? show Answer

Ans. No. Compiler complains that its an abstract method and hence shouldn't have the body.

Q390. Can a class implement two Interfaces having default method with same name and signature ?

public interface DefaultMethodInterface {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface");
}
}

public interface DefaultMethodInterface2 {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface2");
}
}

public class HelloJava8 implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface defMethIn = new HelloJava8();
defMethIn.defaultMethod();
}
}show Answer

Ans. No. Compiler gives error saying "Duplicate Default Methods"



Q391. What If we make the method as abstract in another Interface ?

public interface DefaultMethodInterface {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface");
}
}

public interface DefaultMethodInterface2 {
public void defaultMethod(){
System.out.println("DefaultMethodInterface2");
}
}

public class HelloJava8 implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface defMethIn = new HelloJava8();
defMethIn.defaultMethod();
}
}show Answer

Ans. Even then the Compiler will give error saying that there is a conflict.

Q392. What if we override the conflicting method in the Class ?

public interface DefaultMethodInterface {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface");
}
}

public interface DefaultMethodInterface2 {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface2");
}
}

public class HelloJava8 implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface defMethIn = new HelloJava8();
defMethIn.defaultMethod();
}

public void defaultMethod(){
System.out.println("HelloJava8");
}
}show Answer

Ans. There won't be any error and upon execution the overriding class method will be executed.

Q393. What will happen if there is a default method conflict as mentioned above and we have specified the same signature method in the base class instead of overriding in the existing class ?

show Answer

Ans. There won't be any problem as the Base class method will have precedence over the Interface Default methods.

Q394. If a method definition has been specified in Class , its Base Class , and the interface which the class is implementing, Which definition will be picked if we try to access it using Interface Reference and Class object ? show Answer

Ans. Class method definition is overriding both the definitions and hence will be picked.

Q395. If a method definition has been specified in the Base Class and the interface which the class is implementing, Which definition will be picked if we try to access it using Interface Reference and Class object ? show Answer

Ans. Base Class Definition will have precedence over the Interface Default method definition.

Q396. Can we use static method definitions in Interfaces ?show Answer

Ans. Yes, Effective Java 8.

Q397. Can we access Interface static method using Interface references ?show Answer

Ans. No, only using Interface Name.

Q398. Can we have default method with same name and signature in the derived Interface as the static method in base Interface and vice versa ?show Answer

Ans. Yes , we can do that as static methods are not accessible using references and hence cannot lead to conflict. We cannot do inverse as Default methods cannot be overridden with the static methods in derived interface.

Q399. What is a Lambda Expression ? What's its use ?show Answer

Ans. Its an anonymous method without any declaration. Lambda Expression are useful to write shorthand Code and hence saves the effort of writing lengthy Code. It promotes Developer productivity, Better Readable and Reliable code.

Q400. Difference between Predicate, Supplier and Consumer ? show Answer

Ans. Predicate represents an anonymous function that accepts one argument and produces a result.

Supplier represents an anonymous function that accepts no argument and produces a result.

Consumer represents an anonymous function that accepts an argument and produces no result.

Q401. What does the following lambda expression means ?

helloJava8 ( x-> x%2 )show Answer

Ans. helloJava8 receives an Integer as argument and then returns the modulus of that Integer.

Q402. Write a program to see if the number is prefect number or not ?show Answer

Ans. http://www.c4learn.com/c-programs/program-to-check-whether-number-is.html

Q403. Difference between a Pointer and a Reference ?show Answer

Ans. We can't get the address of a reference like a pointer. Moreover we cannot perform pointer arithmetic with references.

Q404. Difference between TCP and UDP ?show Answer

Ans. http://www.cyberciti.biz/faq/key-differences-between-tcp-and-udp-protocols/

Q405. What things you would care about to improve the performance of Application if its identified that its DB communication that needs to be improved ?show Answer

Ans. 1. Query Optimization ( Query Rewriting , Prepared Statements )
2. Restructuring Indexes.
3. DB Caching Tuning ( if using ORM )
4. Identifying the problems ( if any ) with the ORM Strategy ( If using ORM )


Q406. Explain Singleton Design Pattern ?show Answer

Ans. http://www.buggybread.com/2014/03/java-design-pattern-singleton-interview.html

Q407. If I try to add Enum constants to a TreeSet, What sorting order will it use ?show Answer

Ans. Tree Set will sort the Values in the order in which Enum constants are declared.

Q408. Can we override compareTo method for Enumerations ?show Answer

Ans. No. compareTo method is declared final for the Enumerations and hence cannot be overriden. This has been intentionally done so that one cannot temper with the sorting order on the Enumeration which is the order in which Enum constants are declared.

Q409. How do you define a class of constants in Java?show Answer

Ans. Make the class as final.
Disable the object construction by making constructor private.
Keep only Static Final Variables declared and Defined at the same time.

Q410. What are the steps to be performed while coding Junit with Mocking framework ?show Answer

Ans. Initialize required objects for working with mocks and tested method
Set the mock behaviour on dependent objects
Execute the tested method
Perform assertions
Verify if a method is invoked or not


Q411. What will be the output of this code ?

Set mySet = new HashSet();
mySet.add("4567");
mySet.add("5678");
mySet.add("6789");
for(String s: mySet){
System.out.println(s);
}
show Answer

Ans. It will print 4567,5678 and 6789 but Order cannot be predicted.

Q412. What will be the output of this code ?

Set mySet = new TreeSet();
mySet.add("4567");
mySet.add("5678");
mySet.add("6789");
for(String s: mySet){
System.out.println(s);
}show Answer

Ans. 4567
5678
6789

Q413. What will be the output of this code ?

Set mySet = new HashSet();
mySet.add("4567");
mySet.add("5678");
mySet.add("6789");
System.out.println(s.get(0));
show Answer

Ans. This will give compile time error as we cannot retrieve the element from a specified index using Set. Set doesn't maintain elements in any order.

Q414. What will be the output of the following code ?

enum Day {

MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
}

public class BuggyBread1{

public static void main (String args[]) {
Set mySet = new HashSet();
mySet.add(Day.SATURDAY);
mySet.add(Day.WEDNESDAY);
mySet.add(Day.FRIDAY);
mySet.add(Day.WEDNESDAY);
for(Day d: mySet){
System.out.println(d);
}
}
}show Answer

Ans. FRIDAY, SATURDAY and WEDNESDAY will be printed but the order cannot be determined.

Only one FRIDAY will be printed as Set doesn't allow duplicates.

Order cannot be determined as HashSet doesn't maintain elements in any particular order.


Q415. enum Day {

MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
}


public class BuggyBread1{

public static void main (String args[]) {
Set mySet = new TreeSet();
mySet.add(Day.SATURDAY);
mySet.add(Day.WEDNESDAY);
mySet.add(Day.FRIDAY);
mySet.add(Day.WEDNESDAY);
for(Day d: mySet){
System.out.println(d);
}
}
}show Answer

Ans. WEDNESDAY
FRIDAY
SATURDAY


Only one FRIDAY will be printed as Set doesn't allow duplicates.

Elements will be printed in the order in which constants are declared in the Enum. TreeSet maintains the elements in the ascending order which is identified by the defined compareTo method. compareTo method in Enum has been defined such that the constant declared later are greater than the constants declared prior.

Q416. public class BuggyBread1{

public static void main (String args[]) {
Set mySet = new TreeSet();
mySet.add("1");
mySet.add("2");
mySet.add("111");
for(String d: mySet){
System.out.println(d);
}
}
}show Answer

Ans. 1
111
2

TreeSet maintains the elements in the ascending order which is identified by the compareTo method. compareTo method in String has been defined such that it results in the natural alphabetic Order. Here the elements in the TreeSet are of String and not of Integer. In String Natural Order, 111 comes before 2 as ascii of 1st character first determines the order.


Q417. public class BuggyBread1{

public static void main (String args[]) {
Set mySet = new TreeSet();
mySet.add(1);
mySet.add(2);
mySet.add(111);
for(Integer d: mySet){
System.out.println(d);
}
}
}show Answer

Ans. 1
2
111

TreeSet maintains the elements in the ascending order which is identified by the compareTo method. compareTo method in Integer has been defined such that it results in the natural numerical Order.

Q418. Can we extend an Enum ?show Answer

Ans. No. Enums are final by design.

Q419. Can I use different Java versions for building different Eclipse projects ?show Answer

Ans. Yes. We can assign different JRE System libraries by going to

Java Build Path -> Libraries

Q420. Which access specifiers can be used with top level class ?

a. public or default
b. public or private
c. public or protected
d. protected or default
show Answer

Ans. public or default


Q421. Which of the following can be marked static ?

a. Methods , Variables and Initialization Blocks.
b. Methods , Variables , Initialization Blocks and Outer Classes and nested Classes.
c. Methods , Variables , Initialization Blocks and Outer Classes.
d. Methods , Variables , Initialization Blocks and nested Classes
show Answer

Ans. Methods , Variables , Initialization Blocks and nested Classes


Q422. Which of the following cannot be marked static ?

a. Constructors , Classes ( Outer ) , Classes ( nested ), Interfaces , Local variables , Inner Class methods and instance variables.
b. Constructors , Classes ( Outer ) , Interfaces , Local variables , Class variables , Class Methods , Inner Class methods and instance variables.
c. Constructors , Classes ( Outer ) , Interfaces , Local variables , Inner Class methods and instance variables.
d. Constructors , Classes ( Outer ) , Classes (Nested), Interfaces , Local variables , Inner Class methods and instance variables
show Answer

Ans. Constructors , Classes ( Outer ) , Interfaces , Local variables , Inner Class methods and instance variables.


Q423. Which is of the following is NOT TRUE for JVM ?

a. JVM reads Byte Code and generates Machine Code.
b. JVM is a virtual Machine that acts as a intermediary between Java Application and Host Operating System.
c. JVM reads Source Code and generates Byte Code.
d. JVM acts as a translator that translates different Machine code ( on the basis of Host Machine ) for a common Byte Code.
show Answer

Ans. JVM reads Source Code and generates Byte Code.


Q424. Interface can only have ...

a. Member elements and Methods.
b. Static Variables and Static Methods.
c. Static Final Variables and Instance Method Declarations.
d. Member Elements , Instance Methods, Static variables and Static Methods.
show Answer

Ans. Static Final Variables and Instance Method Declarations.


Q425. Which of the following collection maintain its elements in Natural Sorted order ?

a. HashMap
b. TreeMap
c. LinkedHashMap
d. LinkedMap
show Answer

Ans. TreeMap


Q426. Which of the following collections stores its elements in insertion Order ?

a. HashMap
b. TreeMap
c. LinkedHashMap
d. LinkedMap
show Answer

Ans. LinkedHashMap


Q427. If we add Enum constants to a sorted collection ( Treemap , TreeSet ), What will be the order in which they will be maintained ?

a. Sorted Collection wont maintain them in any order.
b. Insertion Order
c. Order in which constants are declared.
d. Natural Sorting Order.
show Answer

Ans. Order in which constants are declared.


Q428. If we try to add duplicate key to the HashMap, What will happen ?

a. It will throw an exception.
b. It won't add the new Element without any exception.
c. The new element will replace the existing element.
d. Compiler will identify the problem and will throw an error.
show Answer

Ans. The new element will replace the existing element.


Q429. In what order the elements of a HashSet are retrieved ?

a. Random Order
b. Insertion Order
c. Natural Sorting Order
d. Inverse Natural Sorting Order
show Answer

Ans. Random Order


Q430. Which of the following is not type of inner classes ?

a. Simple Inner Class
b. Static Nested Inner Class
c. Method Nested Static Inner Class
d. Anonymous Inner Class
show Answer

Ans. Method Nested Static Inner Class


Q431. Which of the following was not introduced with Java 5 ?

a. Generics
b. Strings within Switch
c. Enums
d. Annotations
show Answer

Ans. Strings within Switch


Q432. Which interface does java.util.Hashtable implement ?

a. List
b. Set
c. Collection
d. Map
show Answer

Ans. Map


Q433. Which of the following is false ?

a. HashMap came before HashTable.
b. HashMap allows null values whereas Hashtable doesn’t allow null values.
c. HashTable and HashMap allow Key-Value pairs.
d. Hashtable is synchronized whereas HashMap is not.
show Answer

Ans. HashMap came before HashTable.


Q434. Which of the following is true ?

a. We can serialize static variables
b. We can serialize transient variables
c. We can serialize final variables
d. We can serialize instance methods
show Answer

Ans. We can serialize final variables


Q435. Which of the following is not the use of this keyword ?

a. Passing itself to another method
b. To call the static method
c. Referring to the instance variable when local variable has the same name
d. Calling another constructor in constructor chaining
show Answer

Ans. To call the static method


Q436. Which of the collections allows null as the key ?

a. HashTable
b. HashMap
c. TreeMap
d. LinkedHashMap
show Answer

Ans. HashTable


Q437. What is the initial state of a thread when it is created and started ?

a. Wait
b. Running
c. Ready
d. Sleep
show Answer

Ans. Ready


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

a. Wait
b. Ready
c. Dead
d. Running
show Answer

Ans. Dead


Q439. How many bits are used to represent Unicode ?

a. 8 bits
b. 16 bits
c. 24 bits
d. 32 bits
show Answer

Ans. 16 bits


Q440. Overridden methods must have the same ...

a. name
b. name and argument list
c. name, argument list, and return type
d. name, argument list, return type and belong to the same class
show Answer

Ans. name and argument list


Q441. Which of the following annotation is used to avoid executing Junits ?

a. @explicit
b. @ignore
c. @avoid
d. @NoTest
show Answer

Ans. @ignore


Q442. Which of the following is usually not part of EAR file ?

a. Server Configuration files
b. HTML and Media Files
c. Application Configuration files
d. Class files
show Answer

Ans. Server Configuration files


Q443. Which of the following file is called deployment descriptor ?

a. application.xml
b. project.xml
c. web.xml
d. build.xml
show Answer

Ans. web.xml


Q444. How can we execute a Java class independently if it doesn't have a static main method ?

a. By initiating the flow in any of the static method
b. By initiating the flow in any of static block
c. By initiating the flow in any other instance method named as main
d. By initiating the flow in any other instance method named as main and making it final
show Answer

Ans. By initiating the flow in any of static block


Q445. What is the size of long data type ?

a. 16 bit
b. 32 bit
c. 64 bit
d. 128 bit
show Answer

Ans. 64 bit


Q446. What is the size of double type ?

a. 16 bit
b. 32 bit
c. 64 bit
d. 128 bit
show Answer

Ans. 64 bit


Q447. What is the size of short type ?

a. 8 bit
b. 16 bit
c. 32 bit
d. 128 bit
show Answer

Ans. 16 bit


Q448. Which keyword is used to provide explicit access of a code block to single thread ?

a. Transient
b. Final
c. Explicit
d. Synchronized
show Answer

Ans. Synchronized


Q449. Which of the following exception is thrown when we try to access element which is beyond the size ?

a. NullPointerException
b. ArrayIndexOutOfBoundException
c. ArithmeticException
d. ParseException
show Answer

Ans. ArrayIndexOutOfBoundException


Q450. Checked exception needs to be ...

a. Caught
b. Method needs to declare that it throws these exception
c. Either A or B
d. Both A and B
show Answer

Ans. Either A or B


Q451. Collections.sort can only be performed on ..

a. Set
b. List
c. Map
d. Any Collection implementation
show Answer

Ans. List


Q452. Effective Java 6 , TreeMap implements ...

a. Map Interface
b. SortedMap Interface
c. NavigableMap Interface
d. SortedNavigableMap Interface
show Answer

Ans. SortedMap Interface


Q453. Which of the following is not possible ?

a. try block followed by catch
b. try block followed by finally
c. try block followed by catch block and then finally
d. try block without catch or finally block
show Answer

Ans. try block without catch or finally block


Q454. Which of the following is not the difference between Singleton and Static class ( Class with static members only ) ?

a. Only one object can be created for Singleton class whereas No objects are created for static class.
b. Singleton class instance is initiated using new keyword whereas static class instance is created using static method.
c. Singleton class can be serialized whereas Static class cannot be.
d. Singleton Class can participate in runtime Polymorphism whereas Static class cannot.
show Answer

Ans. Singleton class instance is initiated using new keyword whereas static class instance is created using static method.


Q455. Which of the following is false about main method ?

a. It should be declared public and static
b. it should have only 1 argument of type String array
c. We can override main method
d. We can overload main method
show Answer

Ans. We can override main method


Q456. Which of the following is false about Constructors ?

a. Constructor can be overloaded
b. A no argument constructor is provided by the compiler if we declare only constructors with arguments.
c. Constructors shouldn't have any return types , not even void.
d. If super is not explicitly called, still super() is intrinsically added by the compiler.
show Answer

Ans. A no argument constructor is provided by the compiler if we declare only constructors with arguments.


Q457. Variables of an interface are intrinsically ...

a. transient
b. final
c. public
d. static
show Answer

Ans. transient


Q458. Which of the following class creates mutable objects ?

a. Boolean
b. File
c. String
d. StringBuffer
show Answer

Ans. StringBuffer


Q459. Which of the following is not true for final variables ?

a. They cannot be changed after initialization
b. They can be initialized within static method
c. They can be declared and initialized together at the same place
d. They can be initialized within constructor
show Answer

Ans. They can be initialized within static method


Q460. Which of the following is false for final ?

a. Final methods cannot be overriden
b. Final methods cannot be overloaded
c. Final classes cannot be subclassed
d. Final class cannot be abstract
show Answer

Ans. Final methods cannot be overloaded


Q461. Invoking start twice on same thread leads to ..

a. ClassCastException
b. NullPointerException
c. InterruptedException
d. IllegalStateException
show Answer

Ans. IllegalStateException


Q462. Which of the following is false about var args ?

a. Var Args argument should have data type followed by three dots
b. Three dots should be consecutive and not separated by even space
c. We cannot have space before and after the dots
d. If there is a var args in the method, it should be only one and the last one.
show Answer

Ans. We cannot have space before and after the dots


Q463. Which of the following is not valid var args declaration ?

a. int sum (int... numbers)
b. int sum (.int .. numbers)
c. int sum (int ... numbers)
d. int sum (int x, int ... numbers)
show Answer

Ans. int sum (.int .. numbers)


Q464. Strings in switch were introduced in Which Java version ?

a. Java 5
b. Java 6
c. Java 7
d. Java
show Answer

Ans. Java 6


Q465. Which of the following doesn't extend Collection interface ?

a. Set
b. List
c. Map
d. Queue
show Answer

Ans. Map