Core Java Interview Questions And Answers For Experienced Pdf

1. What is an interface?
Answer: Interfaces are core part of java programming language and used a lot not only in JDK but also java design patterns, most of the frameworks and tools. Interfaces provide a way to achieve abstraction in java and used to define the contract for the subclasses to implement.

Interfaces are good for starting point to define Type and create top-level hierarchy in our code. Since a Java class can implement multiple interfaces, it’s better to use interfaces as a superclass in most of the cases. Read more at the java interface.

2. What is a ternary operator in java? What is an interface?
Answer: Java ternary operator is the only conditional operator that takes three operands. It’s a one-liner replacement for if-then-else statement and used a lot in java programming. We can use ternary operator if-else conditions or even switch conditions using nested ternary operators. An example can be found at java ternary operator.

3. What is the difference between HashMap and HashTable? What is an interface?
Answer: Both collections implement Map. Both collections store value as key-value pairs. The key differences between the two are:
Hashmap is not synchronized in nature but hashtable is(thread-safe). This means that in a multithreaded application, only one thread can get access to a hashtable object and do an operation on it. Hashmap doesn’t guarantee such behavior and is not used in a multithreaded environment.
Hashmap is traversed using an iterator, hashtable can be traversed by enumerator or iterator.
Iterator in hashmap is fail-fast, enumerator in hashtable is not fail-fast
HashMap permits null values and only one null key, while Hashtable doesn’t allow key or value as null.
Since hashtable is synchronized, it is relatively slower in performance than hashmap.

4. What is the difference between abstract class and interface1? What is an interface?
Answer: A class is called abstract when it is declared with the keyword abstract. Abstract class contains at least one abstract method. It can also contain n numbers of concrete method. An interface can only contain abstract methods.
An interface can have only abstract methods. An abstract class can have concrete and abstract methods.
The abstract class can have public, private, protected or default variables and also constants. In the interface, the variable is by default public final. In nutshell, the interface doesn’t have any variables it only has constants.
A class can extend only one abstract class but a class can implement multiple interfaces. Abstract class doesn’t support multiple inheritances whereas interface does.
If an interface is implemented its mandatory to implement all of its methods but if an abstract class is extended its mandatory to implement all abstract methods.
The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement the new method(s) in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass.

5. What is the most important feature of Java? What is an interface?
Answer:
Java is a platform-independent language

6. What do you mean by platform independence? What is an interface?
Answer: Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux, Solaris, etc).

7. What is a Java applet1? What is an interface?
Answer:
The applet is a Java program.
The applet is designed for transmitting the Java code over the internet.
The execution works automatically by Java-enabled Web Browser.
The applet can respond to the user input.
It is dynamically programmed.

8. What is the difference between JVM and JRE? What is an interface?
Answer: Java Runtime Environment (JRE) is the implementation of JVM. JRE consists of JVM and java binaries and other classes to execute any program successfully. JRE doesn’t contain any development tools like java compiler, debugger, etc. If you want to execute any java program, you should have JRE installed. (E learning portal)

9. Which class is the superclass of all classes?
Answer:
java.lang.The object is the root class for all the java classes and we don’t need to extend it.

10. Why can’t I do myArray?length () ? Arrays are just objects, right?
Answer:  Yes, the specification says that arrays are object references just like classes are. You can even invoke the methods of Object such as toString () and hashCode () on an array. However, the length is a data item of an array and not a method. So you have to use myArray.length.

11. Does Java support Multiple Inheritances?
Answer:  When a class extends more than one classes then it is called multiple inheritances. Java doesn’t support multiple inheritances whereas C++ supports it, this is one of the differences between java and C++. Refer this:

12. What is a finally block? Is there a case when finally will not execute?
Answer:  Finally block is a block which always executes a set of statements. It is always associated with a try block regardless of any exception that occurs or not.
Yes, finally will not be executed if the program exits either by calling System.exit() or by causing a fatal error that causes the process to abort.

13. What is synchronization?
Answer:  Synchronization refers to multi-threading. A synchronized block of code can be executed by only one thread at a time. As Java supports execution of multiple threads, two or more threads may access the same fields or objects. Synchronization is a process which keeps all concurrent threads in execution to be in sync. Synchronization avoids memory consistency errors caused due to inconsistent view of shared memory. When a method is declared as synchronized the thread holds the monitor for that method’s object. If another thread is executing the synchronized method the thread is blocked until that thread releases the monitor.

14. What is Encapsulation?
Answer: Encapsulation means the localization of the information or knowledge within an object.
Encapsulation is also called as “Information Hiding”. Read it here in detail.

15. What are the default and parameterized constructors?
Answer:
Default: Constructors with no arguments are known as default constructors when you don’t declare any constructor in a class, the compiler creates a default one automatically.

