Which is the Best Java Web Framework ?

500 Java / J2EE Interview Questions and Answers


Ans. A cookie is a small piece of text stored on a user's computer by the browser for a specific domain. Commonly used for authentication, storing site preferences, and server session identification.




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

Ans. No

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

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

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

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

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

Q7. What is servlet Chaining ?show Answer

Ans. Multiple servlets serving the request in chain.

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

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

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

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

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

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

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

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

Q15. What is a Final Variable ?show Answer

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

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

Ans. java.lang.StringBuffer.

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

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

Ans. Java.util.Map

Q19. What is an Iterator?show Answer

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

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

Ans. java.util.map

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




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

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

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

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

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

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

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

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

Q28. Does Java provides default copy constructor ?show Answer

Ans. No

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

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

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

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

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



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

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

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

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

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


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

Q38. What are transient variables in java?show Answer

Ans. Transient variables are variable that cannot be serialized.

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

Q40. What are wrapper classes ?show Answer

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

Q41. What is the difference between time slicing and preemptive scheduling ?show Answer

Ans. In preemptive scheduling, highest priority task continues execution till it enters a not running state or a higher priority task comes into existence. In time slicing, the task continues its execution for a predefined period of time and reenters the pool of ready tasks.

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

Ans. Ready state.

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

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

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


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

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

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

Ans. Code segment.

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

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

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

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

Ans. Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

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

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

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

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

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

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

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

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

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

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

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

Q64. What is JSON ?show Answer

Ans. JSON is "JavaScript Object Notation", primarily used for client-server or server-server communication. Its a much lighter and readable alternative to XML. JSON is language independent and is easily parse-able in all programming languages.

Q65. What is the role of JSON.stringify ?show Answer

Ans. JSON.stringify() turns an object into a JSON text and stores that JSON text in a string.

So If we stringfy above notation , it will become

{"name":"xyz","gender":"male";"age":30}

Q66. When were Enums introduced in Java ?show Answer

Ans. Enums were introduced with java 5.

Q67. Which function is used to convert a JSON text into an object ?show Answer

Ans. eval

Q68. Which data types are supported by JSON ?show Answer

Ans. Number
String
Boolean
Array
Object
null

Q69. What are the benefits of JSON over XML ?show Answer

Ans. Lighter and faster than XML as on-the-wire data format
Object Representation - Information is presented in object notations and hence better understandable. Easy to parse and conversion to objects for information consumption.
Support multiple data types - JSON supports string, number, array, boolean whereas XML data are all string.


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

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

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

Q73. Which MVC is struts2 based on ?show Answer

Ans. MVC2

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

Q75. What is URL?show Answer

Ans. URL is Uniform Resource Locator which is representation of HTTP address.

Q76. Explain features of struts2 ?show Answer

Ans. 1) It is an Action based MVC based framework which has adopt mvc2.

2) Struts2 is a pull-MVC (or MVC2) framework where action takes the role of the model rather than the controller. The “pull” concepts means views ability to pull data from an action, rather than having a separate model object available.

3) The Model View-Controller pattern in Struts2 is implemented with five core components – actions, interceptors, value stack / OGNL, result types and results / view technologies.

4) XML configuration as well as Annotation option available.

5) POJO based action available so we can write test cases easily.

6) Integration with Spring, tiles and OGNL based expression langugae.

7) Theme based tag libraries integrated with struts tag as well as support of Ajax tag.

8) Can have various view options like jsp, velocity, freemarker etc.

9) We can embed plugin through which we can modify and extend framework features.

Q77. What is HTTP ?show Answer

Ans. HTTP or Hypertext Transfer Protocol is internet protocol for tranmission of hypertext ( text with meta data ) over internet.

Q78. what is content negotiation?show Answer

Ans. Suppose we want to visit a site for any information, information can be represented in different languages like English,German or may be other and their format for presentation can also differ from HTML to PDF or may be Plain text. In this case when an client makes an HTTP request to a server, client can also specify the media types here. Client can specify what it can accept back from host and on the basis of availability the host will return to the client. This is called content negotiation because client and server negotiated on the language and format of the content to be shared.

Q79. Is tomcat an application or Web server ?show Answer

Ans. Application server.

Q80. Is Apache an application or Web server ?show Answer

Ans. Web server.

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

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

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

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


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

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


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

}


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


Q89. What are meta Annotations ?show Answer

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

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


