Java interview questions featured two

1, GC is the What? Why should there be GC?
A: GC is a garbage collection means, memory handling is where programmers prone to problems, and forget or false memory recovery program will lead to instability or even system crashes, GC functionality provided by Java can automatically monitor the object exceeds the scope so as to achieve the purpose of automatically reclaims the memory, Java language does not provide a display method operation of the release of allocated memory. Java programmers do not have to worry about memory management, because the garbage collector will automatically be managed. To one garbage collection request, invoke the following:. System.gc () or Runtime.getRuntime () gc (), but can be masked JVM garbage recycling call display.
Garbage collection can effectively prevent memory leaks, efficient use of memory can be used. Garbage collector is usually as a separate low priority thread to run, heap memory is dead or not used for a long time to clear and recover under unpredictable circumstances, the programmer can not call for real-time garbage collector all of an object or objects for garbage collection. Java in the early birth, garbage collection is one of the biggest highlights of Java, because the server-side programming required to effectively prevent memory leaks, but things have changed, and now Java's garbage collection has become something to be criticized. IOS mobile intelligent terminal system has generally feel better user experience than Android system, in which a deep-seated reason is that the unpredictable nature of the Android system of garbage collection.

NOTE: There are many, including garbage collection mechanism: generational copy garbage collection, marking garbage collection, incremental garbage collection and other means. Standard Java process both stack heap there. Save the original stack type local variables, stack holds the object to be created. Java platform for heap memory recovery and reuse of the basic algorithm is called mark and sweep, but it has been improved Java, a "generational garbage collection." This approach will follow the life cycle of a Java object heap memory is divided into different areas, garbage collection process, the object might move to a different area:

  • Eden (Eden): This is the birth of the first target area, and for most objects, this is their only existed in the area.
  • Survivors Park (Survivor): From the Garden of Eden survived down the object will be moved here.
  • Lifetime Yang Garden (Tenured): This is the fate of the surviving old enough to object. The young generation collection (Minor-GC) had> process is not going to touch this place. When the young generation can not collect objects into the park enjoying life, it will trigger a full collection (Major-GC), there may also involve compression, in order to free up enough space for large objects.

Associated with garbage collection JVM parameters:

-Xms / -Xmx - Maximum size of the initial heap size / heap
-Xmn - the young generation heap size
-XX: -DisableExplicitGC - let System.gc () does not have any effect
-XX: + PrintGCDetails - GC print details
-XX: + PrintGCDateStamps - GC stamp printing operation
-XX: NewSize / XX: MaxNewSize - set new generation size / maximum size CENOZOIC
-XX: NewRatio - Older Generation ratio can be set and the new generation
-XX: PrintTenuringDistribution - set after each new generation GC output distribution in the target age of the survivors Paradise
-XX: InitialTenuringThreshold / -XX: MaxTenuringThreshold: set the initial value of the old year and the maximum threshold
-XX: TargetSurvivorRatio: set target utilization surviving area

2, String s = new String ( "xyz"); created several String Object?
A: The two objects, a static area of "xyz", with a new one is created in the object on the heap.

3, abstract class and normal class differences:
A: The class contains abstract methods is called an abstract class, but that does not mean an abstract class can have only abstract methods, and general category, as it also can have member variables and common member method. Note that there are abstract classes and ordinary classes three differences:
1) abstract method must be public or protected (because if it is private, it is not inherited by subclasses, subclasses can not implement this method), the default is public by default. .
2) An abstract class can not be used to create objects;
3) if a class inherits from an abstract class, the subclasses of the abstract parent class must implement. If the subclass does not realize the abstract parent class method, it must also be defined as a subclass of an abstract class.
In other respects, the abstract class and normal class and there is no difference

4, the interface is inheritable (extends) the interface? Whether abstract class can implement (implements) interfaces? Abstract class is inheritable specific class (concrete class)?
Answer: The interface can be inherited interfaces, and supports multiple inheritance. An abstract class can implement (the implements) interfaces, classes inherit the abstract class can inherit particular abstract class.

5, a ".java" if the source file can contain multiple class (not an internal class)? What are the limits?
A: Yes, but a source file can only have a public class (public class) and the file name and class name must be fully consistent with the public class.

6, Anonymous Inner Class (anonymous inner classes) can inherit other classes? Can I implement an interface?
A: You can inherit from other classes or implement other interfaces, commonly used in this way Swing programming and the development of Android to implement event listeners and callbacks.

7, inner class can refer to its members containing class (outside of class) do? Are there any restrictions?
A: An inner class object can access the founding members of its outer class object, including private members.

