Summary of 20 advanced Java face questions

Source: Internet
Author: User
Tags dateformat locale

This is the first part of a series of advanced Java interview questions. This section discusses Java core issues such as mutable parameters, assertions, garbage collection, initializers, tokens, dates, calendars, and so on.

    1. What is a mutable parameter?
    2. The purpose of the assertion?
    3. When do I use assertions?
    4. What is garbage collection?
    5. Use an example to explain garbage collection?
    6. When do I run a garbage collection?
    7. Best Practices for garbage collection?
    8. What is a block of initialization data?
    9. What is a static initializer?
    10. What is an instance initialization block?
    11. What is a regular expression?
    12. What is token?
    13. Give an example of a token?
    14. How do I use the Scanner class (Scanner Class) token?
    15. How do I add an hour (hour) to a Date object (date Objects)?
    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 of the important methods in calendar classes?
    20. What is the purpose of the numeric formatting class (number format Class)?

What is a mutable parameter?

Variable parameters allow methods to invoke different numbers of parameters. Take a look at the summation method in the example below. This method can call 1 int parameters, or 2 int parameters, or multiple int parameters.

//int (type) followed ... (three dot ' s) is syntax of a variable argument.      Public intSumint... numbers) {        //inside the method A variable argument is similar to an array. //Number can treated as if it is declared as int[] numbers;        intsum = 0;  for(intnumber:numbers) {Sum+=Number ; }        returnsum; }     Public Static voidMain (string[] args) {Variableargumentexamples example=NewVariableargumentexamples (); //3 ArgumentsSystem.out.println (Example.sum (1, 4, 5));//Ten//4 ArgumentsSystem.out.println (Example.sum (1, 4, 5, 20));// -//0 ArgumentsSystem.out.println (Example.sum ());//0}
The purpose of the assertion?

The assertion was introduced in Java 1.4. It allows you to verify assumptions. If the assertion fails (that is, returns false), 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 ;}
When do I use assertions?

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

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 are no longer required to be referenced from the heap.

Use an example to explain garbage collection?

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

void method () {    new GregorianCalendar (2000,10,30);    SYSTEM.OUT.PRINTLN (calendar);}

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

When the function finishes executing, the reference variable calendar is no longer valid. Therefore, references to objects are not created in the method.

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

When do I run a garbage collection?

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

    • Heap is low on available memory
    • CPU Idle
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 outofmemoryexception when the memory is full and no objects on the heap are available for garbage collection.

An object runs the Finalize () method before it is removed from the heap by garbage collection. We recommend that you do not write any code with the Finalize () method.

What is a block of initialization data?

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

There are two types of initialization data blocks:

Static initializers: Code that runs when a class is loaded

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

What is a static initializer?

