Everyone should know that Java is currently one of the most popular computer languages, the most popular computer language for programmers for several years in a row, so every year new Java programmers are also numerous. Are these new Java programmers in the hole or in the field? That depends on how they feel about the Java language. In any case, questions will have to go through an interview before entering the job. Below is a list of 20 common Java interview questions that must be asked to get the job.

1. What are the features of object-oriented?

A: Object-oriented features mainly have the following aspects:

Abstract: Abstract is the process of constructing a class by summarizing the common characteristics of a class of objects, including data abstraction and behavior abstraction. Abstractions focus only on what properties and behaviors an object has, not on the details of those behaviors.

Inheritance: Inheritance is the process of taking inherited information from an existing class and creating a new class. Classes that provide inheritance information are called superclasses (superclasses, base classes); The class that gets the inheritance information is called a subclass (derived class). Inheritance gives some continuity to a changing software system, and is also an important means of encapsulating variable factors in the program (please read Dr. Yan Hong’s “Java and Patterns” or the section on bridge patterns in “Design Patterns Refinement” if you don’t understand).

Encapsulation: Encapsulation is generally thought of as binding data to methods that manipulate it, and data can only be accessed through defined interfaces. The essence of object orientation is to represent the real world as a series of completely autonomous, closed objects. The methods we write in our classes encapsulate the implementation details; We write a class that encapsulates data and data operations. It can be said that encapsulation is to hide everything that can be hidden, providing only the simplest programming interface to the outside world (think of the difference between ordinary washing machine and automatic washing machine, automatic washing machine is obviously better packaging and therefore easier to operate; The smartphones we use today are packaged well enough to do everything with a few buttons.)

Polymorphism: Polymorphism is the practice of allowing objects of different subtypes to respond differently to the same message. Simply put, the same object reference calls the same method but does different things. Polymorphism is divided into compile-time polymorphism and run-time polymorphism. If an object’s methods are viewed as services that the object provides to the outside world, then runtime polymorphism can be interpreted as: When the service system to provide A system access B, B system has A variety of way of the services they offer, but everything is transparent for A system (like electric razor is A system, its power supply system is B, B system can use the batteries or use alternating current (ac), and even may be solar energy, A system will only by the method of class B object call power supply, But it is not known what the underlying implementation of the power supply system is or how it is powered). Method overload implements compile-time polymorphism (also known as pre-binding), while method override implements runtime polymorphism (also known as post-binding). Runtime polymorphism is the essence of object orientation. To implement polymorphism, you need to do two things: 1). Method rewriting (when a subclass inherits a parent class and overwrites an existing or abstract method in the parent class); 2). Object modeling (using a parent type reference to refer to a subtype object, so that the same reference calls the same method and behaves differently depending on the subtype object).

Want to work on it or are genuinely interested in it. You can ask me for some basic learning videos, Q number: 3300863615, this is free, I hope students don’t take it for granted when looking for me, after all, it is my efforts, I hope you really want to learn Java heart, I will do my best to help you become an excellent programmer. There are learning groups to exchange learning to help each other solve various problems Java Web problems, there are specially-assigned to explain the class. As long as they are serious, in addition to communication, you will learn a lot of Java Web in other places to learn the latest technology and knowledge as well as project combat!

2, access modifiers, public, private, protected, and don’t write what is the difference between (the default)?

A: Members of a class that do not write access modifiers default to default. The default is public for other classes in the same package and private for classes not in the same package. Protected is public for subclasses and private for classes that are not parent-child in the same package. In Java, external class modifiers can only be public or default, and class members (including inner classes) can have the above four modifiers.

Is String the most basic data type?

Answer: No. There are only eight basic data types in Java: byte, short, int, long, float, double, char, Boolean. Except for primitive type and enumeration type, all the other types are reference types.

4, float f = 3.4; Is that correct?

Answer: Not true. 3.4 is a double. Assigning a double to a float is down casting and will result in a loss of precision. Therefore, a cast float f =(float)3.4 is required. Or float f = 3.4f; .

5, short s1 = 1; s1 = s1 + 1; Didn’t you? short s1 = 1; s1 += 1; Didn’t you?

Answer: for short s1 = 1; s1 = s1 + 1; Since 1 is an int, s1+1 is also an int and requires a cast to assign to short. Short s1 = 1; s1 += 1; It compiles correctly because s1+= 1; S1 = (short)(s1 + 1); There is an implicit cast.