8, Java's final keyword in what usage?
A: (1) modifying classes: the class can not be inherited representation; (2) modification methods: Method representation can not be rewritten; (3) modification of variables: variables can only represent an assignment can not be modified after the (constant).

class A {

    static {
        System.out.print("1");
    }

    public A() {
        System.out.print("2");
    }
}

class B extends A{

    static {
        System.out.print("a");
    }

    public B() {
        System.out.print("b");
    }
}

public class Hello {

    public static void main(String[] args) {
        A ab = new B();
        ab = new B();
    }

}

A: Execution result: 1a2b2b. When you create an object constructor is calling sequence: initialize static member, and then call the parent class constructor, then initialize non-static member, and finally call itself constructor.

Tip: If you can not give the correct answer to this question, indicating that question 21 Java class loading mechanism is not yet fully understood before, and quickly look and see.

9, the conversion between data types: how to convert a string primitive data type? How to convert basic data types to strings?
A: The calling method parseXXX (String) corresponding to the basic data types of packaging or valueOf (String) to return the corresponding basic type; a method in which basic data types and the empty string ( "") connected to (+) i.e. its corresponding character string is obtained; another method is to call the class string valueOf () method returns a string corresponding

10, and how to reverse the replacement string?
A: Many methods can write your own implementations can also use methods of the String or StringBuffer / StringBuilder in. There are a common plane is achieved questions reversing recursive string, code as follows:

    public static String reverse(String originStr) {
        if(originStr == null || originStr.length() <= 1) 
            return originStr;
        return reverse(originStr.substring(1)) + originStr.charAt(0);
    }

11, how to GB2312 encoded string into ISO-8859-1 encoded string?
A: The code is as follows:

String s1 = "你好";
String s2 = new String(s1.getBytes("GB2312"), "ISO-8859-1");

12, the date and time:
how to get the date, hours, minutes, seconds?
How to get the number of milliseconds from at 0:00:00 on January 1, 1970 to the present?
How to get the last day of a month?
How to format date?

A: Question 1: Create java.util.Calendar instance, calls its get () method passing different parameters to obtain the value of the parameter corresponds. 8 may be used in Java java.time.LocalDateTimel to get the code shown below.

public class DateTimeTest {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        System.out.println(cal.get(Calendar.YEAR));
        System.out.println(cal.get(Calendar.MONTH));    // 0 - 11
        System.out.println(cal.get(Calendar.DATE));
        System.out.println(cal.get(Calendar.HOUR_OF_DAY));
        System.out.println(cal.get(Calendar.MINUTE));
        System.out.println(cal.get(Calendar.SECOND));

        // Java 8
        LocalDateTime dt = LocalDateTime.now();
        System.out.println(dt.getYear());
        System.out.println(dt.getMonthValue());     // 1 - 12
        System.out.println(dt.getDayOfMonth());
        System.out.println(dt.getHour());
        System.out.println(dt.getMinute());
        System.out.println(dt.getSecond());
    }
}

Question 2: The following methods can get the number of milliseconds.

Calendar.getInstance().getTimeInMillis();
System.currentTimeMillis();
Clock.systemDefaultZone().millis(); // Java 8

Problem 3: The code as shown below.

Calendar time = Calendar.getInstance();
time.getActualMaximum(Calendar.DAY_OF_MONTH);

Question 4: subclass (e.g. SimpleDateFormat class) in use java.text.DataFormat format (Date) method can be formatted date. Java 8 can be used to format the date and time java.time.format.DateTimeFormatter code shown below.

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

class DateFormatTest {

    public static void main(String[] args) {
        SimpleDateFormat oldFormatter = new SimpleDateFormat("yyyy/MM/dd");
        Date date1 = new Date();
        System.out.println(oldFormatter.format(date1));

        // Java 8
        DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        LocalDate date2 = LocalDate.now();
        System.out.println(date2.format(newFormatter));
    }
}

Supplementary: Java date and time API has always been something to be criticized, in order to solve this problem, Java 8 introduces new date and time API, including LocalDate, LocalTime, LocalDateTime, Clock, Instant other categories, these classes the design uses the same mode, so is thread-safe design.

13, print the current time yesterday.

import java.util.Calendar;

class YesterdayCurrent {
    public static void main(String[] args){
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        System.out.println(cal.getTime());
    }
}

In Java 8, the following code can be used to achieve the same functionality.

import java.time.LocalDateTime;

class YesterdayCurrent {

    public static void main(String[] args) {
        LocalDateTime today = LocalDateTime.now();
        LocalDateTime yesterday = today.minusDays(1);

        System.out.println(yesterday);
    }
}
Published 444 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/zt2650693774/article/details/105004812