Q91. How to display and set the Class path in Unix ?show Answer

Ans. To display the current CLASSPATH variable, use these commands in UNIX (Bourne shell):

% echo $CLASSPATH

To delete the current contents of the CLASSPATH variable,

In UNIX: % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable,

In UNIX: % CLASSPATH=/home/george/java/classes; export CLASSPATH


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

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

Q94. Difference between Vector and ArrayList ?show Answer

Ans. Vectors are synchronized whereas Array lists are not.

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

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

Q97. What is Serialization ?show Answer

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

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

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

Q99. What is a final variable ?show Answer

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

Q100. What is a Final Method ?show Answer

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

Q101. What is a Final Class ?show Answer

Ans. A Class that cannot be sub classed.

Q102. What is an Immutable Object ?show Answer

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

Q103. What is an immutable class ?show Answer

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

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


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

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


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

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

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

Ans. No.

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

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

Q111. Name few Java Exceptions ?show Answer

Ans. IndexOutofBound , NoClassDefFound , OutOfMemory , IllegalArgument.

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

Ans. Inheritence.

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

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

Q115. What is "super" used for ?show Answer

Ans. Used to access members of the base class.

Q116. What is "this" keyword used for ?show Answer

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

Q117. Difference between boolean and Boolean ?show Answer

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

Q118. What is a finalize method ?show Answer

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

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

Q120. Is runnable a Marker interface ?show Answer

Ans. No , it has run method declared.

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

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

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

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

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

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

Q127. What Design pattern Wrapper Classes implement ?show Answer

Ans. Adapter.

Q128. What is "Import" used for ?show Answer

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

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

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

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

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

Ans. No.

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

Q133. Difference between StringBuffer and StringBuilder ?show Answer

Ans. StringBuffer is synchronized whereas StringBuilder is not.

Q134. Difference between Map and HashMap ?show Answer

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

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

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

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

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

Q139. How can we manage Error Messages in the web application ?show Answer

Ans. Within message.properties file.

Q140. Is JVM, a compiler or interpretor ?show Answer

Ans. Its an interpretor.

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

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

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

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

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

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

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

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

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

Q150. Example of Chain of Responsibility Design Pattern ?show Answer

Ans. Exception Handling Throw mechanism.

Q151. Example of Observer Design Pattern ?show Answer

Ans. Listeners.

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

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

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

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

Q156. What is a Default Constructor ?show Answer

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

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

Q158. Can we overload constructors ?show Answer

Ans. Yes.

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

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

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

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

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

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

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

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

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

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

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

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

Q167. What is exception propogation ?show Answer

Ans. Passing the exception object to the calling method.

Q168. Difference between nested and inner classes ?show Answer

Ans. Inner classes are non static nested classes.

Q169. What is a nested interface ?show Answer

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

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


Q171. Difference between serializable and externalizable interface ?show Answer

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

Q172. What is reflection ?show Answer

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

Q173. Can we instantiate the object of derived class if parent constructor is protected ?show Answer

Ans. No

Q174. Can we declare an abstract method private ?show Answer

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

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

Q176. What is a config Object? show Answer

Ans. The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet. This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file location.

Q177. What is a pageContext Object? show Answer

Ans. The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page. This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope.

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

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

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

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

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

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

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

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

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

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

Q187. 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++.



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

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

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

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

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

Ans. sockets, RMI. EJB

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

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

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

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

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

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

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

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

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

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

Ans. JProbe, OptimizeIt

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

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

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


Q206. What is XML ?show Answer

Ans. XML or eXtensible Markup Language is a markup languages for describing data and its metadata.

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

Q208. What is DTD ?show Answer

Ans. DTD or Document Type Definition is a standard agreed upon way of communication between two parties. Your application can use a standard DTD to verify that data that you receive
from the outside world is valid and can be parsed by your parser.

Q209. What is XSD ?show Answer

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

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

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

Q212. What is marshalling ?show Answer

Ans. Its the process of creating XML structures out of Java Objects.

Q213. What is unmarshalling ?show Answer

Ans. Its the process of creating Java Objects out of XML structures.

Q214. Which load testing tools have you used ?show Answer

Ans. Rational Robot, JMeter, LoadRunner.

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

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

Q217. What are different modules of spring ?show Answer

Ans. There are seven core modules in spring

Spring MVC
The Core container
O/R mapping
DAO
Application context
Aspect Oriented Programming or AOP
Web module


