*Friday CLOSED

Timings 10.00 am - 08.00 pm

Call : 021-3455-6664, 0312-216-9325 DHA 021-35344-600, 03333808376, ISB 03333808376

Java Interview Questions and Answers in Canada, Toronto, Calgary

image_pdfSave PDFimage_printPrint
Java Interview  Q&A

Top Java Interview Questions and Answers

These are expert-created Java interview questions to help you excel in your Java interview. Here you will learn Java advantages, inheritance, class, enumeration, iterator, JSON, abstract class, transient and volatile variables, HTTP tunneling, hibernate in Java, and more. Learn Java from Omni Academy Java Training to excel in your career!

Top Answers to Java Interview Questions

1. What do you understand by Java?

  • Java is an object-oriented computer language.
  • It is a high-level programming language developed by James Gosling in Sun Microsystems in the year 1995.
  • Java is a fast, secure, and reliable language used for many games, devices, and applications.

2. Compare between Java and Python.

CriteriaJavaPython
Ease of useGoodExcellent
Speed of codingAverageExcellent
Data typesStatic typedDynamically typed
Data Science and Machine Learning applicationsAverageExcellent

3. Outline the major Java features.

  • Object-oriented: Java is based on object-oriented programming where the class and methods describe the state and behavior of an object.
  • Portable: A Java program gets converted into Java bytecodes that can be executed on any platform without any dependency.
  • Platform independent: Java works on the ‘write once, run anywhere’ principle as it supports multiple platforms like Windows, Linux, Mac, Sun Solaris, etc.
  • Robust: Java has strong memory management as there are no pointer allocations. It has an automatic garbage collection that prohibits memory leaks.
  • Interpreted: As mentioned, Java compiler converts the codes into Java bytecodes which are then interpreted and executed by Java Interpreter.

Become a master of Java by enrolling in this online Java Course!

4. What do you mean by an object?

An object consists of methods and classes that depict its state and perform operations. A Java program contains a lot of objects instructing each other their jobs. This concept is part of core Java.

5. What is a class in Java?

Java encapsulates codes in various classes that define new data types. These new data types are used to create objects.

6. Differentiate between JDK, JRE, and JVM.

  • JVM stands for Java Virtual Machine which provides the runtime environment for Java bytecodes to be executed.
  • JRE (Java Runtime Environment) includes the sets of files required by JVM during runtime.
  • JDK (Java Development Kit) consists of JRE along with the development tools required to write and execute a program.

Get a clear idea of why to get certified in Java!

7. Define inheritance.

Java includes the feature of inheritance which is an object-oriented programming concept. Inheritance lets a derived class inherit the methods of a base class.

8. Explain method overloading.

When a Java program contains more than one method with the same name but with different properties, then it is called method overloading.

9. Compare overloading with overriding.

Overloading refers to the case of having two methods of the same name but different properties; whereas, overriding occurs when there are two methods of the same name and properties, but one is in the child class and the other is in the parent class.

10. Explain the creation of a thread-safe singleton in Java using double-checked locking.

Singleton is created with the double-checked locking as before Java 5 acts as a broker and it’s been possible to have multiple instances of singleton when multiple threads create an instance of the singleton at the same time. Java 5 made it easy to create thread-safe singleton using Enum. Using a volatile variable is essential for the same.

11. Distinguish between StringBuffer and StringBuilder in Java programming.

StringBufferStringBuilder
StringBuffer methods are synchronized.StringBuilder is non-synchronized.
The storage area is heap and modified easily.Storage is heap and can be modified.
StringBuffer is thread-safe.StringBuilder is fast as it is not thread-safe.
The performance is very slow.The performance is very fast.

12. Differentiate between an ArrayList and a Vector.

ArrayListVector
An ArrayList is not synchronized.A vector is synchronized.
An ArrayList is fast.A vector is slow as it is thread-safe.
If an element is inserted into an ArrayList, it increases its array size by 50 percent.A vector defaults to doubling the size of its array.
An ArrayList does not define the increment size.A vector defines the increment size.
An ArrayList can only use Iterator for traversing.Except for hashtable, a vector is the only other class that uses both Enumeration and Iterator.