Does Java have a Goto?

A: Goto is a reserved word in Java and is not used in the current version of Java. The appendix to The book “The Java Programming Language” by James Gosling gives a list of Java keywords, including goto and const, but these are not currently available. Therefore, some places call it reserved word, but the term reserved word should have a broader meaning, because programmers familiar with C know that words or combinations of words that have special meaning are regarded as reserved words.)

What is the difference between an int and an Integer?

A: Java is an almost pure object-oriented programming language, but it still introduces basic data types for programming convenience, but in order to treat these basic data types as objects, Java introduces a corresponding Wrapper class for each basic data type. The wrapper class for int is Integer, and since Java 5 automatic boxing/unboxing has been introduced to make them interchangeable.

Java provides a wrapper type for each primitive type:

Primitive types: Boolean, char, byte, short, int, long, float, double

Wrapper types: Boolean, Character, Byte, Short, Integer, Long, Float, Double

class AutoUnboxingTest {public static void main(String[] args) {

Integer a = new Integer(3);

Integer b = 3; // automatically box 3 into Integer type int c = 3;

System.out.println(a == b); // false Two references do not refer to the same object system.out.println (a == c); // select int from c;

}

Recently, I encountered an interview question, which is also related to automatic packing and unpacking. The code is as follows:

public class Test03 {public static void main(String[] args) {

Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;

System.out.println(f1 == f2);

System.out.println(f3 == f4);

}

}

It’s easy to assume that both outputs are either true or false if you don’t know what you’re doing. The first thing to note is that the variables f1, f2, f3, and F4 are all Integer object references, so the == operation below compares references rather than values. What is the nature of packing? When we assign an int value to an Integer object, valueOf, the static method of the Integer class, is called. If you look at valueOf’s source code, you can see what happens.

public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i);

}

IntegerCache is the inner class of Integer, and its code looks like this: / Cache to support the object identity semantics of autoboxing for values between -128 and 127 (inclusive) as required by JLS. The cache is initialized on first usage. The size of the cache may be controlled by the {@code -XX:AutoBoxCacheMax=} option. During VM initialization, java.lang.Integer.IntegerCache.high property may be set and saved in the private system properties in the sun.misc.VM class.

