This is the first in a series of advanced Java interview questions. This section covers mutable arguments, assertions, garbage collection, initializers, tokenization, dates, calendars, and many more core Java issues.

  1. What is a variable parameter?
  2. The purpose of assertions?
  3. When to use assertions?
  4. What is garbage collection?
  5. An example to explain garbage collection?
  6. When is garbage collection run?
  7. Best practices for garbage recycling?
  8. What is initializing a data block?
  9. What is a static initializer?
  10. What is an instance initialization block?
  11. What is a regular expression?
  12. What is tokenization?
  13. Give an example of tokenization?
  14. How to use Scanner Class tokenization?
  15. How do I add an hour to a Date object?
  16. How do I format a date object?
  17. What is the purpose of the Calendar Class in Java?
  18. How do I get an instance of a calendar class in Java?
  19. Explain some important methods in the calendar class?
  20. What does the Number Format Class do?

What is a variable parameter?

Mutable arguments allow methods to be called with different numbers of arguments. Look at the summation method in the following example. This method can call one int argument, two int arguments, or multiple int arguments.

 //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
    }Copy the code

The purpose of assertions?

Assertions were introduced in Java 1.4. It allows you to test hypotheses. If the assertion fails (that is, returns false), an AssertionError is thrown (if assertion is enabled). The basic assertions are shown below.

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

When to use assertions?

Assertions should not be used to validate input data to a public method or command-line argument. IllegalArgumentException would be a better choice. In public methods, only assertions are used to check for situations that they should not happen at all.

What is garbage collection?

Garbage collection is another name for automatic memory management in Java. The goal of garbage collection is to keep as much heap available as possible for your program. The JVM removes objects on the heap that no longer need to be referenced from the heap.

An example to explain garbage collection?

For example, the following method is called from a function.

void method(){
    Calendar calendar = new GregorianCalendar(2000.10.30);
    System.out.println(calendar);
}Copy the code

An object of the GregorianCalendar class is created on the heap by referring to the variable Calendar in the first line of the function.

After the function completes execution, the reference variable Calendar is no longer valid. Therefore, no reference to the object is created in the method.

The JVM recognizes this and removes objects from the heap. This is called recycling.

When is garbage collection run?

Garbage collection runs on the whims and whims of the JVM (it’s not that bad). The possible scenarios for running garbage collection are:

  • Insufficient heap free memory
  • The CPU is idle

Best practices for garbage recycling?

Programmatically, we can ask (remember this is just a request — not a command) that the JVM run garbage collection by calling the System.gc() method.

When memory is full and there are no objects on the heap available for garbage collection, the JVM may throw an OutOfMemoryException.

Objects run the Finalize () method before they are removed from the heap by garbage collection. We recommend not writing any code with the Finalize () method.

What is initializing a data block?

Initialize data block – code that 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 following example: the code between static{and} is called a static initializer. It only runs when the class is first loaded. Only static variables can be accessed in a static initializer. Although three instances are created, the static initializer runs 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 = newInitializerExamples(); }}Copy the code

Sample output

Static Initializer
Count when Static Initializer is run is 0.Copy the code

What is an instance initialization block?

Let’s look at an example: the code in the instance initializer runs every time an instance of a 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 = newInitializerExamples(); }}Copy the code

Sample 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 3Copy the code

What is a regular expression?

Regular expressions make parsing, scanning, and splitting strings very easy. Regular expressions commonly used in Java — Pattern, Matcher, and Scanner classes.

What is tokenization?

Tokenization is the splitting of a string into substrings based on delimiters. For example, delimiters; Split string AC; bd; def; E is the four substrings AC, BD, def and e.

The delimiter itself can also be a common regular expression.

The string.split (regex) function takes regex as an argument.

Give an example of tokenization?

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]Copy the code

How to use Scanner Class tokenization?

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]Copy the code

How do I add an hour to a Date object?

Now, let’s see how to add hours to a date object. All date operations on date need to be done by adding milliseconds to date. For example, if we want to add 6 hours, we need to convert 6 hours into milliseconds. 6 hours = 6 * 60 * 60 * 1000 ms. Take a look at the following examples.

Date date = new Date(a);//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(a); date.setTime(date.getTime() -6 * 60 * 60 * 1000);
System.out.println(date);Copy the code

How do I format a date object?

Formatting dates is done using the DateFormat class. Let’s look at some examples.

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

The formatted date with locale Settings looks like this:

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, 2012Copy the code

What is the purpose of the Calendar Class in Java?

Calendar class, used in Java to process dates. The Calendar class provides easy ways to add and subtract days, months, and years. It also provides a lot of details about dates (what day of the year? A week? Etc.)

How do I get an instance of a Calendar Class in Java?

Calendar classes cannot be created by using New Calendar. The best way to get an instance of a Calendar class is to use the getInstance() static method in Calendar.

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

Explain some important methods in the Calendar Class.

It is not difficult to set a day, month, or year on a Calendar object. Call the set method of the appropriate Constant for Day, Month, or Year. The next argument is the value.

calendar.set(Calendar.DATE.24);
calendar.set(Calendar.MONTH.8);//8 - September
calendar.set(Calendar.YEAR.2010);Copy the code

The calendar the get method

To get information on a specific date — September 24, 2010. We can use the Calendar GET method. The parameters that have been passed represent the values we want from calendar — days or months or years or… Examples of values you can get from Calendar are as follows:

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.SUNDAYCopy the code

What does the Number Format Class do?

Number formats are used to format numbers into different fields and different formats.

Use the number format of the default locale

System.out.println(NumberFormat.getInstance().format(321.24f));/ / 321.24Copy the code

Number format using locale

Format numbers using the Dutch locale:

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

Format numbers using the German locale:

System.out.println(NumberFormat.getInstance(Locale.GERMANY).format(4032.3f));/ / 4.032, 3Copy the code

Format the currency using the default locale

System.out.println(NumberFormat.getCurrencyInstance().format(40324.31f));/ / $40324.31...Copy the code

Format currency with locale

Format the currency using the Dutch locale:

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