Q218. Explain Flow of Spring MVC ?show Answer

Ans. The DispatcherServlet configured in web.xml file receives the request.

The DispatcherServlet finds the appropriate Controller with the help of HandlerMapping and then invokes associated Controller.

Then the Controller executes the logic business logic and then returns ModeAndView object to the DispatcherServlet.

The DispatcherServlet determines the view from the ModelAndView object.

Then the DispatcherServlet passes the model object to the View.

The View is rendered and the Dispatcher Servlet sends the output to the Servlet container. Finally Servlet Container sends the result back to the user.

Q219. What is Spring configuration file?show Answer

Ans. Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.

Q220. Q: What is default scope of bean in Spring framework?show Answer

Ans. The default scope of bean is Sing leton for Spring framework.

Q221. What bean scopes does Spring support? Explain them.show Answer

Ans. The Spring Framework supports following five scopes -

Singleton
prototype
request
session
global-session



Q222. What is bean auto wiring?show Answer

Ans. The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory without using and elements.

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

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



Q225. What are the phases of the JSP life cycle ?show Answer

Ans. Translation of JSP Page

Compilation of JSP Page

Classloading (class file is loaded by the classloader)

Instantiation (Object of the Generated Servlet is created).

Initialization ( jspInit() method is invoked by the container).

Reqeust processing ( _jspService() method is invoked by the container).

Destroy ( jspDestroy() method is invoked by the container).

Q226. Difference between the jsp scriptlet tag and jsp declaration tag?show Answer

Ans. The jsp scriptlet tag can only declare variables not methods whereas jsp declaration tag can declare
variables as well as methods.

The declaration of scriptlet tag is placed inside the _jspService() method whereas The declaration of jsp declaration tag is placed outside the _jspService() method.

Q227. What are JSP directives ? What are different types of directives ?show Answer

Ans. The jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet.

There are three types of directives -

• page directive
• include directive
• taglib directive



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


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

Q230. What is MVC ? show Answer

Ans. The Model/View/Controller pattern, a strategy for dividing responsibility in a GUI component. The model is the data for the component. The view is the visual presentation of the component on the screen. The controller is responsible for reacting to events by changing the model. According to the MVC pattern, these responsibilities should be handled by different objects.

Q231. What is race condition ?show Answer

Ans. A source of possible errors in parallel programming, where one thread can cause an error in another thread by changing some aspect of the state of the program that the second thread is depending on (such as the value of variable).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Q252. What is session tracking and how do you track a user session in servlets?show Answer

Ans. Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are:

User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password

Hidden form fields - fields are added to an HTML form that are not displayed in the client's browser. When the form containing the fields is submitted, the fields are sent back to the server

URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change.

Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser.

HttpSession- places a limit on the number of sessions that can exist in memory.

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

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

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


Q256. Can we call constructor explicitly ?show Answer

Ans. Yes.

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

Ans. No.

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

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

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

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

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



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

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

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

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

Ans. Open ended Questions.

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

Ans. Open ended Questions.

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

Ans. Open ended Questions.

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

Ans. Open ended Questions.

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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


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


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

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


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


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


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


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


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


Q293. What are use cases?show Answer

Ans. It is part of the analysis of a program and describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance.


Q294. Which Java operator is right associative?show Answer

Ans. The = operator is right associative.


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


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

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


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

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


Q298. Can try statements be nested?show Answer

Ans. Yes


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

Ans. Program throws "NoSuchMethodError" error at runtime .


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


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


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


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


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


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


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


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

Q308. What is the best practice configuration usage for files - pom.xml or settings.xml ?show Answer

Ans. The best practice guideline between settings.xml and pom.xml is that configurations in settings.xml must be specific to the current user and that pom.xml configurations are specific to the project.

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

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

Q311. How can I change the default location of the generated jar when I command "mvn package"?show Answer

Ans. By default, the location of the generated jar is in ${project.build.directory} or in your target directory. We can change this by configuring the outputDirectory of maven-jar-plugin.

Q312. What is Maven's order of inheritance?show Answer

Ans. 1. parent pom
2. project pom
3. settings
4. CLI parameters


Q313. What is a Mojo?show Answer

Ans. A mojo is a Maven plain Old Java Object. Each mojo is an executable goal in Maven, and a plugin is a distribution of one or more related mojos.

Q314. How do I determine which POM contains missing transitive dependency?show Answer

Ans. run mvn -X

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

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

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


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

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