*/private static class IntegerCache {static final int low = -128; static final int high; static final Integer cache[]; static {// high value may be configured by propertyint h = 127; String integerCacheHighPropValue =

sun.misc.VM.getSavedProperty(“java.lang.Integer.IntegerCache.high”); if (integerCacheHighPropValue ! = null) {try {int i = parseInt(integerCacheHighPropValue);

i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUEh = Math.min(i, Integer.MAX_VALUE – (-low) -1);

} catch( NumberFormatException nfe) {// If the property cannot be parsed into an int, ignore it.}

}

high = h;

cache = new Integer[(high – low) + 1]; int j = low; for(int k = 0; k < cache.length; k++)

cache[k] = new Integer(j++); // range [-128, 127] must be interned (JLS7 5.1.7) Assert IntegerCache. High >= 127;

}

private IntegerCache() {}

}

To put it simply, if the Integer literal is between -128 and 127, then no new Integer object is created, but the Integer object in the constant pool is referenced directly, so f1==f2 is true and F3 ==f4 is false.

Note: the more seemingly simple the interview questions, the more mystery, the need for the interviewer to have considerable skills.

8, Explain the use of stack, heap and static area in memory.

A: Usually we define a variable of a basic data type, a reference to an object, and the field storage of function calls all use the stack space in memory; Objects created by the new keyword and constructor are placed in the heap space; Literals in the program such as the directly written 100, “hello”, and constants are placed in the static section. Stack space is the fastest to operate but the stack is small. Usually a large number of objects are placed in the heap space. In theory, the entire memory that is not used by other processes or even virtual memory on the hard disk can be used as heap space.

Want to work on it or are genuinely interested in it. You can ask me for some basic learning videos, Q number: 3300863615, this is free, I hope students don’t take it for granted when looking for me, after all, it is my efforts, I hope you really want to learn Java heart, I will do my best to help you become an excellent programmer. There are learning groups to exchange learning to help each other solve various problems Java Web problems, there are specially-assigned to explain the class. As long as they are serious, in addition to communication, you will learn a lot of Java Web in other places to learn the latest technology and knowledge as well as project combat!

String str = new String(“hello”);

In the above statement, the variable STR is placed on the stack, the string object created with new is placed on the heap, and the literal “hello” is placed in the static section.

9. When an object is passed as a parameter to a method that changes the object’s properties and returns the changed result, is it value passing or reference passing?

Answer: Value passing. Method calls in the Java language only support value passing of parameters. When an object instance is passed to a method as a parameter, the parameter’s value is a reference to that object. Properties of objects can be changed during invocation, but changes to object references do not affect the caller. C++ and C# can change the value of an argument passed in by passing a reference or passing out a parameter. It is possible to write code like this in C#, but not in Java.

using System; namespace CS01 {class Program {public static void swap(ref int x, ref int y) {int temp = x;

x = y;

y = temp;

}public static void Main (string[] args) {int a = 5, b = 10;

swap (ref a, ref b); // a = 10, b = 5; Console.WriteLine (“a = {0}, b = {1}”, a, b);

}

}

}

Description: The inconvenience of not passing references in Java has not been improved in Java 8, which is why there are so many Wrapper classes in code written in Java (putting references that need to be modified through method calls into a Wrapper class and passing the Wrapper object into the method). This only leads to bloated code, especially for developers who have made the transition from C and C++ to Java programmers.

10. The difference between Overload and Override. Can overloaded methods be differentiated by return type?

Answer: Method overloading and overwriting are both ways of implementing polymorphism, the difference being that the former implements compile-time polymorphism, while the latter implements runtime polymorphism. Overloading occurs when a method with the same name has different argument lists (different parameter types, different number of arguments, or both) and is considered overloaded. Rewriting occurs between a subclass and its parent class. Rewriting requires that the subclass overridden method has the same return type as the parent overridden method, is more accessible than the parent overridden method, and cannot declare more exceptions than the parent overridden method (Richter’s substitution principle). Overloading has no special requirements for return types.

Question: “Why can’t overload be distinguished by return type?”

Describe how the JVM loads class files.

A: The loading of classes in the JVM is done by the ClassLoader and its subclasses. The ClassLoader in Java is an important component of the Java runtime system that finds and loads classes in class files at run time.

Because of Java’s cross-platform nature, a compiled Java source program is not an executable program, but one or more class files. When a Java program needs to use a class, the JVM ensures that the class has been loaded, wired (validated, prepared, and parsed), and initialized. Loading a class refers to reading the data from the class’s.class file into memory, usually by creating a byte array that reads into the.class file and generates a class object corresponding to the loaded class. After loading, the Class object is not complete, so the Class is not available at this point. When the class is loaded, it enters the connect phase, which consists of three steps: validation, preparation (allocating memory for static variables and setting default initial values), and parsing (replacing symbolic references with direct references). Finally, the JVM initializes the class, including: 1) if the class has a direct parent that has not already been initialized, then initialize the parent first; 2) If there are initializers in the class, execute those initializers in turn.

Want to work on it or are genuinely interested in it. You can ask me for some basic learning videos, Q number: 3300863615, this is free, I hope students don’t take it for granted when looking for me, after all, it is my efforts, I hope you really want to learn Java heart, I will do my best to help you become an excellent programmer. There are learning groups to exchange learning to help each other solve various problems Java Web problems, there are specially-assigned to explain the class. As long as they are serious, in addition to communication, you will learn a lot of Java Web in other places to learn the latest technology and knowledge as well as project combat!

The loading of classes is done by class loaders, including the root loader (BootStrap), Extension loader (Extension), System loader (System), and user-defined ClassLoader (a subclass of java.lang.classloader). Since Java 2(JDK 1.2), the class loading process has adopted the parent delegate mechanism (PDM). PDM ensures the security of the Java platform. In this mechanism, the Bootstrap of the JVM is the root loader, while all other loaders have one or only one parent class loader. The loading of a class is first requested by the parent class loader, and only when the parent class loader is unable to do so is the subclass loader loaded by itself. The JVM does not provide a reference to Bootstrap to a Java program. Here are a few notes about class loaders:

Bootstrap: Generally implemented in native code, responsible for loading the JVM base core libraries (rt.jar).

