Frequently Asked Java Interview Questions And Answers

1) What is the similarity and difference between String, StringBuilder and StringBuffer class in Java?

– String and StringBuffer class are thread safe but StringBuilder is not thread safe

– StringBuffer and StringBuilder objects are mutable but String objects are immutable

2) What is the difference between final, finally and finalize?

– The final keyword used in several contexts to define an entity that can only be assigned once

– The finally block is always executed whether the exception is handled or not

– Finalize method is a method that GarbageCollector always calls just before the deletion/destroying the object, which is eligible for Garbage Collection to perform clean-up activity

3) What is Singleton class in Java and how can we make a class singleton?

 A singleton class is a class that can have only one object (an instance of the class) at a time.

To design a singleton class:

  1. Make constructor as private.
  2. Write a static method that has return type object of this singleton class.

Singletons can be used while working with databases. They can be used to create a connection pool to access the database while reusing the same connection for all the clients. For example,

class Database {
   private static Database dbObject;

   private Database() {      
   }

   public static Database getInstance() {

      // create object if it's not already created
      if(dbObject == null) {
         dbObject = new Database();
      }

       // returns the singleton object
       return dbObject;
   }

   public void getConnection() {
       System.out.println("You are now connected to the database.");
   }
}

class Main {
   public static void main(String[] args) {
      Database db1;

      // refers to the only object of Database
      db1= Database.getInstance();
      
      db1.getConnection();
   }
}

 

4) What is the difference between abstract class and interface?

– In case of abstract class, a class can only extend one abstract class but in interfaces, a class can implement several interfaces

– An abstract class can have non abstract methods but all methods of an interface are abstract

– An abstract class can be public, private or protected but an interface must be public or none

– An abstract class can contain constructors but interface cannot contain constructors

– An abstract class can provide complete, default code or just details that have to be overridden but  an interface cannot provide code at all, just the signature

5) What is the difference between method overloading and method overriding

Method Overloading:

– Methods of same class shares the same name but each method must have a different number of parameters or parameters having different types and order

– It is a compile time polymorphism

– The methods must have a different signature

– It may or may not need inheritance

Method Overriding:

– The subclass has the same method name, same number and type of parameters and same return type as a superclass

– It is a runtime polymorphism

– The methods must have same signature -It always requires inheritance

6) Why String is immutable in Java?

String is immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, one client action will affect another client. Since caching of String objects was important from performance reason this risk was avoided by making the String class immutable.

7) Why Character Array is better than String to store passwords in Java?

Since strings are immutable in Java if you store password as plain text it will be available in memory until Garbage Collector clears it and since String are used in String pool for reusability there is pretty high chance that it will remain in memory for long duration, which poses a security threat. Since strings are immutable there is no way contents of string can be changed while if you use char[] you can still set all its elements as blank or zero. So storing password in char array mitigates security risk of stealing password.

8) Can you override static method in Java?. If I create the same method in the subclass is it compile time error?

No, you cannot override static method in Java but it doesn’t return any compile time error when you declare an exact same method in a subclass. Method overriding is based upon dynamic binding at runtime and static methods are bonded using static binding at compile time.

9) Can a Java class implement implement two interfaces with same methods ?

If two interfaces contain a method with the same signature but different return types then it is impossible to implement both the interfaces simultaneously. It will throw a compile time error. But if two interfaces contain a method with same signature and return types then a single implementation will work for both interfaces and there will be no error.

10) What is the difference between HashTable and HashMap in Java?

– HashMap is non synchronized and not thread safe but HashTable is synchronized and thread safe

– HashMap allows one null key and multiple null values but HashTable doesn’t allow any null key or value

– HashMap is faster than HashTable

11) What is the difference between ArrayList and HashSet in Java?

– ArrayList is an ordered collection and maintains insertion order of elements while HashSet is an unordered collection and doesn’t maintain any order

– ArrayList allows duplicates while HashSet doesn’t allow duplicate

12) How can you check substring exists in string in Java?

There are many ways to check SubString exists in String in Java like contains() and indexof() methods.

– contains() method searches the sequence of characters in the given string. It returns true if sequence of char values are found in this string otherwise returns false.

String str = "Java Interview Questions";
system.out.println(str.contains("Java"));

Output: true

– indexof() method returns the index within this string of the first occurrence of the specified character or -1, if the character does not occur.

String str = "Java Interview Questions";
system.out.println(str.indexof("I")); 


Output: 6

13) What is the difference between HashMap and HashSet in Java?

– HashMap stores a key-value pair but HashSet stores objects

– HashMap doesn’t allow duplicate keys and allows duplicate values but HashSet doesn’t allow duplicate values

– HashMap is faster than Hashset because values are associated with a unique key but HashSet is slower than HashMap because the member object is used for calculating hashcode value, which can be same for two objects

– HashMap contains a null key and multiple null values but HashSet contains a single null value

– In HashMap 2 objects are created during put operation, one for key and one for value but in HashSet only 1 object is created for add operation

14) Why main method is public static void in Java?

Main method is an standard method which is used by JVM to start execution of any Java program. Main method is public so that it is visible to every other class. It is static so that it can be called without creating an instance. It is void because it doesn’t return any value to JVM.

15) How to sort ArrayList in Java?

ArrayList can be sorted using Collections.Sort() method. Sort method optionally accepts a Comparator but if it is not provided it uses compareTo() method for comparison. To sort in reverse order use Collections.reverseOrder().

//To sort list in Ascending Order
public static void SortListInAscendingOrder(){
ArrayList<String> languages = new ArrayList<String>();
languages.add("Java");
languages.add(".Net");
languages.add("Python");
Collections.sort(languages);
System.out.println("Sorted List:\n" + languages);
}
//To sort list in Descending Order
public static void SortListInDescendingOrder(){
ArrayList<String> languages = new ArrayList<String>();
languages.add("Java");
languages.add(".Net");
languages.add("Python");
Collections.sort(languages,Collections.reverseOrder());
System.out.println("Sorted List:\n" + languages);
}

 

 

Share

Bijan Patel

Founder & Creator of QAScript | 12+ years of IT Experience | Full Stack Automation Engineer | Blogger | Trainer

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!