Summary of 20 interview questions for Java advanced developers
This is the first part of an advanced Java interview series. This part discusses the core issues of Java, such as variable parameters, assertions, garbage collection, initializers, tokenization, dates, calendars and so on.
What are variable parameters?
Variable parameters allow methods with different numbers of parameters to be called. Look at the summation method in the following example. This method can call 1 int parameter, 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, 5, 20));//30 //0 Arguments System.out.println(example.sum());//0 }
Purpose of assertion?
Assertions were introduced in Java 1.4. It allows you to test hypotheses. If the assertion fails (i.e. returns false), an assertionerror is thrown (if assertion is enabled). The basic assertion is shown below.
private int computerSimpleInterest(int principal,float interest,int years){ assert(principal>0); return 100; }
When to use assertions?
Assertions should not be used to validate input data to a public method or command line parameter. The illegalargumentexception would be a better choice. In the public method, only assertions are used to check what should not happen at all.
What is garbage collection?
Garbage collection is another name for automatic memory management in Java. The purpose of garbage collection is to keep as many heaps as possible for programs. The JVM deletes objects on the heap that no longer need to be referenced from the heap.
Explain garbage collection with an example?
For example, the following method will be called from a function.
void method(){ Calendar calendar = new GregorianCalendar(2000,10,30); System.out.println(calendar); }
By referring to the variable calendar in the first line of the function, an object of the gregoriancalendar class is created on the heap.
After the function is executed, the reference variable calendar is no longer valid. Therefore, no reference to the object was created in the method.
The JVM recognizes this and deletes objects from the heap. This is called garbage collection.
When does garbage collection run?
Garbage collection runs on the whim and whim of the JVM (not that bad). Possible situations for running garbage collection are:
Best practices for garbage collection?
Programmatically, we can ask (remember that this is just a request & mdash; & mdash; not a command) the JVM to run garbage collection by calling the system. GC () method.
When the memory is full and there are no objects on the heap available for garbage collection, the JVM may throw OutOfMemoryException.
The finalize () method is run before the object is deleted from the heap by garbage collection. We recommend not writing any code with the finalize () method.
What is an initialization block?
Initialize data block & mdash& mdash; Code that runs when an object is created or a class is loaded.
There are two types of initialization data blocks:
Static initializer: the code that runs when the class is loaded
Instance initializer: the 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 runs only when the class is first loaded. Only static variables can be accessed in the 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 = new InitializerExamples(); } }
Sample output
Static Initializer Count when Static Initializer is run is 0.
What is an instance initialization block?
Let's look at an example: each time an instance of a class is created, the code in the instance initializer runs.
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(); } }
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
What is a regular expression?
Regular expressions make it easy to parse, scan, and split strings. Regular expressions commonly used in Java & mdash& mdash; Pattern, matcher and scanner classes.
What is tokenization?
Tokenization refers to dividing a string into several substrings based on the separator. For example, separator; 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.
String. The 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]
How to 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", e]
How do I add hours to a date object?
Now, let's look at how to add hours to a date object. All date operations on date can only be completed 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 milliseconds. Look at the following example.
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 I format date objects?
Formatting the date needs to be done using the dateformat class. Let's look at a few examples.
//Formatting Dates System.out.println(DateFormat.getInstance().format( date));//10/16/12 5:18 AM
The formatted date with locale is as follows:
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 purpose of calendar class in Java?
Calendar Class (YouTube video link)- https://www.youtube.com/watch?v=hvnlYbt1ve0 )Used to process dates in Java. The calendar class provides a simple way to increase and decrease the number of days, months, and years. It also provides many details related to dates (which day of the year, which week, etc.)
How to get an instance of 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();
Explain some important methods in calendar class?
It is not difficult to set the day, month or year on the calendar object. Call the appropriate constant set method for 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, 2010);
Calendar get method
To get information about a specific date & mdash& mdash; September 24, 2010. We can use the calendar get method. The passed parameters represent the values we want from calendar & mdash& mdash; Day or month or year or & hellip& hellip; 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.SUNDAY
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 number format of the default locale
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 default locale
System.out.println(NumberFormat.getCurrencyInstance().format(40324.31f));//$40,324.31
Format currency using locale
Format currency using Dutch locale:
System.out.println(NumberFormat.getCurrencyInstance(new Locale("nl")).format(40324.31f));//? 40.324,31
License
This article, as well as any relevant source code and files, is based on the code project open license (cpol).
English Original: advanced Java interview questions translation: Codeco