20 advanced Java interview questions, that you should know? (Short Answers) 2018

0 39

Get real time updates directly on you device, subscribe now.

Java advanced interview question

This is a high-level Java interview question. This interview question discusses Java core issues such as variable parameters, assertions, garbage collection, initialisers, tokenisation, dates, calendars, and more.

1. What is a variable parameter?

Variable parameters allow methods that call different numbers of parameters. Please see the summation method in the example below. This method can call 1 int parameter, or 2 int parameters, or multiple 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
 }

2. What is the purpose of the assertion?

Assertions were introduced in Java 1.4. It allows you to verify the hypothesis. If the assertion fails (ie returns false), an AssertionError is thrown if the assertion is enabled. The basic assertions are as follows.

Private int computerSimpleInterest(int principal,float interest,int years){
 Assert(principal>0);
 Return 100;
}

3. When do you use assertions?

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

4. What is garbage collection?

Garbage collection is another term for automatic memory management in Java. The purpose of garbage collection is to keep as many available heaps as possible for the program. The JVM deletes objects on the heap that no longer need to be referenced from the heap.

5. Explain garbage collection with an example?

For example, the following method will be called from the function.

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

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

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

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

6. When is the garbage collection running?

Garbage collection runs when the JVM wits and wits (not so bad). The possible scenarios for running garbage collection are:

  • Heap free memory
  • CPU idle

7. Best practices for garbage collection?

In a programmatic way, we can ask (remember that this is just a request – not a command). The JVM runs garbage collection by calling the System.gc() method.

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

The finalize() method is run before the object is removed from the heap by garbage collection. We recommend not writing any code with the finalize() method.

8. What is the initialization data block?

Initialize the data block – the code that runs when the object is created or the class is loaded.

There are two types of initialization data blocks:

Static initializer: the code that runs when the class is loaded

Instance initializer: code that runs when a new object is created

9. What is a static initializer?

Take a 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 the static initializer. Although three instances are created, the static initializer only runs 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();
 }
}

Sample output

Static Initializer
Count when Static Initializer is run is 0.

10. What is an instance initialization block?

Let’s look at an example: every time an instance of a class is created, the code in the instance initializer runs.

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 3

11. What is a regular expression?

Regular expressions make it easy to parse, scan, and split strings. Regular expressions commonly used in Java – the Pattern, Matcher and Scanner classes.

12. What is tokenization?

Tokenization refers to splitting a string into several substrings based on the separator. For example, the separator; the split string ac; bd; def; e is the four substrings ac, bd, def, and e.

The separator itself can also be a common regular expression.

The String.split(regex) function takes regex as a parameter.

13. 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]

14. How to use tokenizer class (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]

15. How do I add hours to a Date Objects?

Now let’s see how to add hours to a date object. All date operations on date need to be completed by adding milliseconds to date. For example, if we want to increase by 6 hours, then we need to convert 6 hours into milliseconds. 6 hours = 6 60 60 * 1000 milliseconds. Please see the example below.

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);

16. How to format date objects?

Formatting dates needs to be done using the DateFormat class. Let us look at a few examples.

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

The formatted date with the locale is as follows:

System.out.println(DateFormat.getDateInstance(
 DateFormat.FULL, new Locale("it", "IT"))
 .format(date));//marted" 16 ottobre 2017
System.out.println(DateFormat.getDateInstance(
 DateFormat.FULL, Locale.ITALIAN)
 .format(date));//marted" 16 ottobre 2017
//This uses default locale US
System.out.println(DateFormat.getDateInstance(
 DateFormat.FULL).format(date));//Tuesday, October 16, 2017
System.out.println(DateFormat.getDateInstance()
 .format(date));//Oct 16, 2017
System.out.println(DateFormat.getDateInstance(
 DateFormat.SHORT).format(date));//10/16/17
System.out.println(DateFormat.getDateInstance(
 DateFormat.MEDIUM).format(date));//Oct 16, 2017
System.out.println(DateFormat.getDateInstance(
 DateFormat.LONG).format(date));//October 16, 2017

17. What is the purpose of Calendar Class in Java?

The Calendar class is used in Java to process dates. The Calendar class provides an easy way to increase and decrease the number of days, months, and years. It also provides a lot of date-related details (what day of the year? Which week? etc.)

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

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

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

19. Explain some important methods in the Calendar Class?

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

Calendar.set(Calendar.DATE, 24);
Calendar.set(Calendar.MONTH, 8);//8 - September
Calendar.set(Calendar.YEAR, 2017);

Calendar 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 to get from the calendar – days or months or years or … the values ​​you can get from the calendar are as follows:

System.out.println(calendar.get(Calendar.YEAR));//2017
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

20. What is the purpose of the Number Format Class?

The number format is used to format numbers into different regions and different formats.

Use the default locale number format

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

Number format using locale

Format numbers using the Dutch locale:

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

Format numbers using the German locale:

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

Format currency using the default locale

System.out.println(NumberFormat.getCurrencyInstance().format(40324.31f));//$40,324.31

Format currency using locale

Format the currency using the Dutch locale:

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

Finally, I left a question for everyone:

How to sort 10GB text data under limited memory?s

93%
Awesome
  • Explanation
  • Details

Get real time updates directly on you device, subscribe now.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More