Q320. 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);
}

Q321. 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), "");
}


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

Ans. toUpperCase and toLowerCase

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

Q336. 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);
}

Q337. 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;
}
}




Q338. 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;
}

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

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

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

Q342. 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 ");
}
}
}

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




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

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

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

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


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

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



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

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

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

Ans. LinkedHashMap

Q353. Is it legal to initialize List like this ?


LinkedList l=new LinkedList();
show Answer

Ans. No, Generic parameters cannot be primitives.

Q354. 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.*;

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

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

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

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

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


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

Ans. XML and JSON ( Javascript Object Notation ).

Q361. Difference between Inner and Outer Join ?show Answer

Ans. Inner join is the intersection of two tables on a particular columns whereas Outer Join is the Union of two tables.





Q362. What is a Cursor ?show Answer

Ans. It's a facility that allows traversal over the records pulled from a table or combination of tables. Its like iterator in Java.

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





Q364. What are temp tables ?show Answer

Ans. These are the tables that are created temporarily and are deleted once the Stored Procedure is complete.

For example - we may like to pull some info from a table and then do some operations on that data and then store the output in final output table. We can store the intermediary values in a temp table and once we have final output with us, we can just delete it.

Q365. Why Web services use HTTP as the communication protocol ?show Answer

Ans. With the advent of Internet, HTTP is the most preferred way of communication. Most of the clients ( web thin client , web thick clients , mobile apps ) are designed to communicate using http only. Web Services using http makes them accessible from vast variety of client applications.

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

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

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

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

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

Q371. gfddddddddddddddddddddddddshow Answer

Ans. gfhhhhhhhhhhhhhhhhhhhhf

Q372. Does SQL allow null values ? Can we use it within Where clause ?show Answer

Ans. Yes , we can have null values for columns in SQL. Null value represent that the columns value is unknown or haven't been filled. Yes, We can use it within where clause to get the rows with null values.

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

Q374. What is the use of HTTPSession in relation to http protocol ?show Answer

Ans. http protocol on its own is stateless. So it helps in identifying the relationship between multiple stateless request as they come from a single source.

Q375. Why using cookie to store session info is a better idea than just using session info in the request ?show Answer

Ans. Session info in the request can be intercepted and hence a vulnerability. Cookie can be read and write by respective domain only and make sure that right session information is being passed by the client.

Q376. What are different types of cookies ?show Answer

Ans. Session cookies , which are deleted once the session is over.

Permanent cookies , which stays at client PC even if the session is disconnected.

Q377. http protocol is by default ... ?show Answer

Ans. stateless

Q378. Can finally block throw an exception ?show Answer

Ans. Yes.

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

Ans. Yes

Q380. Which of the following is a canonical path ?

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

Ans. 2nd

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

Q382. 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);"

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

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

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

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

Ans. OutputStreamWriter

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

Ans. FileReader

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

Ans. FileInputStream

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

Ans. InputStream

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

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

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

Ans. IOException

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

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

Ans. FileNotFoundException

Q393. Will this code compile fine ?

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

Ans. Yes.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Ans. split() and macthes()

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

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

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

Q412. Which are the sorted collections ?show Answer

Ans. TreeSet and TreeMap

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

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

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

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

Ans. Statically typed

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

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

Ans. Using Collections.reverseOrder()

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

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

Ans. Keys

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

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

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

Q422. Can we null keys in TreeMap ?show Answer

Ans. No, results in exception.

Q423. Can value be null in TreeMap ?show Answer

Ans. Yes.

Q424. Which interface TreeMap implements ?show Answer

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

Q425. Do we have form beans in Struts 2 ?show Answer

Ans. No, because they are not longer required. As action classes are no more singleton in Struts 2, user inputs can be captured in action itself.

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

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

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

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

Q430. What the Bean scopes provided by Spring ?show Answer

Ans. Singleton , Prototype , Request , Session , global-session

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

Ans. By Name , By Type and Constructor.

Q432. Difference between first level and second level cache in hibernate ?show Answer

Ans. 1. First level cache is enabled by default whereas Second level cache needs to be enabled explicitly.

2. First level Cache came with Hibernate 1.0 whereas Second level cache came with Hibernate 3.0.

3. First level Cache is Session specific whereas Second level cache is shared by sessions that is why First level cache is considered local and second level cache is considered global.

Q433. What are the the methods to clear cache in Hibernate ?show Answer