Take a look at the following example: static{  } The code between and is called a static initializer. It runs only when the class is loaded for the first time. Only static variables can be accessed in the static initializer. Although three instances were created, the static initializer runs only once.

 Public classInitializerexamples {Static intcount; inti; Static{        //This is a static initializers.        Run only if Class is first loaded. //Only static variables can accessedSystem.out.println ("Static Initializer"); //i = 6;//COMPILER ERRORSystem.out.println ("Count when Static Initializer are run is" +count); }     Public Static voidMain (string[] args) {Initializerexamples example=NewInitializerexamples (); Initializerexamples example2=NewInitializerexamples (); Initializerexamples Example3=NewInitializerexamples (); }}

Sample output

0.
What is an instance initialization block?

Let's take a look at an example: every time you create an instance of a class, the code in the instance initializer runs.

 Public classInitializerexamples {Static intcount; inti; {        //This was an instance initializers.        Run every time an object is created. //static and instance variables can be accessedSystem.out.println ("Instance Initializer"); I= 6; Count= Count + 1; System.out.println ("Count when Instance Initializer are run is" +count); }     Public Static voidMain (string[] args) {Initializerexamples example=NewInitializerexamples (); Initializerexamples example1=NewInitializerexamples (); Initializerexamples example2=NewInitializerexamples (); }}

Sample output

Instance Initializer       1      Instance Initializer      2      Instance Initializer      3
What is a regular expression?

Regular expressions make it easy to parse, scan, and split strings. Regular expressions commonly used in Java--patter,matcher and scanner classes.

What is token?

Token refers to dividing a string into substrings based on a delimiter. For example, a delimiter; a split string ac;bd;def;e to four substrings, ac bd def e .

The delimiter itself can also be a common regular expression.

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

Give an example of a token?
Private Static void tokenize (String string,string regex) {    = string.split (regex);    System.out.println (arrays.tostring (tokens));} Tokenize ("ac;bd;def;e", ";"); // [AC, BD, Def, E]

How do I use the Scanner class (Scanner Class) token?

Private Static void Tokenizeusingscanner (String string,string regex) {    new  Scanner (string);    Scanner.usedelimiter (regex);    ListNew arraylist<string>();      while (Scanner.hasnext ()) {        Matches.add (Scanner.next ());    }    System.out.println (matches);} Tokenizeusingscanner ("ac;bd;def;e", ";"); // [AC, BD, Def, E]
How do I add an hour (hour) to a Date object (date Objects)?

Now, let's look at adding 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 add 6 hours, then we need to convert 6 hours into milliseconds. 6 hours = 6 * 60 * 60 * 1000 Ms. Take a look at the example below.

New Date (); // increase time by 6 hrsdate.settime (Date.gettime () + 6 * * * +); SYSTEM.OUT.PRINTLN (date); // Decrease time by 6 hrs New  -6 * * +); SYSTEM.OUT.PRINTLN (date);
How do I format a Date object?

The formatted 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 the locale is as follows:

System.out.println (Dateformat.getdateinstance (Dateformat.full,NewLocale ("It", "it") ). Format (date);//marted&ldquo; ottobreSystem.out.println (Dateformat.getdateinstance (Dateformat.full, Locale.italian). Format (date);//marted&ldquo; ottobre//This uses default locale USSystem.out.println (Dateformat.getdateinstance (dateformat.full). Format (date));//Tuesday, October ,System.out.println (Dateformat.getdateinstance (). Format (date);//Oct, aSystem.out.println (Dateformat.getdateinstance (dateformat.short). Format (date));//10/16/12System.out.println (Dateformat.getdateinstance (dateformat.medium). Format (date));//Oct, aSystem.out.println (Dateformat.getdateinstance (dateformat.long). Format (date));//October,
What is the purpose of the Calendar class in Java?

The Calendar class (YouTube video link-https://www.youtube.com/watch?v=hvnlYbt1ve0) 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 (which day of the year?). What week? And so on

How do I get an instance of the Calendar class in Java?

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

//COMPILER ERRORCalendar calendar = calendar.getinstance ();  
Explain some of the important methods in the Calendar class?

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

Calendar.set (calendar.date,8); // 8-septemberCalendar.set (Calendar.year, 2010);

Calendar Get method

To get information for 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--day or month or year or ... Examples of values you can get from the calendar are:

System.out.println (Calendar.get (calendar.year)); //  . System.out.println (Calendar.get (calendar.month)); // 8 System.out.println (Calendar.get (calendar.date)); //  - System.out.println (Calendar.get (calendar.week_of_month)); // 4 System.out.println (Calendar.get (calendar.week_of_year)); //  the System.out.println (Calendar.get (calendar.day_of_year)); // 267 System.out.println (Calendar.getfirstdayofweek ()); // 1-Calendar.sunday
What is the purpose of the numeric formatting class (number format Class)?

Number formats are used to format numbers into different regions and in different formats.

Number format using the default locale

System.out.println (Numberformat.getinstance (). Format (321.24f)); // 321.24

Use number formats for locales

Format numbers using the Dutch locale:

System.out.println (numberformat.getinstance ( "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

Formatting currencies using the default locale

System.out.println (Numberformat.getcurrencyinstance (). Format (40324.31f)); // $40,324.31

Format currency using locale settings

Format currency using the Dutch locale:

System.out.println (numberformat.getcurrencyinstance ( "NL")). Format (40324.31f)); // ? 40.324,31
License

This article, as well as any related source code and files, is based on the code Project Open License (Cpol).

Link: http://www.codeceo.com/article/20-java-advanced-interview-questions.html
English Original: Advanced Java interview Questions
Translation Code Agricultural Network-Xiao Feng

Summary of 20 advanced Java face questions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.