Top 30 Core Java Interview questions and answers for freshers
Here is the list of some of the most common Questions & answers for Java interviews. It’s not limited to any particular company as well, in fact, all major IT companies in India e.g. TCS, CTS, Infosys, Tech Mahindra, HCL, Oracle Financial Services, and many of the major investment asked this kind of fact-based question on their Java recruitment drives. By the way, some questions are really easy, and some are real tough, so it’s mixed of both, but one thing is common, they are the most frequently asked questions from Java interviews for freshers.
1) What is an immutable object? How do you create an Immutable object in Java?
Table of Contents
- Immutable objects offer several benefits over a conventional mutable object, especially while creating concurrent Java application. Immutable object not only guarantees safe publication of object’s sta but also can be shared among other threads without any external synchronization. In fact, JDK itself contains several immutable classes like String, Integer, and other wrapper classes.For those, who doesn’t know what is immutable class or object, Immutable objects are those, whose state can not be changed once created e.g. java.lang.String, once created can not be modified e.g. trim, uppercase, lowercase.All modification in String results in a new object, how to write an immutable class in Java or how to make a class immutable. By the way making a class immutable is not difficult on the code level, but its the decision to make, which class mutable or immutable which makes difference. Immutable classes are those class, whose object can not be modified once created,it means any modification on the immutable object will result in another immutable object. the best example to understand immutable and mutable objects are, String and StringBuffer. Since String is an immutable class, any change on existing string object will result in another string e.g. replacing a character into String, creating a substring from String, all result in new objects.While in the case of a mutable object like StringBuffer, any modification is done on the object itself and no new objects are created. Some times this immutability of String can also cause security hole, and that the reason why password should be stored on char array instead of String.
2)Can we create an Immutable object, which contains a mutable object?
- Yes, its possible to create an Immutable object which may contain a mutable object, you just need to be a little bit careful not to share the reference of the mutable component, instead, you should return a copy of it if you have to. Most common example is an Object which contains the reference of java.util.Date object.
3)What is the right data type to represent a price in Java?
- BigDecimal if memory is not a concern and Performance is not critical, otherwise double with predefined precision.
4) How do you convert bytes to String?
- You can use constructor of String, which takes byte array and character encoding
String str = new String(bytes, “UTF-8”);
This is the right way to convert bytes to String, provided you know for sure that bytes are encoded in the character encoding you are using.
5)There are two classes B extends A and C extends B, Can we cast B into C e.g. C = (C) B
- Type casting in Java is to cast one type, a class or interface, into another type i.e. another class or interface. Since Java is an Object oriented programming language and supports both Inheritance and Polymorphism, It’s easy that Super class reference variable is pointing to SubClass object but the catch here is that there is no way for Java compiler to know that a Superclass variable is pointing to a SubClass object. Which means you can not call a method which is declared in the subclass. In order to do that, you first need to cast the Object back into its original type. This is called type casting in Java. You can type cast both primitive and reference type in Java. The concept of casting will be clearer when you will see an example of type casting in next section.Type casting also comes with the risk of ClassCastException in Java, which is quite common with a method which accepts Object type and later types cast into more specific type.We will see when ClassCastException comes during type casting and How to avoid it in coming section of this article. Another worth noting point here is that from Java 5 onwards you can use Generics to write type-safe code to reduce the amount of type casting in Java which also reduces the risk of java.lang.ClassCastException at runtime.
6)Which class contains clone method? Cloneable or Object?
- java.lang.Cloneable is marker interface and doesn’t contain any method clone method is defined in the object class. It is also knowing that clone() is a native method means it’s implemented in C or C++ or any other native language.
7) Is ++ operator is thread-safe in Java?
- No, it’s not a thread safe operator because it involve multiple instructions like reading a value, incriminating it and storing it back into memory which can be overlapped between multiple threads.
8)Difference between a = a + b and a += b ?
- The += operator implicitly cast the result of addition into the type of variable used to hold the result. When you add two integral variables e.g. variable of type byte, short, or int then they are first promoted to int and them addition happens.No, you cannot store a double value into a long variable without casting because the range of double is more that long and you we need to type cast.
9)Explain System.out.printing() statement?
10)Which one will take more memory, an int or Integer?
- An Integer object will take more memory an Integer is the object and it store meta data overhead about the object and int is primitive type so it takes less space.
11)Why is String Immutable in Java?
- The String is Immutable in java because java designer thought that string will be heavily used and making it immutable allow some optimization easy sharing same String object between multiple clients.
12)What is constructor chaining in Java?
- When you call one constructor from other than it’s known as constructor chaining in Java. This happens when you have multiple, overloaded constructor in the class.
13)What is the difference between JRE, JDK, JVM and JIT?
- JRE stands for Java run-time and it’s required to run Java application. JDK stands for Java development kit and provides tools to develop Java program e.g. Java compiler. It also contains JRE. The JVM stands for Java virtual machine and it’s the process responsible for running Java application. The JIT stands for Just In Time compilation and helps to boost the performance of Java application by converting Java byte code into native code when the crossed certain threshold i.e. the mainly hot code is converted into native code.
14)What is a.hashCode() used for? How is it related to a.equals(b)?
- The = b does object reference matching if both a and b are an object and only return true if both are pointing to the same object in the heap space, on the other hand, a.equals(b) is used for logical mapping and its expected from an object to override this method to provide logical equality. For example, String class overrides this equals() method so that you can compare two Strings, which are the different object but contains same letters.
15)What is a.hashCode() used for?
- hashCode() method returns an int hash value corresponding to an object. It’s used in hash based collection classes e.g Hashtable, HashMap, LinkedHashMap and so on. It’s very tightly related to the equals() method. According to Java specification, two objects which are equal to each other using equals() method must have the same hash code.
16)The difference between final, finalize and finally?
- The final is a modifier which you can apply to variable, methods, and classes. If you make a variable final it means its value cannot be changed once initialized. finalize is a method, which is called just before an object is a garbage collected, giving it last chance to resurrect itself, but the call to finalize is not guaranteed. finally is a keyword which is used in exception handling along with try and catch. the final block is always executed irrespective of whether an exception is thrown from try block or not.
17) What is an Applets?
- Applets :
– These are small java programs.
– They can send from one computer to another computer over the internet using the Applet Viewer that supports java.
– Applets can run in a Web browser as it is a java program. It can be a fully functional Java application because it has the entire Java API at its disposal.
– Applets follow the security rules given by the Web browser.
– Applet security is also known as sandbox security.
18)What is a compile time constant in Java?
- public static final variables are also known as a compile time constant.
19)The difference between List, Set, Map, and Queue in Java?
- Duplicate ObjectsThe main difference between List and Set interface in Java is that List allows duplicates while Set doesn’t allow duplicates. All implementation of Set honor this contract. The map holds two objects per Entry e.g. key and value and It may contain duplicate values but keys are always unique. See here for more difference between List and Set data structure in Java.Order
Another key difference between List and Set is that List is an ordered collection, List’s contract maintains insertion order or element. Set is an unordered collection, you get no guarantee on which order element will be stored. Though some of the Set implementation e.g. LinkedHashSet maintains order. Also SortedSet and SortedMap e.g. TreeSet and TreeMap maintains a sorting order, imposed by using Comparator or Comparable.
Null elements
The list allows null elements and you can have many null objects in a List because it also allowed duplicates. Set just allow one null element as there is no duplicate permitted while in Map you can have null values and at most one null key. worth noting is that Hashtable doesn’t allow null key or values but HashMap allows null values and one null key. This is also the main difference between these two popular implementations of Map interface, aka HashMap vs Hashtable.
Popular implementation
Most popular implementations of List interface in Java are ArrayList, LinkedList, and Vector class. ArrayList is more general purpose and provides random access with index, while LinkedList is more suitable for frequently adding and removing elements from List. Vector is synchronized counterpart of ArrayList. On the other hand, most popular implementations of the Set interface are HashSet, LinkedHashSet, and TreeSet. First one is general purpose Set which is backed by HashMap, see how HashSet works internally in Java for more details. It also doesn’t provide any ordering guarantee but LinkedHashSet does provide ordering along with uniqueness offered by the Set interface. Third implementation TreeSet is also an implementation of SortedSet interface, hence it keeps elements in a sorted order specified by compare() or compareTo() method. Now the last one, most popular implementation of Map interface are HashMap, LinkedHashMap, Hashtable, and TreeMap. First one is the non-synchronized general purpose Map implementation while Hashtable is its synchronized counterpart, both doesn’ provide any ordering guarantee which comes from LinkedHashMap. Just like TreeSet, TreeMap is also a sorted data structure and keeps keys in sorted order.
20)The difference between LinkedHashMap and PriorityQueue in Java?
- PriorityQueue guarantees that lowest or highest priority element always remains at the head of the queue, but LinkedHashMap maintains the order on which elements are inserted. When you iterate over a PriorityQueue, iterator doesn’t guarantee any order but iterator of LinkedHashMap does guarantee the order on which elements are inserted.
21)The difference between ArrayList and LinkedList in Java?
- The main difference between ArrayList vs LinkedList is that former is backed by an array while later is based upon linked list data structure, which makes the performance of add(), remove(), contains() and iterator() different for both ArrayList and LinkedList. The difference between ArrayList and LinkedList is also an important Java collection interview questions, as much popular as Vector vs ArrayList or HashMap vs HashSet in Java.1) Both ArrayList and LinkedList are an implementation of List interface, which means you can pass either ArrayList or LinkedList if a method accepts List interface.
2) Both ArrayList and LinkedList are not synchronized, which means you can not share them between multiple threads without external synchronization.
3) ArrayList and LinkedList are ordered collection e.g. they maintain insertion order of elements i.e. the first element will be added to the first position.
4) ArrayList and LinkedList also allow duplicates and null, unlike any other List implementation e.g. Vector.
22) How do you print Array in Java?
- You can print an array by using the Arrays.toString() and Arrays.deepToString() method. Since array doesn’t implement toString() by itself, just passing an array to System.out.println() will not print its contents but Arrays.toString() will print each element.
23)What is the difference between Hashtable and HashMap?
25)What is default size of ArrayList and HashMap in Java?
- As of Java 7 now, a default size of ArrayList is 10 and default capacity of HashMap is 16, it must be the power of 2. Here is code snippet from ArrayList and HashMap class:
// from ArrayList.java JDK 1.7
private static final int DEFAULT_CAPACITY = 10;
//from HashMap.java JDK 7
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
26)Is it possible for two unequal objects to have the same hashcode?
- Yes, two unequal objects can have the same hashcode that’s why collision happen in a hashmap.the equal hashcode contract only says that two equal objects must have the same hashcode it doesn’t say anything about the unequal object.
The Comparable interface is used to define the natural order of object while Comparator is used to define custom order. Comparable can be always one, but we can have multiple comparators to define customized order for objects.
27)How do you format a date in Java? e.g. in the DDMMYYYY format?
- You can either use SimpleDateFormat class or job-time library to format the date in Java. DateFormat class allows you to format date on many popular formats. Please see the answer for code samples to format the date into different formats e.g. dd-MM-yy or DDMMYYYY.
28)The difference between java.util.Date and java.sql.Date in Java?
- There are two date classes in Java, one in java.util package and other in the java.sql package. Though both are known as Date class, there is some difference between java.util.Date and java.sql.Date e.g. Former is used whenever a Date is required in Java application while later is used to read and store DATE SQL type from the database. There is one more important difference is java.util.Date stores both date and time values, while java.sql.date only stores date information, without any time part. As per Javadoc, java.sql.date is a thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be ‘normalized’ by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
29)How to convert String to int in Java?
- Java provides Integer.parseInt() method to parse a String to an int value, but that’s not the only way to convert a numeric String to int in Java. There is, in fact, a better way, 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. Yes, you guessed it right, I am talking about Integer.valueOf() method, which implements Flyweight design pattern and maintains a cached pool of frequently used int values e.g. from -128 to 127. So every time you pass a numeric String which is in the range of -128 to 127, Integer.valueOf() doesn’t create a new Integer object but return the same value from the cached pool. The only drawback is that Integer.valueOf() returns an Integer object and not an int primitive value like parseInt() method, but given auto-boxing is available in Java from JDK 5 onward, which automatically convert an Integer object to an int value in Java.
30) Explain numberFormatException.?
- A Java NumberFormatException usually occurs when you try to do something like converting a String to a numeric value, like an int, float, double, long, etc.