Ans. Evict() and clear(). Evist is used to clear a particular object from the cache whereas clear clears the complete local cache.

Q434. What are different types of second level cache ?show Answer

Ans. 1. EHCache ( Easy Hibernate )
2. OSCache ( Open Symphony )
3. Swarm Cache ( JBoss )
4. Tree Cache ( JBoss )

Q435. Can we disable first level cache ? What should one do if we don't want an object to be cached ?show Answer

Ans. No.We can either call evict after the object retrieval or can use separate sessions.

Q436. How to configure second level cache in Hibernate ?show Answer

Ans. 1. Configure Provider class in Hibernate configuration file.

2. Add Cache usage tag ( read-only or read-write ) in mapping files ( hbm ).

3. Create an XML file called ehcache.xml and place in classpath which contains time settings and update settings, behavior of cache , lifetime and idletime of Pojos, how many objects are allowed.

Q437. What is Hibernate ?show Answer

Ans. Hibernate is a Java ORM Framework.

Q438. What are the advantages of Hibernate ?show Answer

Ans. 1. No need to know SQL, RDBMS, and DB Schema.
2. Underlying Database can be changed without much effort by changing SQL dialect and DB connection.
3.Improved Performance by means of Caching.


Q439. What are the different types of inheritance in Hibernate ?show Answer

Ans. Table Per Class , Table per Sub Class , Table per Concrete Class

Q440. What is the purpose of dialect configured in Hibernate configuration file ?show Answer

Ans. It tells the framework which SQL varient to generate.

Q441. Please specify in what sequence the objects of following classes will be created ?

Session , SessionFactory, Query , Configuration
show Answer

Ans. Configuration -> SessionFactory -> Session -> Query

Q442. What are different types of associations in Hibernate ?show Answer

Ans. There are 4 types of associations in Hibernate

One to One
One to Many
Many to One
Many to Many



Q443. What are the configuration files in Hibernate ?show Answer

Ans. hibernate.cfg.xml ( Main Configuration File )

and *.hbm.xml files ( Mapping Files )

Q444. What are the contents of Hibernate configuration file ( hibernate.cfg.xml ) ?show Answer

Ans. HBM Files ( Mapping )
DB Connection ( DB Connection String , User Name , Password , Pool Size )
SQL Dialect ( SQL variant to be generated )
Show SQL ( Show / No show SQL on Console )
Auto Commit ( True / False )

Q445. What are the Core Interfaces of Hibernate Framework ? show Answer

Ans. Configuration
SessionFactory
Session
Transaction
Query and Citeria


Q446. What are collection types in Hibernate ?show Answer

Ans. Bag, Set , List , Array, Map

Q447. Difference between load and get ?show Answer

Ans. If id doesn't exist in the DB load throws an exception whereas get returns null in that case.

get makes the call to DB immediately whereas load makes the call to proxy.

Q448. What is lazy fetching in Hibernate ?show Answer

Ans. Lazy fetching is the technique of not loading the child objects when parent objects are loaded. By default Hibernate does not load child objects. One can specify whether to load them or not while doing the association.

Q449. Different types of Hibernate Instance States ?show Answer

Ans. Transient - In this state, an instance is not associated with any persistence context
Persistent - In this state, an instance is associated with a persistence context
Detached - This is a state for an instance which was previously associated with a persistence context an has been currently closed dissociated

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

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

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

Q452. When should we use prototype scope and singleton scope for beans ?show Answer

Ans. We should use singleton scope for beans when they are stateless and prototype when they are stateful.

Q453. Difference between Assert and Verify ?show Answer

Ans. Assert works only if assertions ( -ea ) are enabled which is not required for Verify.

Assert throws an exception and hence doesn't continue with the test if assert evaluates to false whereas it's not so with Verify.

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

Q455. Which class elements are not persisted ?show Answer

Ans. Static and Transient.

Q456. Which annotations are used in Hibernate ?show Answer

Ans. @Entity
@Table
@Id
@Column
@Temporal
@Basic
@Enumerated
@Access
@Embeddable
@Lob
@AttributeOverride
@Embedded
@GeneratedValue
@ElementCollection
@JoinTable
@JoinColumn
@CollectionId
@GenericGenerator
@OneToOne
@OneToMany
@ManyToOne
@ManyToMany
@NotFound

Q457. What entries we make in the hibernate config file if we are not using hbm files but Annotations ?show Answer