Extension: Load the class library from the directory specified by the java.ext.dirs system property. Its parent loader is Bootstrap.

System: also called application class loader, its parent is Extension. It is the most widely used class loader. It records classes from the directory specified by the environment variable CLASspath or the system property java.class.path and is the default parent of a user-defined loader.

12. What are the similarities and differences between abstract classes and interfaces?

A: Neither abstract classes nor interfaces can be instantiated, but references to abstract classes and interface types can be defined. A class that inherits an abstract class or implements an interface must implement all of its abstract methods. Otherwise, the class still needs to be declared as abstract. An interface is more abstract than an abstract class, because an abstract class can define constructors, can have abstract methods and concrete methods, whereas an interface cannot define constructors and its methods are all abstract methods. Members in an abstract class can be private, default, protected, or public, while members in an interface are all public. Member variables can be defined in an abstract class, whereas member variables defined in an interface are actually constants. Classes with abstract methods must be declared as abstract classes, and abstract classes need not have abstract methods.

The difference between a Static Nested Class and an Inner Class?

A: Static Nested classes are internal classes that are declared Static and can be instantiated independent of external Class instances. The normal inner class needs to be instantiated by the outer class, and the syntax looks weird, as shown below.

/* public class Poker {public class Poker {

Private static String[] suites = {” Spades “, “Hearts “,” Flowers “, “diamonds “}; private static String[] suites = {” Spades “,” hearts “, “flowers “,” diamonds “};

private static int[] faces = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};

private Card[] cards; /* constructor /public Poker() {

cards = new Card[52]; for(int i = 0; i < suites.length; i++) {for(int j = 0; j < faces.length; j++) {

cards[i * 13 + j] = new Card(suites[i], faces[j]);

}

}

}/* public void shuffle() {for(int I = 0, len = card.length; i < len; i++) {int index = (int) (Math.random() * len);

Card temp = cards[index];

cards[index] = cards[i];

cards[i] = temp;

}

} @param index public Card deal(int index) {return cards[index];

}/** Card class (one card) [Inner class]

*/public class Card {

private String suite; // private int face; Public Card(String suite, int face) {this.suite = suite; this.face = face;

}@Overridepublic String toString() {String faceStr = “”; switch(face) {case 1: faceStr = “A”; break; case 11: faceStr = “J”; break; case 12: faceStr = “Q”; break; case 13: faceStr = “K”; break; default: faceStr = String.valueOf(face);

}return suite + faceStr;

}

}

}

Test code:

class PokerTest {public static void main(String[] args) {

Poker poker = new Poker();

poker.shuffle(); Card c1 = poker.deal(0); Poker.Card c2 = poker.new Card(” heart “, 1); // Create a card system.out.println (c1); // system.out.println (c2); // Print: heart A}

}

Interview question – Where in the following code do compilation errors occur?

class Outer {class Inner {}public static void foo() { new Inner(); }public void bar() { new Inner(); }public static void main(String[] args) {new Inner();

}

}

Note: Java non-static inner class objects are created by relying on their outer class objects,

Methods foo and main in the interview question above are static methods. Static methods do not have this.

That is, there is no such thing as an external class object, so you cannot create an inner class object. If you want to create an inner class object in a static method, you can do this:

new Outer().new Inner();

Will there be memory leaks in Java? Please briefly describe.

A: Java is theoretically free of memory leaks because of its garbage collection (GC) mechanism (which is one of the reasons Java is so widely used for server-side programming); However, in real development, there may be useless but reachable objects that cannot be collected by GC, and thus memory leaks can occur. For example, Hibernate Session(level 1 cache) objects are persistent and will not be collected by the garbage collector. However, these objects may contain garbage objects that may leak memory if they are not closed or flushed. The code in the following example also causes memory leaks.

import java.util.Arrays; import java.util.EmptyStackException; public class MyStack {private T[] elements; private int size = 0; private static final int INIT_CAPACITY = 16; public MyStack() {

elements = (T[]) new Object[INIT_CAPACITY];

}public void push(T elem) {

ensureCapacity();

elements[size++] = elem;

}public T pop() {if(size == 0)throw new EmptyStackException(); return elements[–size];

}private void ensureCapacity() {if(elements.length == size) {

elements = Arrays.copyOf(elements, 2 * size + 1);

}

}

}

The code above implements a stack (FILO) structure that doesn’t seem to have any obvious problems at first glance, and it can even pass the various unit tests you write. The pop method, however, has a memory leak problem. When we pop an object from the stack, the object is not garbage collected, even if the application that uses the stack no longer references the object, because the stack maintains out-of-date references to the object. In languages that support garbage collection, memory leaks are hidden and are essentially unconscious object retention. If an object reference is inadvertently retained, the garbage collector does not process that object or any other object referenced by that object. Even if there are only a few objects, this can result in many objects being excluded from the garbage collection, which can have a significant impact on performance. In extreme cases, Disk Paging(exchanging data between physical memory and virtual memory of hard disks) can be triggered, or even cause outofMemoryErrors.

If you are looking for a job or just out of school, or have been working but often feel a lot of difficult, feel that their Java learning is not enough to continue to learn, want to change careers afraid of learning not, you can add Q3300863615 to learn to consult Java to continue to learn. And there are free videos for you to pick up.

15, how to implement object cloning?

A: There are two ways:

1). Implement Cloneable interface and override clone() method in Object class;

