Interview Questions and Answers for 'Java' | Search Interview Question - javasearch.buggybread.com
Javasearch.buggybread.com

Search Interview Questions


 More than 3000 questions in repository.
 There are more than 900 unanswered questions.
Click here and help us by providing the answer.
 Have a video suggestion.
Click Correct / Improve and please let us know.
Label / Company      Label / Company / Text

   



Interview Questions and Answers - Order By Newest

   next 30
 Q41. Which keyword is used to provide explicit access of a code block to single thread ?

a. Transient
b. Final
c. Explicit
d. Synchronized
Core Java
Ans. Synchronized

  Sample Code for Synchronized

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   threads   multithreading     Asked in 2 Companies      basic


Usually asked in relation to casting and ClassCastException.
 Q42. What is instanceOf operator ? Explain it's use ?Core Java
Ans. The operator instanceOf is used to verify if the specified object is the instance of specified class or interface.

Syntax if(x instanceOf ABC)

where x is an object reference and ABC could be a class name or interface name. The above statement will be true if x holds an object that is an instance of ABC or any of the child class of ABC or if x holds an object that implements ABC.

instanceOf operator is used to verify in case of downcasting. For ex -

DerivedClass extends BaseClass

x is the reference of BaseClass but holds DerivedClass object ( Polymorphism )

There is an operation that is defined in Derived Class, let's say derivedClassMethod()

We cannot call derivedClassMethod() directly using x as x is reference of BaseClass and not DerivedClass and hence can only access methods that are defined in BaseClass and overridden in derived class.

Though we can cast it to DerivedClass as following
((DerivedClass)x).derivedClassMethod();

But it may throw ClassCastException in case x doesn't hold an instance of DerivedClass at that point.

So before casting it to DerivedClass we may like to make sure that it is an instance of DerivedClass and hence won't throw ClassCastException.

So we make a check for it

if(x instanceOf DerivedClass) {
((DerivedClass)x).derivedClassMethod();
}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     instanceOf  instanceOf operator  Why we need instanceOf operator  use of instanceOf operator     Asked in 2 Companies      Intermediate        frequent


Very frequently asked. Favorite question in Walk in Drive of many Indian service companies.
  Q43. Difference between TreeMap and HashMap ?Core Java
Ans. They are different the way their elements are stored in memory. TreeMap stores the Keys in order whereas HashMap stores the key value pairs randomly.

  Sample Code for treemap

  Sample Code for hashmap

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   collections   map   treemap   hashmap   treemap vs hashmap     Asked in 31 Companies      basic        frequent

Try 1 Question(s) Test


 Q44. What are concepts introduced with Java 5 ?Core Java
Ans. Generics , Enums , Autoboxing , Annotations and Static Import.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   java5   generics   enum   autoboxing   annotations   static import        rare

Try 1 Question(s) Test


 Q45. Describe what happens when an object is created in Java ?Core Java
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   memory management   object creation   advanced   ebay


 Q46. What is session tracking and how do you track a user session in servlets?Java EE
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     j2ee   servlets   session   session management   web applications   cookies   httpsession   url rewriting   architecture     Asked in 1 Companies


Advanced level question usually asked to senior developers , leads and architects.
 Q47. How does volatile affect code optimization by compiler?Core Java
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   java keywords   volatile   synchronization   compiler optimization   variable caching   architecture     Asked in 3 Companies      expert


Advanced level question frequently asked in US based companies. Recently asked in EMC and Intuit.
  Q48. Can you provide some implementation of a Dictionary having large number of words ? Solution
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   collections   hashmap   binary search   search algorithm   advanced   architecture   data structure     Asked in 6 Companies        frequent

Try 1 Question(s) Test


Frequently asked to fresh graduates and less experienced.
 Q49. Why do we write public static void main ? Can we use some other syntax too for main ?Core Java
Ans. 1. public is the access modifier that makes the method accessible from anywhere, static is the keyword that makes it accessible even without creating any object, void means it doesn't return anything , String args[] is the array of argument that the method receives.

2. If we use main without the string args , it will compile correctly as Java will treat it as just another method. It wont be the method "main" which Java looks for when it looks to execute the class and hence will throw

Error: Main method not found in class , please define the main method as:
public static void main(String[] args)

3. Main is not a keyword but a special string that Java looks for while initiating the main thread.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   main method     Asked in 4 Companies      basic        frequent

Try 1 Question(s) Test


 Q50. What are the benefits of using Spring Framework ?Spring
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 is 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

  Sample Code for spring

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   spring framework   mvc   spring container   architecture   technical architect   java architect   technical lead  ioc     Asked in 2 Companies      basic        frequent


 Q51. Difference between Static and Singleton Class ?Core Java
Ans. 1. Static class is a class which cannot be instantiated and all its members are static whereas Singleton is the class that only permit creation of single object and then the object is reused.

2. As there is no object in Static class, it cannot participate in runtime Polymorphism.

3. As Static class doesnt allow creating objects and hence it cannot be serialized.

4. Static class body is initialized eagerly at application load time whereas Singleton object can be initiated eagerly using static blocks or lazily on first need.

5. Its not recommended to use pure static class as it fails to use many OOPs concepts.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     Static Class  Singleton  Static Class vs Singleton     Asked in 3 Companies      Intermediate        frequent


Very frequently asked in companies using SOA.
  Q52. What are RESTful Web Services ?Rest
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   web services   rest   java   j2ee  architecture     Asked in 14 Companies      intermediate        frequent