Ans. We configure Entity classes having annotated mappings.

Q458. How many SessionFactory and Session objects are created ?show Answer

Ans. Single SessionFactory object and multiple session objects for opening different session. Hibernate creates new Session object per thread.

Q459. What is the way to rollback transaction if something goes wrong using hibernate API ? show Answer

Ans. We can have the code calling Hibernate API within try block and can have transaction.rollback within Catch.

Q460. What is the use of hbm2ddl Configuration in Hibernate ?show Answer

Ans. This configuration specifies if hibernate should creates the Schema / Table on its own if the respective table is not found.

"update" doesn't create the table if it's not found whereas configuration set as "create" creates the schema automatically.

Q461. What is the difference between these 2 annotations ?

@Entity

@Entity ( name="EMPLOYEES" )
show Answer

Ans. The first annotation will try to map the Class with the Table as of same name as Class whereas the second annotation will specify the Entity name as "EMPLOYEES" and hence will try to map with Table Name "EMPLOYEES".

Q462. "What is the difference between these 2 annotations ?

@Entity ( name ="EMPLOYEES")

@Entity
@Table ( name=""EMPLOYEES"" )

@Entity ( name="EMP")
@Table ( name="EMPLPYEES" )
show Answer

Ans. First Annotation will set the Entity name as EMPLOYEES and hence will try to map with the same Table name.

The second annotation will make the Entity mapped to table EMPLOYEES irrespective of the Entity Name ( which is class name in this case ).

Third Annotations will set the different names for Enitity and Table and will explicitly map them.

Q463. What are the different ID generating strategies using @GeneratedValue annotation ?show Answer

Ans. Auto , Identity , Sequence and Table.

Q464. How to do Eager loading in Hibernate ?show Answer

Ans. Using

lazy = false in hibernate config file

or

@Basic(fetch=FetchType.EAGER) at the mapping

Q465. What is Lazy Initialization in Hibernate ?show Answer

Ans. It's a feature to lazily initialize dependencies , relationship and associations from the Database. Any related references marked as @OneToMany or @ManyToMany are loaded lazily i.e when they are accessed and not when the parent is loaded.

Q466. What are the ways to avoid LazyInitializationException ?show Answer

Ans. 1. Set lazy=false in the hibernate config file.

2. Set @Basic(fetch=FetchType.EAGER) at the mapping.

3. Make sure that we are accessing the dependent objects before closing the session.

4. Using Fetch Join in HQL.

Q467. What is cascade ?show Answer

Ans. Instead of Saving Parent as well as Child Entities individually , Hibernate provides the option to persist / delete the related entities when the Parent is persisted.

Q468. What are the different Cascade types ?show Answer

Ans. Detach, Merge , Persist , Remove , Refresh

Q469. Which type of associated Entities are Eagerly loaded by Default ?show Answer

Ans. OneToOne

Q470. After which Hibernate version , related Entities are initialized lazily ?show Answer

Ans. After Hibernate 3.0

Q471. Can we declare Entity class as final ?show Answer

Ans. Yes but as Hibernate creates the Proxy Classes inherited from the Entity Classes to communicate with Database for lazy initialization. Declaring entity classes as final will prohibit communication with database lazily and hence will be a performance hit.

Q472. What are the restrictions for the entity classes ?show Answer

Ans. 1. Entity classes should have default constructor.

2. Entity classes should be declared non final.

3. All elements to be persisted should be declared private and should have public getters and setters in the Java Bean style.

4. All classes should have an ID that maps to Primary Key for the table.

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

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

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

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

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

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

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

Ans. No. Compiler will give error.

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

Ans. No. Compilation error.

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

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

Q482. 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"



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

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

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

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

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

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

Ans. Yes, Effective Java 8.

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

Ans. No, only using Interface Name.

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

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

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

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

Q494. What is the difference between namenode and datanode in Hadoop? show Answer

Ans. NameNode stores MetaData (No of Blocks, On Which Rack which DataNode is stored etc) whereas the DataNode stores the actual Data.

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

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

Q497. Difference between TCP and UDP ?show Answer

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

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


Q499. Explain Singleton Design Pattern ?show Answer

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

Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus




×

Try our new Java Interview Questions Search Tool.

There are more than 1000 questions with practice tests.

It's updated daily and It's Awesome.


×

Try our new Java Practice Test tool.

There are more than 200 questions and expanding quickly. It's updated daily and It's Awesome.