2). Implement Serializable interface, clone through object serialization and deserialization, you can realize the real deep clone, the code is as follows.

import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class MyUtil {private MyUtil() {throw new AssertionError();

}public static T clone(T obj) throws Exception {

ByteArrayOutputStream bout = new ByteArrayOutputStream();

ObjectOutputStream oos = new ObjectOutputStream(bout);

oos.writeObject(obj);

ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());

ObjectInputStream ois = new ObjectInputStream(bin); return (T) ois.readObject(); // These two memory-based streams can release resources as soon as the garbage collector cleans up the object. This is different from freeing external resources such as file streams.

}

Here is the test code:

import java.io.Serializable; / * *

  • human

*/class Person implements Serializable {private static final long serialVersionUID = -9102017020286042305L; private String name; // private int age; Private Car Car; Public Person(String name, int age, Car Car) {this.name = name; this.age = age; this.car = car;

}public String getName() {return name;

}public void setName(String name) {this.name = name;

}public int getAge() {return age;

}public void setAge(int age) {this.age = age;

}public Car getCar() {return car;

}public void setCar(Car car) {this.car = car;

}@Overridepublic String toString() {return “Person [name=” + name + “, age=” + age + “, car=” + car + “]”;

}

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 / * *}

  • The car class

*/class Car implements Serializable {private static final long serialVersionUID = -5713945027627603702L; private String brand; Private int maxSpeed; Public Car(String brand, int maxSpeed) {this.brand = brand; this.maxSpeed = maxSpeed;

}public String getBrand() {return brand;

}public void setBrand(String brand) {this.brand = brand;

}public int getMaxSpeed() {return maxSpeed;

}public void setMaxSpeed(int maxSpeed) {this.maxSpeed = maxSpeed;

}@Overridepublic String toString() {return “Car [brand=” + brand + “, maxSpeed=” + maxSpeed + “]”;

}

}class CloneTest {public static void main(String[] args) {try {

Person p1 = new Person(“Hao LUO”, 33, new Car(“Benz”, 300));

Person p2 = MyUtil.clone(p1); P2.getcar ().setbrand (“BYD”); Println (p1); Person (p1); Person (p1);

} catch (Exception e) {

e.printStackTrace();

}

}

}

Note: clones based on serialization and deserialization implementations are not just deep clones,

More importantly, generic qualification allows you to check whether the object to be cloned supports serialization,

This check is done by the compiler rather than throwing an exception at run time, and this scheme is significantly superior to cloning objects using the Clone method of the Object class.

It is always better to expose problems at compile time than to leave them at run time.

What is GC? Why GC?

A: GC means garbage collection, and memory processing is the place where programmers are prone to problems. Forgetting or wrong memory collection will lead to instability or even crash of the program or system. The GC function provided by Java can automatically monitor whether the object is out of scope so as to achieve the purpose of automatic memory collection. The Java language does not provide a display operation to free allocated memory. Java programmers don’t have to worry about memory management because the garbage collector manages it automatically. To request garbage collection, one of the following methods can be called: System.gc() or Runtime.geTruntime ().gc(), but the JVM can mask the garbage collection calls displayed.