Frequently asked to experienced developers. Recently asked in many US interviews.
  Q53. What is database deadlock ? How can we avoid them?Database
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   database   architecture     Asked in 7 Companies      expert        frequent


 Q54. Can we declare static variables as transient ?Core Java
Ans. It's weird that compiler doesn't complain if we declare transient with static variable because it makes no sense. At least a warning message saying "transient is useless in this situation" would have helped with code cleaning.

Static variables are never serialized and transient is an indication that the specified variable shouldn't be serialized so its kind of double enforcement not to serialize.

It could be that as it makes no different to the variable behavior and hence using both keywords with a variable are permitted.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     static  transient  serialization     Asked in 1 Companies      expert        rare

Try 1 Question(s) Test


 Q55. Which of the following are valid declarations

1. void method(int... x){};
2. void method(int.. x){};
3. void method(int.. .x){};
4. void method(int ...x){};
5. void method(int... x){};
6. void method(int ... x){};
7. void method(int x, int... y){};
8. void method(int... x, int y){};
9. void method(int... x,int... y){};
Core Java
Ans. 1st is a valid and standard declaration.

2nd results in compilation error as only 2 dots are there.

3rd results in compilation error as three dots are not consecutive and broken.

4 through 6 may not be standard and ideal way of declarations but they are valid and will compile and work fine.

7 is valid declaration.

8 and 9 will result in compilation error as var args can only be provided to last argument.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     var args  methods  functions   method declaration  scjp  ocjp


 Q56. How is string object immutable if we can concat a string to it ?Core Java
Ans. Because it doesn't make the change in the existing string but would create a new string by concatenating the new string to previous string. So Original string won't get changed but a new string will be created. That is why when we say

str1.concat("Hello");

It means nothing because we haven't specified the reference to the new string and we have no way to access the new concatenated string. Accessing str1 with the above code will still give the original string.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     string  string immutable  immutability  string concat


 Q57. Difference between JVM, JRE and JDK ?Core Java
Ans. JDK(Java Development kit) = Development Kit comprising of JVM , library and development tools for developers

JRE (Java Run time Environment) - Comprise of JVM and set of libraries

JVM(Java Virtual Machine) = Interpreter which reads the .class file line by line.

When we install JDK, JRE also get installed so we can write,compile and excute our code. Used by developer. Without JDK we can only execute the program using JRE.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     jvm  jre  jdk  jvm vs jre vs jdk     Asked in 4 Companies


Very Frequently asked across all type of companies and across all levels.
  Q58. Difference between Public, Private, Default and Protected ?Core Java
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   oop   access specifier   public   private   default   protected   public vs private vs default vs protected     Asked in 12 Companies      basic        frequent

Try 1 Question(s) Test


 Q59. Does Constructor creates the object ?Core Java
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   constructor   object creation      intermediate        rare


 Q60. 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");
}
Core Java
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     string   string class   java   ==   object references   coding     Asked in 2 Companies      basic        frequent

Try 1 Question(s) Test


 Q61. Can constructors be synchronized in Java ?Core Java
Ans. No. Java doesn't allow multi thread access to object constructors so synchronization is not even needed.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     synchronization   synchronize   constructor   java   multithreading   yes-no   advanced     Asked in 1 Companies      expert        rare


Frequently asked question for intermediate developers. Frequently asked in HCL Technologies and EPAM.
  Q62. What is Volatile keyword used for ?Core Java
Ans. Volatile is a declaration that a variable can be accessed by multiple threads and hence shouldnt be cached.

  Sample Code for volatile

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   oops   synchronization   volatile   java keywords     Asked in 42 Companies      intermediate        frequent

Try 1 Question(s) Test


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

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   collections   arraylist   list   autoboxing   wrapper classes      expert        rare


Advanced level question. Recently asked in few Indian service companies ( Based on 3 inputs )
 Q64. What are various types of Class loaders used by JVM ?Core Java
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   jvm   memory management   class loaders   bootstrap   extensions   system  classloaders   advanced   technical lead   technical architect     Asked in 7 Companies


  Q65. Difference between SAX and DOM Parser ?Xml
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   xml   parsers   sax   dom parser   difference   architecture   technical lead   technical architect  markup language   sax vs dom     Asked in 14 Companies        frequent

Try 1 Question(s) Test


 Q66. How compiler handles the exceptions in overriding ?Core Java
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

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   overriding   exceptions   inheritence   inheritance  object oriented programming (oops)  oops concepts   oops


 Q67. What things should be kept in mind while creating your own exceptions in Java?Core Java
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   exceptions   exception handling   user defined exceptions   throwable   architecture   library development   technical architect   technical lead


Frequently asked to fresh graduates and less experienced.
  Q68. Difference between Composition and Inheritance ?Core Java
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   oops   oops concepts   inheritance  object oriented programming (oops)  oops concepts   composition  object oriented programming (oops)  oops concepts   difference between   basic interview question     Asked in 12 Companies      basic        frequent

Try 2 Question(s) Test


 Q69. How to find whether a given integer is odd or even without use of modulus operator in java?Core Java
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 ");
}
}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   code   coding   tricky questions   interesting questions   modulus operator     Asked in 4 Companies        frequent


 Q70. 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());
}
Core Java
Ans. NullPointerException

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

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   io   file   fileio   coding   code   file handling


previous 30   next 30

Help us and Others Improve. Please let us know the questions asked in any of your previous interview.

Any input from you will be highly appreciated and It will unlock the application for 10 more requests.

Company Name:
Questions Asked: