Advanced Java Interview Questions for Freshers and Experienced

Advanced Java Interview Questions covers a varied range of topics : Variable Arguments, Threads, Serialisation, Collections and a lot more. Advanced Java Interview Questions are very important, especially, for experienced java developers.In addition to reading the questions, we recommend watching these two interview preparation videos covering important core java questions.

advanced java interview question topics
  1. What are Variable Arguments or varargs?
  2. What are Asserts used for?
  3. When should Asserts be used?
  4. What is Garbage Collection?
  5. Can you explain Garbage Collection with an example?
  6. When is Garbage Collection run?
  7. What are best practices on Garbage Collection?
  8. What are Initialization Blocks?
  9. What is a Static Initializer?
  10. What is an Instance Initializer Block?
  11. What are Regular Expressions?
  12. What is Tokenizing?
  13. Can you give an example of Tokenizing?
  14. How can you Tokenize using Scanner Class?
  15. How do you add hours to a date object?
  16. How do you format Date Objects?
  17. What is the use of Calendar class in Java?
  18. How do you get an instance of Calendar class in Java?
  19. Can you explain some of the important methods in Calendar class?
  20. What is the use of NumberFormat class?

What are Variable Arguments or varargs?

Variable Arguments allow calling a method with different number of parameters. Consider the example method sum below. This sum method can be called with 1 int parameter or 2 int parameters or more int parameters.

    //int(type) followed ... (three dot's) is syntax of a variable argument. 
    public int sum(int... numbers) {
        //inside the method a variable argument is similar to an array.
        //number can be treated as if it is declared as int[] numbers;
        int sum = 0;
        for (int number: numbers) {
            sum += number;
        }
        return sum;
    }

    public static void main(String[] args) {
        VariableArgumentExamples example = new VariableArgumentExamples();
        //3 Arguments
        System.out.println(example.sum(1, 4, 5));//10
        //4 Arguments
        System.out.println(example.sum(1, 4, 5, 20));//30
        //0 Arguments
        System.out.println(example.sum());//0
    }

What are Asserts used for?

Assertions are introduced in Java 1.4. They enable you to validate assumptions. If an assert fails (i.e. returns false), AssertionError is thrown (if assertions are enabled). Basic assert is shown in the example below

private int computerSimpleInterest(int principal,float interest,int years){
    assert(principal>0);
    return 100;
}

When should Asserts be used?

Assertions should not be used to validate input data to a public method or command line argument. IllegalArgumentException would be a better option. In public method, only use assertions to check for cases which are never supposed to happen.

What is Garbage Collection?

Garbage Collection is a name given to automatic memory management in Java. Aim of Garbage Collection is to Keep as much of heap available (free) for the program as possible. JVM removes objects on the heap which no longer have references from the heap.

Can you explain Garbage Collection with an example?

Let’s say the below method is called from a function.

void method(){
    Calendar calendar = new GregorianCalendar(2000,10,30);
    System.out.println(calendar);
}

An object of the class GregorianCalendar is created on the heap by the first line of the function with one reference variable calendar.

After the function ends execution, the reference variable calendar is no longer valid. Hence, there are no references to the object created in the method.

JVM recognizes this and removes the object from the heap. This is called Garbage Collection.

When is Garbage Collection run?

Garbage Collection runs at the whims and fancies of the JVM (it isn't as bad as that). Possible situations when Garbage Collection might run are

  • when available memory on the heap is low
  • when cpu is free

What are best practices on Garbage Collection?

Programmatically, we can request (remember it’s just a request - Not an order) JVM to run Garbage Collection by calling System.gc() method.

JVM might throw an OutOfMemoryException when memory is full and no objects on the heap are eligible for garbage collection.

finalize() method on the objected is run before the object is removed from the heap from the garbage collector. We recommend not to write any code in finalize();

What are Initialization Blocks?

Initialization Blocks - Code which runs when an object is created or a class is loaded

There are two types of Initialization Blocks

Static Initializer: Code that runs when a class is loaded.

Instance Initializer: Code that runs when a new object is created.

What is a Static Initializer?

Look at the example below:Code within static{ and } is called a static initializer. This is run only when class is first loaded. Only static variables can be accessed in a static initializer. Even though three instances are created static initializer is run only once.

public class InitializerExamples {
    static int count;
    int i;

    static{
        //This is a static initializers. Run only when Class is first loaded.
        //Only static variables can be accessed
        System.out.println("Static Initializer");
        //i = 6;//COMPILER ERROR
        System.out.println("Count when Static Initializer is run is " + count);
    }

    public static void main(String[] args) {
        InitializerExamples example = new InitializerExamples();
        InitializerExamples example2 = new InitializerExamples();
        InitializerExamples example3 = new InitializerExamples();
    }
}
Example Output

Static Initializer

Count when Static Initializer is run is 0

What is an Instance Initializer Block?

Let’s look at an example : Code within instance initializer is run every time an instance of the class is created.

public class InitializerExamples {
    static int count;
    int i;
    {
        //This is an instance initializers. Run every time an object is created.
        //static and instance variables can be accessed
        System.out.println("Instance Initializer");
        i = 6;
        count = count + 1;
        System.out.println("Count when Instance Initializer is run is " + count);
    }
        
    public static void main(String[] args) {
        InitializerExamples example = new InitializerExamples();
        InitializerExamples example1 = new InitializerExamples();
        InitializerExamples example2 = new InitializerExamples();
    }

}
Example Output
      
      Instance Initializer
      Count when Instance Initializer is run is 1
      Instance Initializer
      Count when Instance Initializer is run is 2
      Instance Initializer
      Count when Instance Initializer is run is 3
      

What are Regular Expressions?

Regular Expressions make parsing, scanning and splitting a string very easy. We will first look at how you can evaluate a regular expressions in Java – using Patter, Matcher and Scanner classes. We will then look into how to write a regular expression.

What is Tokenizing?

Tokenizing means splitting a string into several sub strings based on delimiters. For example, delimiter ; splits the string ac;bd;def;e into four sub strings ac, bd, def and e.

Delimiter can in itself be any of the regular expression(s) we looked at earlier.

String.split(regex) function takes regex as an argument.

Can you give an example of Tokenizing?

private static void tokenize(String string,String regex) {
    String[] tokens = string.split(regex);
    System.out.println(Arrays.toString(tokens));
}

tokenize("ac;bd;def;e",";");//[ac, bd, def, e]

How can you Tokenize using Scanner Class?

private static void tokenizeUsingScanner(String string,String regex) {
    Scanner scanner = new Scanner(string);
    scanner.useDelimiter(regex);
    List<String> matches = new ArrayList<String>();
    while(scanner.hasNext()){
        matches.add(scanner.next());
    }
    System.out.println(matches);
}

tokenizeUsingScanner("ac;bd;def;e",";");//[ac, bd, def, e]

How do you add hours to a date object?

Lets now look at adding a few hours to a date object. All date manipulation to date needs to be done by adding milliseconds to the date. For example, if we want to add 6 hour, we convert 6 hours into millseconds. 6 hours = 6 * 60 * 60 * 1000 milliseconds. Below examples shows specific code.

Date date = new Date();

//Increase time by 6 hrs
date.setTime(date.getTime() + 6 * 60 * 60 * 1000);
System.out.println(date);

//Decrease time by 6 hrs
date = new Date();
date.setTime(date.getTime() - 6 * 60 * 60 * 1000);
System.out.println(date);

How do you format Date Objects?

Formatting Dates is done by using DateFormat class. Let’s look at a few examples.

//Formatting Dates
System.out.println(DateFormat.getInstance().format(
        date));//10/16/12 5:18 AM

Formatting Dates with a locale

System.out.println(DateFormat.getDateInstance(
        DateFormat.FULL, new Locale("it", "IT"))
        .format(date));//marted“ 16 ottobre 2012

System.out.println(DateFormat.getDateInstance(
        DateFormat.FULL, Locale.ITALIAN)
        .format(date));//marted“ 16 ottobre 2012

//This uses default locale US
System.out.println(DateFormat.getDateInstance(
        DateFormat.FULL).format(date));//Tuesday, October 16, 2012

System.out.println(DateFormat.getDateInstance()
        .format(date));//Oct 16, 2012
System.out.println(DateFormat.getDateInstance(
        DateFormat.SHORT).format(date));//10/16/12
System.out.println(DateFormat.getDateInstance(
        DateFormat.MEDIUM).format(date));//Oct 16, 2012

System.out.println(DateFormat.getDateInstance(
        DateFormat.LONG).format(date));//October 16, 2012

What is the use of Calendar class in Java?

Calendar class (Youtube video link - https://www.youtube.com/watch?v=hvnlYbt1ve0) is used in Java to manipulate Dates. Calendar class provides easy ways to add or reduce days, months or years from a date. It also provide lot of details about a date (which day of the year? Which week of the year? etc.)

How do you get an instance of Calendar class in Java?

Calendar class cannot be created by using new Calendar. The best way to get an instance of Calendar class is by using getInstance() static method in Calendar.

//Calendar calendar = new Calendar(); //COMPILER ERROR
Calendar calendar = Calendar.getInstance();

Can you explain some of the important methods in Calendar class?

Setting day, month or year on a calendar object is simple. Call the set method with appropriate Constant for Day, Month or Year. Next parameter is the value.

calendar.set(Calendar.DATE, 24);
calendar.set(Calendar.MONTH, 8);//8 - September
calendar.set(Calendar.YEAR, 2010);
Calendar get method

Let’s get information about a particular date - 24th September 2010. We use the calendar get method. The parameter passed indicates what value we would want to get from the calendar – day or month or year or .. Few examples of the values you can obtain from a calendar are listed below.

System.out.println(calendar.get(Calendar.YEAR));//2010
System.out.println(calendar.get(Calendar.MONTH));//8
System.out.println(calendar.get(Calendar.DATE));//24
System.out.println(calendar.get(Calendar.WEEK_OF_MONTH));//4
System.out.println(calendar.get(Calendar.WEEK_OF_YEAR));//39
System.out.println(calendar.get(Calendar.DAY_OF_YEAR));//267
System.out.println(calendar.getFirstDayOfWeek());//1 -> Calendar.SUNDAY

What is the use of NumberFormat class?

Number format is used to format a number to different locales and different formats.

Format number Using Default locale
System.out.println(NumberFormat.getInstance().format(321.24f));//321.24        
Format number using locale

Formatting a number using Netherlands locale

System.out.println(NumberFormat.getInstance(new Locale("nl")).format(4032.3f));//4.032,3

Formatting a number using Germany locale

System.out.println(NumberFormat.getInstance(Locale.GERMANY).format(4032.3f));//4.032,3
Formatting a Currency using Default locale
System.out.println(NumberFormat.getCurrencyInstance().format(40324.31f));//$40,324.31
Format currency using locale

Formatting a Currency using Netherlands locale

System.out.println(NumberFormat.getCurrencyInstance(new Locale("nl")).format(40324.31f));//? 40.324,31

If you loved these Questions, you will love our PDF Interview Guide with 400+ Questions.
Download it now!.

400+ Interview Questions in 4 Categories:
  1. Java : Core Java, Advanced Java, Generics, Exception Handling, Serialization, Threads, Synchronization, Java New Features
  2. Frameworks : Spring, Spring MVC, Struts, Hibernate
  3. Design : Design, Design Patterns, Code Review
  4. Architecture : Architecture, Performance & Load Testing, Web Services, REST Web Services,Security, Continuous Integration