Garbage collection can effectively prevent memory leaks and efficiently use available memory. The garbage collector is typically run as a single, low-priority thread that unpredictably cleans and reclaims dead or unused objects in the heap. Programmers cannot call the garbage collector in real time to collect an object or all objects. In the early days of Java, garbage collection was one of the biggest highlights of Java, because server-side programming was required to effectively prevent memory leaks. However, time has changed, and Java’s garbage collection mechanism has become a thing of the past. Mobile intelligent terminal users generally feel that iOS system has a better user experience than Android system. One of the deep reasons lies in the unpredictability of garbage collection in Android system.

Add-on: There are many garbage collection mechanisms, including generation copy garbage collection, tag garbage collection, incremental garbage collection, and so on.

Standard Java processes have both stacks and heaps. The stack holds primitive local variables and the heap holds objects to be created. The Java platform’s basic algorithm for collecting and reusing heap memory is called mark and sweep, but Java improves on this with “generational garbage collection.”

This method divides the heap memory into different regions according to the life cycle of Java objects. During garbage collection, objects may be moved to different regions: – Eden: This is the region where objects were originally born and, for most objects, this is the only region they have ever existed. – Survivor Paradise: Survivors from The Garden of Eden are moved here. – Tenured: This is the fate of surviving subjects old enough to survive. The minor-GC process does not touch this area.

A Major GC is triggered when the younger generation can’t fit an object into a lifetime recreation park, which may also involve compression,

To make enough space for large objects. JVM parameters related to garbage collection: -xms / -xmx — Initial size of the heap/maximum size of the heap — Xmn — size of the young generation in the heap — XX: -disableexplicitGC — Make System.gc() useless — XX:+PrintGCDetails — PrintGC details -xx :+PrintGCDateStamps — PrintGC operation timestamp -xx :NewSize/XX:MaxNewSize — Set New generation size/new generation maximum size -xx :NewRatio — Can set the proportion of the old generation and new generation – XX: PrintTenuringDistribution – set up after each new generation GC output objects in the age distribution of survivors park – XX: InitialTenuringThreshold / -xx :MaxTenuringThreshold: sets the initial value and maximum value of the old age threshold. -xx :TargetSurvivorRatio: sets the target usage rate of the surviving zone

17. Date and Time:

How to get the year, month, day, hour, minute, second?

How do I get the number of milliseconds from 00:00:00 on January 1, 1970 to the present day?

How do I get the last day of a month?

How do I format dates?

A:

Problem 1: Create a java.util.calendar instance and call its get() method to pass in different parameters to get their corresponding values. This can be obtained in Java 8 using java.time.localDateTimel, as 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 – 11System.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 8LocalDateTime dt = LocalDateTime.now();

System.out.println(dt.getYear());

System.out.println(dt.getMonthValue()); // 1 – 12System.out.println(dt.getDayOfMonth());

System.out.println(dt.getHour());

System.out.println(dt.getMinute());

System.out.println(dt.getSecond());

}

}

Problem 2: The number of milliseconds can be obtained by any of the following methods.

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

Problem 3: The code is shown below.

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

Problem 4: Use the format(Date) method in a subclass of java.text.DataFormat, such as the SimpleDateFormat class, to format a Date. Java 8 can be used in Java. Time. The format. DateTimeFormatter to format the date time, code as 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 8DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern(“yyyy/MM/dd”); LocalDate date2 = LocalDate.now(); System.out.println(date2.format(newFormatter));

}

}

Supplement: Java’s date and time API has been criticized for a long time. To address this problem, Java 8 introduced a new date and time API, including classes LocalDate, LocalTime, LocalDateTime, Clock, Instant, and so on. These classes are designed to use immutable patterns and are therefore thread-safe. If you don’t understand this, please refer to my other article, Summary and Thoughts on Concurrent Programming in Java.

Compare Java with JavaSciprt.

A: JavaScript and Java are two different products developed by two companies. Java is an object-oriented programming language developed by Sun Microsystems, which is especially suitable for Internet application development. JavaScript is a Netscape product, developed to extend the capabilities of the Netscape browser, an object – and event-driven interpretive language that can be embedded in Web pages. JavaScript’s predecessor is LiveScript; Java’s predecessor is the Oak language.