Parameterized: Constructor with arguments are known as parameterized constructors.

16. Can a constructor call another constructor?
Answer:  Yes. A constructor can call another constructor of the same class using this keyword. For e.g. this() calls the default constructor.
Note: this() must be the first statement in the calling constructor.

17. Can a constructor call the constructor of parent class?
Answer:  Yes. In fact, it happens by default. A child class constructor always calls the parent class constructor. However, we can still call it using super keyword. For e.g. super() can be used for calling the superclass default constructor.

18. How do you identify if JVM is 32-bit or 64-bit from Java Program?
Answer: This can be identified by checking some system properties such as sun.arch.data.model or os.arch.

19. What is the difference between DOM and SAX parser in Java?
Answer: DOM parser loads the whole XML into memory to create a tree-based DOM model. This helps it quickly locate nodes and make a change in the structure of XML. SAX parser is an event-based parser and does not load the whole XML into memory.

For this reason, DOM is quicker than SAX but it needs more memory and is not fitting to parse large XML files.

20. Explain 5 features introduced in JDK 1.7?
Answer: try-with-resources statements free you from closing streams, and resources when you are finished with them, Java automatically closes this.
Fork-join pool to implement something like the Map-reduce pattern in Java, which allows String variable, and literal into switch statements.
Diamond operator for improving type inference, so there is no need to assert generic type on the right-hand side of variable declaration any longer, meaning the results are more clear and the code is more concise.
Improved exception handling, which lets you catch multiple exceptions in the same catch block.

21. Garbage collection in java?
Answer: Since objects are dynamically allocated by using the new operator, java handles the de-allocation of the memory automatically when no references to an object exist for a long time is called garbage collection. The whole purpose of Garbage collection is efficient memory management.

22. What is an exception?
Answer: Exceptions are abnormal conditions that arise during the execution of the program. It may occur due to wrong user input or wrong logic written by the programmer.

23. What are the types of exceptions?
Answer:
There are two types of exceptions: checked and unchecked exceptions.
Checked exceptions: These exceptions must be handled by programmer otherwise the program would throw a compilation error.
Unchecked exceptions: It is up to the programmer to write the code in such a way to avoid unchecked exceptions. You would not get a compilation error if you do not handle these exceptions. These exceptions occur at runtime.

24. What is the difference between Error and Exception?
Answer:

Error: Mostly a system issue. It always occurs at run time and must be resolved in order to proceed further.
Exception: Mostly an input data issue or wrong logic in code. Can occur at compile time or run time.

25. What is a Java Bean?
Answer: A JavaBean is a Java class that follows some simple conventions including conventions on the names of certain methods to get and set state called Introspection. Because it follows conventions, it can easily be processed by a software tool that connects Beans together at runtime. JavaBeans are reusable software components.

26. How can we create a thread in java?
Answer:
There are the following two ways of creating a thread:
1) By implementing the Runnable interface.
2) By Extending Thread class.

27. Preemptive scheduling vs. time slicing?
Answer:
1) Preemptive scheduling is prioritized. The highest priority process should always be a process that is currently utilized.
2) Time slicing means task executes for a defined slice/ period of time and then enter in the pool of ready state. The scheduler then determines which task execute next based on priority or another factor.

28. What is Starvation?
Answer: Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by “greedy” threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.

29. What’s the difference between Callable and Runnable?
Answer: Both of these are interfaces used to carry out the task to be executed by a thread. The main difference between the two interfaces is that Callable can return a value, while Runnable cannot. Another difference is that Callable can throw a checked exception, while Runnable cannot. Runnable has been around since Java 1.0, while Callable was introduced as part of Java 1.5.

30. What do the Thread?class methods run() and start() do?
Answer:

Thread.run() will execute in the calling thread, i.e. a new thread is not created, the code is executed synchronously. Thread.start() will execute the same code but in a new asynchronous thread.

31. How would you convert bytes to String?
Answer:
To convert bytes to String, you would use Strong constructor which accepts byte[].

However, you should be mindful of the right character encoding otherwise the platform’s default character encoding will be used, which may not necessarily be the same.

32. Is it possible to cast an int value into a byte variable? What would happen if the value of int is larger than byte?
Answer: Yes, it is possible but int is 32 bit long in Java, while byte is 8 bit long in Java. Therefore when you can cast an int to byte higher, 24 bits are gone and a byte can only hold a value between -128 to 128.

33. What is the difference between an object-oriented programming language and object-based programming language?
Answer: Object-based programming languages follow all the features of OOPs except Inheritance. Examples of object-based programming languages are JavaScript, VBScript, etc.

34. Name the different modules of the Spring framework?
Answer:
Some of the important Spring Framework modules are:

Spring Context – for dependency injection.
Spring AOP – for aspect-oriented programming.
Spring DAO – for database operations using DAO pattern
Spring JDBC – for JDBC and DataSource support.
Spring ORM – for ORM tools support such as Hibernate
Spring Web Module – for creating web applications.
Spring MVC – Model-View-Controller implementation for creating web applications, web services, etc.

35. Explain Bean in Spring and List the different Scopes of Spring bean?
Answer: Beans are objects that form the backbone of a Spring application. They are managed by the Spring IoC container. In other words, a bean is an object that is instantiated, assembled, and managed by a Spring IoC container.

There are five Scopes defined in Spring beans.
Singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.
Prototype: A new instance will be created every time the bean is requested.
Request: This is same as prototype scope, however, it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
Session: A new bean will be created for each HTTP session by the container.
Global-session: This is used to create global session beans for Portlet applications.

36. What is a static variable?
Answer:  static variable is used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students, etc.
static variable gets memory only once in class area at the time of class loading.

37. What is the difference between a factory and abstract factory pattern?
Answer: Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for the creation of different hierarchies of objects based on the type of factory. E.g. Abstract Factory extended by Automobile Factory, User Factory, Role Factory, etc. Each individual factory would be responsible for the creation of objects in that genre.

38. Differentiate JAR and WAR files?
Answer: Full form of JAR files is Java Archive Files.
Aggregating many files into one is allowed in JAR files
The JAR is usually used to hold Java classes in a library.
WAR files

Full form of WAR files is Web Archive Files.
XML, Java classes, and JavaServer Pages are stored in WAR
Mainly used for Web Application purposes.`

39. What is composition in Java?
Answer: a Composition is again a specialized form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object dose does not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of the relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different houses if we delete the house room will automatically delete.

In case you are facing any challenges with these java interview questions, please comment on your problems in the section below. Apart from this Java Interview Questions Blog, if you want to get trained from professionals on this technology.

40. What is an inner class in java?
Answer:  We can define a class inside a class and they are called nested classes. Any non-static nested class is known as an inner class. Inner classes are associated with the object of the class and they can access all the variables and methods of the outer class. Since inner classes are associated with the instance, we can’t have any static variables in them.

We can have a local inner class or anonymous inner class inside a class. For more details read java inner class.

41. Is Java platform independent?
Answer:  Yes. Java is a platform-independent language. We can write java code on one platform and run it on another platform. For e.g. we can write and compile the code on windows and can run it on Linux or any other supported platform. This is one of the main features of java.

42. How do you convert String to int in Java?
Answer: Java provides Integer.parseInt() method to parse a String to an int value. However, there is another way to do this, which takes advantage of the parsing logic of parseInt() method as well as caching offered by Flyweight design pattern, which makes it more efficient and useful.

43. What is a servlet?
Answer:  Java Servlet is server-side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.
The javax.servlet and javax.servlet.https packages provide interfaces and classes for writing our own servlets.
All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.
Most of the times, web applications are accessed using HTTP protocol and thats why we mostly extend HttpServlet class. Servlet API hierarchy is shown in the below image.

44. What are the differences between forwarding () method and sendRedirect() methods?
Answer:
Forward() method SendRedirect() method
forward() sends the same request to another resource. sendRedirect() method sends new request always because it uses the URL bar of the browser.
forward() method works at the server-side. sendRedirect() method works at client side.
forward() method works within the server only. sendRedirect() method works within and outside the server.

45. What is the life-cycle of a servile?
Answer:
There are 5 stages in the lifecycle of a servlet: LifeCycleServlet – Java Interview Questions

Servlet is loaded
Servlet is instantiated
Servlet is initialized
Service the request

46. Is String a datatype in Java?
Answer: The interviewer wanted an explanation which stated that String is not a primitive data type in Java; it is one of the most extensively used objects in Java, which is an instance of String class.

47. Explain the difference between the public, private, final, protected, and default modifiers?
Answer: These keywords – public, private, final, protected, and default modifiers – are to specify access levels for member variables, or for member functions (methods).

Public variables: these are variables that are noticeable to every class.
Private variables: these are variables that are noticeable only to the class to which they fit in.
Protected variables: these are variables that are noticeable only to the class to which they fit in, as well as any other relevant subclasses.
The decision to use private, protected, or public variables can be difficult. It is a question of whether or not an external object (or program), actually needs direct access to the information.

If you prefer to have other objects to access internal data, but want to control it at the same time, you would make it either private or protected. However, be mindful of delivering functions which can affect the data in an organized way.

Although David mentions it isn’t fair to place too much emphasis on the protected and default modifiers and exactly what they mean. Though extra credit could be assumed for why and which circumstances you would use these.

Note: Browse latest Java Interview Questions and JAVA Tutorial Videos. Here you can check Java training details and JAVA Training Videos for self learning. Contact +91 988 502 2027 for more information.

Leave a Comment

Scroll to Top