13. Mention the difference between Iterator and Enumeration.

Iterator Enumeration
Iterator is an interface found in the java.util package.Enumeration is an object that generates elements one at a time.
Uses three methods to interface:hasNext()next()remove()Uses two methods:hasMoreElements()nextElement()
Iterators allow removing elements from the given collection during the iteration with well-defined semantics.It is used for passing through a collection, usually of unknown size.
Iterator method names have been improved.The traversing of elements can only be done once per creation.

14. Explain the difference between the inner class and the subclass.

Inner ClassSubclass
An inner class is a class that is nested within another class.A subclass is a class that inherits from another class called the superclass.
It provides the access rights for the class which is nesting it and that can access all variables and methods defined in the outer class.It provides access to all public and protected methods and fields of its superclass.

15. Can we execute any code, even before the main method? Explain.

Yes, we can execute any code, even before the main method. We will be using a static block of code in the class when creating the objects at load time of the class. Any statements within this static block of code will get executed at once while loading the class, even before the creation of objects in the main method.

16. How can we restrict inheritance for a class?

We can restrict inheritance for a class by the following steps:

  1. By using the final keyword
  2. If we make all methods final, then we cannot override that
  3. By using private constructors
  4. By using the Javadoc comment (//)

17. Java doesn’t support multiple inheritance. Why?

Java doesn’t support multiple inheritance because we cannot use different methods in one class; it creates an ambiguity.
Example:

class  Omni Academy 1
{
void test()
{
system.out.println("test() method");
}
}class Omni Academy 2
{
void test()
{
system.out.println("test() method");
}
}Multiple inheritance
class C extends  Omni Academy 1, Omni Academy2
{
………………………………………….
…………………………………………..
}

Intellipaat1 and Intellipaat2 test() methods are inheriting to class C. So, which test() method class C will take?

As Intellipaat1 and Intellipaat2 class test () methods are different, here we would face ambiguity.

18. Are constructors inherited? Can a subclass call the parent’s class constructor?

We cannot inherit a constructor. We create an instance of a subclass using a constructor of one of its superclasses. Because overriding the superclass constructor is not our wish as if we override a superclass constructor, then we will destroy the encapsulation abilities of the language.

19. Define JSON.

The expansion of JSON is ‘JavaScript Object Notation.’ It is a much lighter and readable alternative to XML. It is independent and easily parse-able in all programming languages. It is primarily used for client–server and server–server communication.

20. What are the advantages of JSON over XML?

The advantages of JSON over XML are:

  1.  JSON is lighter and faster than XML.
  2.  It is easily understandable.
  3.  It is easy to parse and convert to objects for information consumption.
  4. JSON supports multiple data types—string, number, array, or Boolean—but XML data are all strings.

21. Name the methods of an object class.

  • clone(): This method helps create and return a copy of an object.
  • equals(): This method helps compare.
  • finalize(): It is called by the garbage collector on the object.
  • getClass(): It allows us to return the runtime class of the object.
  • hashCode(): This method helps return a hash code value for the object.
  • toString(): It lets us return a string representation of the object.
  • notify(), notifyAll(), and wait(): These help in synchronizing the activities of the independently running threads in a program.

22. Define content negotiation.

If we have visited a website to search for information, we will get the information in different languages and in different formats. When a client makes an HTTP request to a server, the client can also specify the media types here. The client can specify what it can accept back from the host, and on the basis of availability the host will return to the client. This is known as content negotiation because the client and the server negotiate on the language and format of the content to be shared.

23. Can we import the same package/class twice? Will the JVM load the package twice at runtime?

A package or class can be inherited multiple times in a program code. JVM and compiler will not create any issue. Moreover, JVM automatically loads the class internally once, regardless of times it is called in the program.

24. Define an abstract class.

A class that contains the abstract keyword in its declaration is known as an abstract class. It can have abstract and non-abstract methods (method with a body).

  1.  This class can have public, private, protected, or constants and default variables.
  2.  It needs to be extended and its method needs to be implemented. It cannot be instantiated.
  3.  If a class has at least one abstract method, then the class must be declared abstract.

25. Describe annotations.

  • Java annotation is a tag that symbolizes the metadata associated with class, interface, methods, fields, etc.
  • Annotations do not directly influence operations.
  • The additional information carried by annotations is utilized by Java compiler and JVM.

26. Java doesn’t use pointers. Why?

Pointers are susceptible and slightly carelessness in their use which may result in memory problems, and hence Java basically manages their use.

This blog will help you get a better understanding of Mobile Technology for Android and iOS using Java!

27. Distinguish between static loading and dynamic class loading.

  • Static loading: In static loading, classes are loaded statically with the operator ‘new.’
  • Dynamic class loading: It is a technique for programmatically invoking the functions of a class loader at runtime. The syntax for this is as follows:
Class.forName (Test className);

28. Struts 1 classes are not thread-safe, whereas Struts 2 classes are thread-safe. Why?

Struts 1 actions are singleton. So, all threads operate on the single action object and hence make 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 it is thread-safe.

29. Define JAXP and JAXB.

JAXP: It stands for Java API for XML Processing. This provides a common interface for creating and using DOM, SAX, and XSLT APIs in Java regardless of which vendor’s implementation is actually being used.
JAXB: It stands for Java API for XML Binding. This standard defines a system for a script out of Java objects as XML and for creating Java objects from XML structures.

30. Define an enumeration?

Usually, we call enumeration as an enum. An enumeration is an interface containing methods for accessing the original data structure from which the enumeration is obtained. It allows sequential access to all the elements stored in the collection.

31. How can we find the actual size of an object on the heap?

In Java, there is no way to find out the actual size of an object on the heap.

32. Which API is provided by Java for operations on a set of objects?

Java provides a Collection API that provides many useful methods, which can be applied to a set of objects. Some of the important classes provided by the Collection API include ArrayList, HashMap, TreeSet, and TreeMap.

33. What’s the base class of all exception classes?

Java.Lang.throwable: It is the superclass of all exception classes, and all exception classes are derived from this base class.

34. Why do we use a vector class?

A vector class provides the ability to execute a growable array of objects. A vector proves to be very useful if you don’t know the size of the array in advance or if we need one that can change the size over the lifetime of a program.

35. What is the difference between transient and volatile variables in Java?

Transient: In Java, it is used to specify whether a variable is not being serialized. Serialization is a process of saving an object’s state in Java. When we want to persist the object’s state by default, all instance variables in the object are stored. In some cases, we want to avoid persisting a few variables because we don’t have the necessity to transfer across the network. So, we declare those variables as transient.

If the variable is confirmed as transient, then it will not be persisted. The transient keyword is used with the instance variable that will not participate in the serialization process. We cannot use static with a transient variable as they are part of the instance variable.

Volatile: The volatile keyword is used with only one variable in Java, and it guarantees that the value of the volatile variable will always be read from the main memory and not from the thread’s local cache; it can be static.

36. Why Map interface does not extend the Collection interface in the Java Collections Framework?

The Map interface is not compatible with the Collection interface, because Map requires a key as well as a value, for example, if we want to add a key–value pair, we will use put(Object key, Object value).

There are two parameters required to add an element to HashMap object. In Collection interface, add(Object o) has only one parameter.

The other reasons are: Map supports valueSet, keySet, and other suitable methods that have just different views from the Collection interface.

37. Mention the uses of the synchronized block.

We use the synchronized block because:

  •  It helps lock an object for every shared resource.
  •  The scope of the synchronized block is smaller than the method.

38. What are the functions of hashCode() method?

The hashCode() method returns a hash code value (an integer number) and also the same integer number if the two keys (by calling the equals() method) are the same.
But sometimes, the two hash code numbers can have different or the same keys.

39. What is the default size of the load factor in the hashing-based collection?

Default size = 0.75

Default capacity = initial capacity * load factor

40. What are the differences between the JSP custom tags and Java beans?

  • Custom tags can manipulate JSP content, but beans cannot.
  • Composite operations can be reduced to a considerably simpler form with custom tags than with beans.
  • Custom tags require reasonably a bit more work to set up than beans do.
  • Custom tags are available only in JSP 1.1 and so on, but beans can be used in all JSP 1.x versions.

41. Explain the expression language in JSP.

The expression language is used in JSP to simplify the accessibility of objects. It provides many objects that can be used directly like param, requestScope, sessionScope, applicationScope, request, session, etc.

42. What are implicit objects?

Implicit objects, also called pre-defined variables, are created by the JSP engine inside the service method so that it can be accessed directly without being declared explicitly.

43. Define a cookie. What are the differences between a session and a cookie?

A cookie is a small piece of information, which is sent to the browser by a web server. The browser stores the cookies for every web server in a local file. In a future request, the browser sends all stored cookies for that detailed web server.

The difference between cookies and sessions are:

  •  A session works regardless of the settings on the client browser. The client may have selected to disable cookies.
  •  Sessions and cookies also differ in storing the amount of information. The HTTP session is able to store any Java object, while a cookie can only store String objects.

44. What is HTTP Tunneling?

HTTP tunneling refers to encapsulating the private network data/information and transmitting it through a public network. Instead of sending data as a packet, tunneling encrypts the data and encapsulates it in a connection. This process allows the outside clients to collect all the data sent by the client-side Object Request Broker (ORB) that needs to be sent to the server-side ORB. HTTP tunneling masks other protocol requests as HTTP requests.

45. What is the function of the IOC container in spring?

The IOC container is responsible for:

  • Creating an instance
  • Configuring the instance
  •  Assembling the dependencies

46. What is lazy loading in hibernate?

Lazy loading is a kind of setting that decides whether to load the child entities along with the parent entities or not. When enabling this feature, the associated entities will be loaded only when they are requested directly. The default value of this setting is ‘true’ which stops the child entities from loading.

47. How can we fetch records using Spring JdbcTemplate?

We can fetch records from the database by the query method of JdbcTemplate. There are two interfaces to do this:

  1.  ResultSetExtractor
  2.  RowMapper

48. Which is the front controller class of Spring MVC?

The Dispatcher Servlet class works as the front controller in Spring MVC.

49. What are the states of an object in hibernate?

The states of an object in hibernate are:

  1. Transient: The objects that are just created having no primary key are in a transient state. Here the objects are associated with any session.
  2. Persistent: When the session of an object is just opened and its instance is just saved or retrieved, it is said to be in a persistent state.
  3. Detached: When the session of an object is closed, it is said to be in a detached state.

50. How to make an immutable class in hibernate?

If we mark a class as mutable=”false”, the class will be treated as an immutable class. The default value of mutable is “true”.

51. What is hash-collision in a HashTable? How is it handled in Java?

In HashTable, if two different keys have the same hash value, then it leads to hash-collision. A bucket of type linked list is used to hold the different keys of the same hash value.

52. Write a syntax to convert a given collection to a SynchronizedCollection.

The following will convert a given collection to a synchronized collection:

Collections.synchronizedCollection(Collection collectionObj)

53. Write a code to make the Collections read-only.

We can make the Collections read-only by using the following lines code:

General : Collections.unmodifiableCollection(Collection c)Collections.unmodifiableMap(Map m)
Collections.unmodifiableList(List l)
Collections.unmodifiableSet(Set s)

54. What is meant by binding in RMI?

Binding is the process of associating or registering a name for a remote object, which can be used as a further, in order to look up that remote object. A remote object can be associated with a name using the bind/rebind methods of the Naming class.

55. What are latest features introduced in Java 8?

The below features are introduced in Java 8:

  • Lambda Expressions
  • Interface Default and Static Methods
  • Method Reference
  • Parameters Name
  • Optional Streams
  • Concurrency

56. Name a few Java 8 annotations.

@Functional Interface annotation: It was introduced in Java SE 8, which indicates that the type declaration is intended to be a functional interface as defined by the Java language specification.

@Repeatable annotation: Introduced in Java SE 8, @Repeatable annotation indicates that the marked annotation can be applied many times to the same declaration or type use.

57. Distinguish between a predicate and a function.

predicate takes one argument and returns a Boolean value.

function takes one argument and returns an object. Both are useful for evaluating lambda expressions.

58. Write a code to sort a list of strings using Java 8 lambda expression.

. private void sortUsingJava8(List names){
Collections.sort(names, (p1, p2) -> p1.compareTo(p2));
}

59. What is Nashorn in Java 8?

With Java 8, Nashorn, a much-improved JavaScript engine, is introduced and it replaced the existing Rhino. It provides 2–10 times better performance, as it directly compiles the code in memory and passes the bytecode to JVM. Although, Nashorn uses the invoke dynamic feature, introduced in Java 7, to improve performance.

60. Define a StringJoiner and write a sample code.

StringJoiner is a util method to construct a string with the desired delimiter.

Sample CodeStringJoiner strJoiner = new StringJoiner(".");
strJoiner.add("AAA").add("BBB");
System.out.println(strJoiner);
OutPut:
AAA.BBB

61. Can you execute the JavaScript code from Java 8 code base?

Yes! We can execute the JavaScript code from Java 8 code base by using ScriptEngineManager. We call JavaScript code and interpret it in Java.

Related Courses -Learn Online Now!

RPA (Robotic Process Automation)

Machine Learning with 9 Practical Applications

Mastering Python – Machine Learning

Data Sciences with Python Machine Learning 

Data Sciences Specialization
Diploma in Big Data Analytics

Learn Internet of Things (IoT) Programming
Oracle BI – Create Analyses and Dashboards
Microsoft Power BI with Advance Excel

Join FREE – Big Data Workshop 

sharing is caring

Leave a Reply


ABOUT US

OMNI ACADEMY & CONSULTING is one of the most prestigious Training & Consulting firm, founded in 2010, under MHSG Consulting Group aim to help our customers in transforming their people and business - be more engage with customers through digital transformation. Helping People to Get Valuable Skills and Get Jobs.

Read More

Contact Us

Get your self enrolled for unlimited learning 1000+ Courses, Corporate Group Training, Instructor led Class-Room and ONLINE learning options. Join Now!
  • Head Office: A-2/3 Westland Trade Centre, Shahra-e-Faisal PECHS Karachi 75350 Pakistan Call 0213-455-6664 WhatsApp 0334-318-2845, 0336-7222-191, +92 312 2169325
  • Gulshan Branch: A-242, Sardar Ali Sabri Rd. Block-2, Gulshan-e-Iqbal, Karachi-75300, Call/WhatsApp 0213-498-6664, 0331-3929-217, 0334-1757-521, 0312-2169325
  • ONLINE INQUIRY: Call/WhatsApp +92 312 2169325, 0334-318-2845, Lahore 0333-3808376, Islamabad 0331-3929217, Saudi Arabia 050 2283468
  • DHA Branch: 14-C, Saher Commercial Area, Phase VII, Defence Housing Authority, Karachi-75500 Pakistan. 0213-5344600, 0337-7222-191, 0333-3808-376
  • info@omni-academy.com
  • FREE Support | WhatsApp/Chat/Call : +92 312 2169325
WORKING HOURS

  • Monday10.00am - 7.00pm
  • Tuesday10.00am - 7.00pm
  • Wednesday10.00am - 7.00pm
  • Thursday10.00am - 7.00pm
  • FridayClosed
  • Saturday10.00am - 7.00pm
  • Sunday10.00am - 7.00pm
WhatsApp Us