Here is a comparison of the similarities and differences between the two languages:

  • Object based and Object oriented: Java is a true object oriented language, even to develop simple programs, must design objects; -JavaScript is a scripting language that can be used to create complex software that is independent of the network and interacts with users. – It is an object-based and event-driven programming language, so it provides a very rich internal Object for designers to use. – Interpret and compile: Java source code must be compiled before it can be executed. JavaScript is an interpreted programming language – its source code is not compiled and is interpreted and executed by the browser. -(Almost all browsers today use just-in-time (JIT) technology to improve JavaScript performance)- Strongly typed variables and weakly typed variables: Java uses strongly typed variable checking, that is, all variables must be declared before compilation; JavaScript variables are weakly typed – they can even be undeclared before being used, and the JavaScript interpreter checks at run time to infer their data type. – Different code formats.

What is the structure of a Java heap? What is Perm Gen space in the heap?

The JVM’s heap is the run-time data area on which all instances and arrays of classes are allocated memory. It is created when the JVM starts. The heap memory occupied by objects is reclaimed by the automatic memory management system, the garbage collector.

Heap memory is made up of living and dead objects. Live objects are accessible to the application and are not garbage collected. Dead objects are objects that are inaccessible to the application and have not yet been collected by the garbage collector. These objects occupy heap memory space until the garbage collector collects them.

20. Explain the storage performance and features of ArrayList, Vector and LinkedList.

A: ArrayList and Vector both store data in arrays that have more elements than the actual number of stored data to add and insert elements. They both allow elements to be indexed directly by ordinal number. However, inserting elements involves memory operations such as moving array elements, so indexing data is fast and inserting data is slow. The methods in Vector are thread-safe, thanks to the synchronized modifier, but perform worse than ArrayList and are already legacy containers in Java. LinkedList USES two-way linked list to achieve storage (memory scattered memory unit by attaching the reference, can form a linear structure according to the serial number index, the chain store mode compared with continuous storage arrays, memory utilization is higher), according to the serial number prior to or after the index data needed to traverse, However, only the items before and after the item need to be recorded when inserting data, so the insertion speed is fast. Vector is a legacy container (provided in earlier versions of Java, along with Hashtable, Dictionary, BitSet, Stack, and Properties) and is no longer recommended. But because ArrayList and LinkedListed are both non-thread-safe, if you have multiple threads working on the same container, It can then be converted into thread-safe containers through the synchronizedList method in the utility class Collections (this is an application of the decorator pattern, which enhances the implementation by passing existing objects into another class’s constructor to create new objects).

Supplement: Properties is a special key-value pair mapping with both keys and values as strings. It should be designed to associate a Hashtable and set its two generic parameters to String. But Properties in the Java API directly inherits Hashtable, which is an obvious abuse of inheritance. On the other hand, containers belong to utility classes. It Is A mistake to inherit utility classes. The best way to Use utility classes Is to Use HAS-A relationships (associations) or use-A relationships (dependencies). Similarly, it is incorrect for Stack classes to inherit from Vector. Sun engineers also make this kind of stupid mistake, which makes people sigh.

[How to learn Java Web] want to develop in this area or are really interested. You can ask me for some basic learning videos, Q number: 3300863615, this is free, I hope students don’t take it for granted when looking for me, after all, it is my efforts, I hope you really want to learn Java heart, I will do my best to help you become an excellent programmer. There are also people exchange learning to help each other solve various problems Java Web problems, there are special people to explain the class. As long as they are serious, in addition to communication, you will learn a lot of Java Web in other places to learn the latest technology and knowledge as well as project combat!

Q plus I have the following requirements, do not disturb the substandard:

1. I majored in Java in college, but I was frustrated in the interview after graduation and could not find a suitable job

2. I have been in the company for a long time and now I am comfortable, but I hit a wall in the interview when I change my job. Need to study in a short time, job-hopping to get a high salary

3. After attending the offline training, I have not mastered the knowledge deeply enough, and it is difficult to find employment. I want to further my study

4, already in the Java related departments work on the job, on their own career planning is not clear, dawdle

5, have a certain C language foundation, contact with Java development, want to change careers

Do not disturb the trumpet, do not like to add

This list of 20 common Java interview questions is not intended to be a rote memorization of these questions, but rather to extract from these interview questions the key features that companies value in Java, so you should understand the art of Java.