What are the features of the Java language?
- Object-oriented (encapsulation, inheritance, polymorphism);
- Platform independence, the specific performance of platform independence is that Java is “Write Once, Run any Where” language, so the program written in Java language has a good portability, and ensure this point is Java virtual machine mechanism. After virtual machines were introduced, the Java language ran on different platforms without recompiling.
- Reliability and security;
- Multithreading is supported. C++ language has no built-in multithreading mechanism, so it must call the multithreading function of the operating system to carry out multithreading program design, while Java language provides multithreading support.
- Network programming is supported and very convenient. The Java language itself is designed to simplify network programming, so the Java language not only supports network programming but also is very convenient.
- Compilation and interpretation coexist;
What’s the relationship between Java and C++, and what’s the difference?
- Both are object-oriented languages that support encapsulation, inheritance, and polymorphism;
- C++ supports Pointers, while Java has no concept of Pointers.
- C++ supports multiple inheritance, while Java does not, but allows a class to implement multiple interfaces.
- Java is a fully object-oriented language, and it eliminates structure and association in C/C++, making compilers more concise.
- Java automatically collects unwanted memory, eliminating the need for manual deletion. In C++, memory resources must be released by the program, which adds to the programmer’s burden.
- Java does not support operator overloading, which is considered a prominent feature of C++.
- Java allows preprocessing but does not support preprocessor functionality, so for preprocessing, it provides import statements that are similar to C++ preprocessors.
- Java does not support default parameter functions, while C++ does;
- C and C++ do not support string variables and use the “Null” terminator in C and C++ programs to represent the end of a string. In Java, strings are implemented using class objects (String and StringBuffer);
- The GOTO statement is a “relic” of C and C++. Java does not provide goTO statements. Although Java specifies goto as a keyword, it does not support its use, which makes programs more concise and readable.
- Java does not support automatic casts in C++ and must be cast explicitly by a program if needed.
What is the relationship between the JVM, JRE, and JDK?
JDK stands for Java Development Kit, which is a full-featured Java SDK. It has everything the JRE has, as well as a compiler (Javac) and tools (such as Javadoc and JDB). It can create and compile programs.
JRE stands for Java Runtime Environment. It is a collection of all the content needed to run a compiled Java program, including the Java Virtual Machine (JVM), Java class libraries, Java commands, and other basic artifacts. However, it cannot be used to create new programs.
The JDK contains the JRE, and the JRE contains the JVM.
What is bytecode?
Is Java a language that compiles or interprets execution?
Java can be “compiled once, run anywhere” because the JVM is customized for a variety of operating systems and platforms, and because fixed-format bytecodes (.class files) can be compiled and produced for use by the JVM on any platform. Thus, you can also see how important bytecode is to the Java ecosystem.
It is called bytecode because bytecode files are made up of hexadecimal values, and the JVM reads them in bytes in groups of two hexadecimal values. In Java, source code is typically compiled into a bytecode file using the Javac command, a. Java file from compile to run as shown in the figure below.
What are the benefits of adopting bytecode?
Java solves the problem of low efficiency of traditional interpreted languages by means of bytecode to some extent, and at the same time retains the portability of interpreted languages. So Java programs run more efficiently, and because bytecode is not specific to a particular machine, Java programs can run on many different machines without recompiling.
What is the difference between the Oracle JDK and OpenJDK?
There are probably a lot of people like me who haven’t touched or used OpenJDK before looking at this question. Here are some information I collected to answer this question that many people ignore.
- Oracle JDK versions will be released every three years, while OpenJDK versions will be released every three months;
- The OpenJDK is a reference model and is fully open source, whereas the Oracle JDK is an implementation of OpenJDK and is not fully open source;
- The Oracle JDK is more stable than the OpenJDK. The OpenJDK and Oracle JDK have nearly the same code, but the Oracle JDK has more classes and some bug fixes. Therefore, if you want to develop enterprise/business software, the Oracle JDK is recommended as it is thoroughly tested and stable. In some cases, some people have mentioned that they may encounter many application crashes while using OpenJDK, but simply switch to the Oracle JDK to solve the problem;
- The Oracle JDK provides better performance than the OpenJDK in terms of responsiveness and JVM performance;
- The Oracle JDK does not provide long-term support for upcoming releases; users must update to the latest version each time to get support;
- The Oracle JDK is licensed under the binary code License, while the OpenJDK is licensed under the GPLv2 license.
Basic grammar
What data types do Java have?
The Java language has two types of data types: basic data types and reference data types.
1. The basic data types include Boolean, float, char, byte, short, int, long, and double, as shown in the following table.
Basic types of | digits | byte | The default value |
---|---|---|---|
int | 32 | 4 | 0 |
short | 16 | 2 | 0 |
long | 64 | 8 | 0L |
byte | 8 | 1 | 0 |
char | 16 | 2 | ‘u0000’ |
float | 32 | 4 | 0f |
double | 64 | 8 | 0d |
boolean | 1 | false |
For Boolean, the official documentation is undefined and depends on the JVM vendor’s implementation. Logically it takes up 1 bit, but in practice it takes into account efficient computer storage.
The Java Virtual Machine specification says: The JVM does not provide Boolean specific bytecode instructions. Boolean data is represented by int when compiled in the JVM. The Boolean data is 4 bytes and 32 bits, and the Boolean array is encoded as Java VIRTUAL machine byte arrays. At this point, each Boolean data byte is 8 bits.
Note:
- In Java, long must be followed by L, otherwise it will be interpreted as an integer:
char a = 'h'
Char: single quotation mark,String a = "hello"
: double quotation marks
2. Reference data types are based on basic data types, including arrays, classes, and interfaces. Reference data types are user-defined to restrict the types of other data. In addition, pointer, structural, union, and enumeration types in C++ are not supported in the Java language.
Can switch work on byte, can switch work on long, and can switch work on String?
Java5 Before switch(expR), expR can be only byte, short, char, or int.
Since Java 5, enumerated types have been introduced in Java. Expr can also be enum types.
As of Java 7, expr can also be a String, but long integers are not allowed in all current versions.
What are the differences between access modifiers public, private, protected, and do not write (default)?
In Java, access control characters can be used to protect access to classes, variables, methods, and constructors. Java supports four different access permissions.
- Default (default, write nothing) : Visible within the same package, without any modifiers. Use objects: classes, interfaces, variables, methods.
- Private: visible within the same class. Use objects: variables, methods. Note: You cannot decorate classes (external classes)
- Public: visible to all classes. Use objects: classes, interfaces, variables, methods
- Protected: Visible to classes and all subclasses within the same package. Use objects: variables, methods. Note: You cannot decorate classes (external classes).
What is the difference between break,continue and return?
- Break: no longer executes the loop (terminates the current loop body)
- Continue Breaks out of the current loop and continues with the next loop (terminating the current loop and entering the next loop condition)
- Return the program returns, not executing the following code (directly returning from the current method)
The keyword
What is the difference between final, Finally and Finalize?
Final is used to modify variables, methods, and classes.
- Final variable: the modified variable is immutable
Immutable reference
andObject immutable
“Final” meansImmutable reference
, final variables must be initialized and are usually calledconstant
. - Final method: A modified method is not allowed to be overridden by any subclass, which can use the method.
- Final classes: Modified classes cannot be inherited, and all methods cannot be overridden.
As part of exception handling, finally can only be used in try/catch statements, with a statement block indicating that the statement must eventually be executed (whether or not an exception is thrown). It is often used in situations where resources need to be released. System.exit (0) can block finally execution.
Finalize is a method defined in java.lang.Object, which means that every Object has a method that is called when gc starts and the Object is collected.
Finalize method of an object will only be called once, when Finalize method is called, it is not necessary to recycle the object immediately. Therefore, after Finalize method is called, the object will not need to be recycled, and then it is time to be recycled, because it has been called once before. Therefore, Finalize will not be called again, which will cause problems. Therefore, it is not recommended to use Finalize method.
Why the static keyword?
In general, when new is used to create objects of the class, data storage space is allocated and methods are made available for external calls. But sometimes we just want to allocate a single storage space for a particular domain, regardless of how many objects to create or not create any objects at all, or we want to call methods without creating objects at all. In both cases, the static keyword satisfies our requirements.
What does the keyword “static” mean? Can I override a private or static method in Java?
The “static” keyword indicates that a member variable or method can be accessed without the instance variable of the class to which it belongs.
Static methods cannot be overridden in Java because method overrides are dynamically bound at runtime, whereas static methods are statically bound at compile time. Static methods are not associated with any instance of a class, so they are not conceptually applicable.
Can non-static variables be accessed in a static environment?
The static variable is classed in Java and has the same value in all instances. The static variable is initialized when the class is loaded by the Java virtual machine. If your code attempts to access non-static variables without an instance, the compiler will report an error because the variables have not yet been created and are not yet associated with any instance.
Static Can static methods reference non-static resources?
No, something that happens when it’s new, it doesn’t know anything about a static resource that exists after it’s initialized.
Can static methods reference static resources?
Yes, because it’s all loaded when the class is initialized, and everyone knows each other.
Can non-static methods reference static resources?
Yes, a non-static method is an instance method, and that comes after new, so it knows everything that belongs to a class.
What is the order in which Java static variables, code blocks, and static methods are executed?
There are three types of code blocks: Static code blocks, construction code blocks, and common code blocks
Code block execution order Static code block — > Construct code block — > constructor — > plain code block
The code block execution order in inheritance: superclass static block > subclass static block > superclass code block > superclass constructor > subclass code block > subclass constructor
For more information, check out this article: juejin.cn/post/684490…
object-oriented
What’s the difference between object-oriented and procedural?
Process-oriented:
- Advantages: Higher performance than object-oriented, because class invocation needs to be instantiated, the overhead is relatively large, more consumption of resources; For example, SCM, embedded development, Linux/Unix and so on generally adopt process-oriented development, performance is the most important factor.
- Disadvantages: No object-oriented easy maintenance, easy reuse, easy to expand.
Object-oriented:
- Advantages: easy to maintain, easy to reuse, easy to expand, because of the characteristics of object-oriented encapsulation, inheritance, polymorphism, can design a low coupling system, make the system more flexible, more easy to maintain.
- Disadvantages: Lower performance than process-oriented.
Talk about three features of object orientation
- Encapsulation. Encapsulation is best understood. Encapsulation is one of the characteristics of object orientation and is the main feature of object and class concepts. Encapsulation is to encapsulate objective things into abstract classes, and classes can only allow their data and methods to be operated by trusted classes or objects, to hide the information of the untrusted.
- Inheritance. Inheritance is the ability to take all the functionality of an existing class and extend it without having to rewrite the original class. New classes created by inheritance are called “subclasses” or “derived classes,” and inherited classes are called “base classes,” “parent classes,” or “superclasses.”
- Polymorphism. It means that attributes and methods defined in the parent class can have different data types or exhibit different behaviors after being inherited by subclasses, which makes the same attribute or method have different meanings in the parent class and its subclasses.
How is polymorphism implemented in the Java language?
There are essentially two kinds of polymorphism:
Compile-time polymorphism (also known as static polymorphism)
2. Runtime polymorphism (also known as dynamic polymorphism)
An example of compile-time polymorphism is overload, where compile-time polymorphism is determined at compile time and certain methods are called at run time.
** When we talk about polymorphism, we usually refer to runtime polymorphism, which is when a particular method is not called at compile time and is deferred until run time. ** This is why polymorphic methods are sometimes called delayed methods.
There are three necessary conditions for Java to implement polymorphism: inheritance, rewriting, and upward transformation. Only when these three conditions are met can developers use uniform logic to implement code within the same inheritance structure to handle different objects and thus perform different behaviors.
- Inheritance: In polymorphism, there must be a subclass and a parent class that have an inheritance relationship.
- Override: A subclass redefines methods in its parent class that are called when those methods are called.
- Upward transition: In polymorphism, a reference to a subclass is assigned to a superclass object so that the reference can call both the methods of the parent class and the methods of the subclass.
Java implementation principle of polymorphism can see this article: my.oschina.net/u/4432600/b…
What is the difference between Overload and Override?
Methods 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.
- Overrides occur between subclasses and superclasses. The return value and parameter of overridden methods cannot be changed, regardless of method return values and access modifiers. That is, overloaded methods cannot be distinguished by their return types. Namely shell unchanged, core rewrite!
- Overloading is when methods in a class have the same name but different parameters. The return types can be the same or different. Each overloaded method (or constructor) must have a unique list of parameter types. The most common place is constructor overloading.
Can overloaded methods be distinguished by return value types?
Overloaded methods cannot be distinguished by the return value type. Because no type information is specified, the compiler does not know which function you are calling.
float max(int a, int b);
int max(int a, int b);
Copy the code
When Max (1,2) is called; There is no way to determine which one is being called. For this reason alone, overloading with only a different return value type should not be allowed.
Can the constructor be overridden?
Constructors cannot be inherited and therefore cannot be overridden, but can be overridden. Each class must have its own constructor, which is responsible for constructing its own part of the construct. Subclasses do not override the constructor of their parent class; instead, they must first call the constructor of their parent class.
What is the difference between abstract classes and interfaces?
Grammatical differences:
- Abstract classes can provide implementation details for member methods, whereas only public abstract methods can exist in interfaces.
- Member variables in abstract classes can be of various types, while member variables in interfaces can only be of public static final type.
- Interfaces cannot have static code blocks and static methods, whereas abstract classes can have static code blocks and static methods.
- A class can inherit only one abstract class, while a class can implement multiple interfaces.
Differences at the design level:
- An abstract class is an abstraction of a thing, that is, a class abstraction, whereas an interface is an abstraction of behavior. An abstract class abstracts the class as a whole, including properties and behaviors, whereas an interface abstracts parts of the class (behavior).
- The design level is different, abstract class as the parent of many subclasses, it is a kind of template design. Interface is a code of conduct, it is a radiation design.
Want to understand, you can refer to this article: www.cnblogs.com/dolphin0520…
Can abstract classes use final decoration?
No, an abstract class is defined to be inherited by other classes. If it is defined as final, the class cannot be inherited, and thus conflicts with each other. Therefore, final cannot modify an abstract class
How can Java create objects?
There are four ways to create objects in Java:
- New Creates a new object
- By reflex mechanism
- Clone mechanism
- Through serialization mechanism
Both require an explicit call to the constructor. For clone mechanism, it is necessary to pay attention to the difference between shallow copy and deep copy. For serialization mechanism, it is necessary to clarify its implementation principle. In Java, serialization can be implemented by implementing Externalizable or Serializable.
What is an immutable object? What are the benefits?
Immutable objects mean that once an object has been created, its state cannot be changed. Any modification creates a new object, such as String, Integer, and other wrapper classes. The biggest benefit of immutable objects is thread-safety.
Can I create an immutable object that contains a mutable object?
For example, final Person[] persons = new Persion[]{}. Persons is a reference to an immutable object, but the Person instance in the array is mutable. Special care should be taken not to share references to mutable objects in this case. In this case, if the data needs to change, a copy of the original object is returned.
What is the difference between value passing and reference passing? Why is there only value passing in Java?
Value passing: When a method is called, the parameters are passed as a copy of the value, that is, they are not related to each other.
Reference pass: refers to the method call, the parameters are passed by reference, actually passed the address of the reference, that is, the address of the memory space corresponding to the variable. A reference to a value is passed, meaning that both before and after the pass point to the same reference (that is, the same memory space).
When a primitive type is passed as a parameter, it must be passed as a value; When a reference type is passed as an argument, it is also passed by value, except that the “value” is the corresponding reference.
Want to understand, you can refer to this article: www.itwanger.com/java/2019/1…
Object equality judgment
What is the difference between equals and ==?
== is commonly used for comparisons between the same basic data types, as well as between objects of the same type;
- if
= =
Compare basic data types, then compare the values of the two basic data types are equal; - if
= =
Is the comparison of two objects, then the comparison is the reference of two objects, that is, to determine whether two objects point to the same memory area;
The equals method is used primarily between two objects to check whether one is equal to the other
Check the equals method in the Object class.
public boolean equals(Object obj) {
return (this == obj);
}
Copy the code
It is also used to determine whether two objects are equal or not.
- In case 1, the class does not override equals(). Comparing two objects of that class through equals() is equivalent to comparing them through “==”.
- In case 2, the class overrides equals(). In general, we override equals() to make the contents of two objects equal; Return true if their contents are equal (that is, the objects are considered equal).
The Java language specification requires the equals method to have the following properties:
- Reflexivity. For any non-null reference value x, x.equals(x) must be true.
- Symmetry. For any non-null reference values x and y, y.equations (x) is true if and only if x. equations (y) is true.
- Transitivity. For any non-null reference values x, y, and z, x. quals(z) must be true if x. quals(y) is true and y. quals(z) is true.
- Consistency. For any non-null reference values x and y, x.equals(y) returns either true or false consistently on multiple calls to equals if the object information used for the comparison has not been modified.
- For any non-null reference value x, x. beers (null) returns false.
What about hashCode()?
HashCode () is used to get a hashCode, also known as a hashCode; It actually returns an int. The purpose of this hash code is to determine the index position of the object in the hash table. HashCode () is defined in the JDK’s Object.java, which means that any class in Java contains a hashCode() function.
Hash table stores key-value pairs. It can quickly retrieve the corresponding value according to the key. That’s where the hash code comes in! (Can quickly find the desired object)
Why hashCode?
Use “How a HashSet checks for duplicates” as an example to illustrate why hashCode is needed:
When you add an object to a HashSet, the HashSet evaluates the object’s Hashcode value to determine where the object was added. It also compares the object’s Hashcode value to the hashcode value of other objects that have already been added. If there is no matching Hashcode, the HashSet assumes that the object is not repeated.
But if objects with the same Hashcode value are found, the equals() method is called to check whether objects with hashCode equality are really the same. If they are the same, the HashSet will not let the join succeed. If it is different, it will be rehashed to another location. This significantly reduced the number of equals calls, which in turn significantly increased the execution speed.
What is the relationship between hashCode() and equals()?
To understand the relationship between these two methods, you need to have a basic understanding of hash tables. Its basic structure is as follows:
For the HashCode method, a hash value is returned, and the hash value mod the length of the array determines the location of a storage subscript, as shown in the first column enclosed in an array.
Different hashes may have the same result after they are mod Ed, using equals to determine whether they are the same object, or inserting them into the linked list if they are different.
HashCode () equals()
- If two objects are equal, the HashCode must also be the same;
- If two objects are equal, calling equals on both objects returns true;
- Two objects that have the same hashCode value are not necessarily equal;
Why do I have to override hashCode to override equals?
Check hashCode first and equals() in the same case. If you override only equals but not hashCode, the hashCode value will be different, and equals() will determine true.
In some Java containers, two objects are not allowed to be identical and will be overwritten if they are judged to be identical. If you override only equals () but not hashcode, the hashcode of Object is a hash converted from the storage address of the Object. In this case, it is possible to overwrite the same object by not overwriting the hashCode method, causing the same object to be hashed to a different location.
What’s the difference between String,StringBuffer, and StringBuilder?
1. Variable and immutable. The String class uses character arrays to hold strings, and because of the “final” modifier, strings are immutable. Any modification to an existing String creates a new object and stores the new value in it.
The String class uses a final char array to store characters.
private final char value[];
AbstractStringBuilder and StringBuffer both inherit from AbstractStringBuilder classes. AbstractStringBuilder also uses character arrays to store strings. Both objects are mutable.
The source code is as follows:
char[] value;
2. Whether multithreading is safe.
Objects in strings are immutable, which means they can be interpreted as constants, which is obviously thread-safe.
StringBuilder is non-thread-safe.
StringBuffer places synchronization locks on methods or on invoked methods, so it is thread-safe.
The source code is as follows:
@Override
public synchronized StringBuffer append(String str) {
toStringCache = null;
super.append(str);
return this;
}
Copy the code
3. The performance
Each time a String type is changed, a new String is generated and a pointer is pointed to the new String. A StringBuffer operates on the StringBuffer object itself each time, rather than generating new objects and changing object references. Using StirngBuilder in the same situation yields only a 10% to 15% improvement over using StringBuffer, but at the risk of multithreading insecurity.
Why is String designed to be immutable?
1. Easy to implement String pool
In Java, because of the heavy use of String constants, creating a String every time you declare a String would be a huge waste of space resources. Java introduces the concept of String pool, which creates a storage space in the heap. When initializing a String variable, if the String already exists, it does not create a new String variable, but returns a reference to an existing String.
String a = "Hello world!" ; String b = "Hello world!" ;Copy the code
If strings are mutable, and a String variable changes its value, then the value of the variable it points to also changes, String pool will not be possible!
2. Make multithreading safe
In concurrent scenarios, it is safe for multiple threads to read a resource at the same time, which does not cause competition. However, it is not safe for multiple threads to write resources. Immutable objects cannot be written, which ensures the security of multiple threads.
3. Avoid safety issues
Strings are often used as parameters in network connections and database connections, for example, network connection address URL, file path, and String parameters required by reflection mechanisms. Its immutability can guarantee the security of the connection. If the string is mutable, it is possible for a hacker to change the value of the string pointing to an object, which can cause a serious security problem.
4. Speed up string processing
Since strings are immutable, ensuring the uniqueness of hashCode, the hashcode of the object can be safely cached without recalculation when it is created. This is why Maps like strings as keys, which are faster than other Key objects. So keys in a HashMap tend to use strings.
In general, the reasons why strings are immutable include design considerations, efficiency optimization, and security.
reference
Tech.meituan.com/2019/09/05/…
C.biancheng.net/view/769.ht…
www.51gjie.com/java/81.htm…
www.justdojava.com/2019/03/21/…
Blog.csdn.net/qq_28051453…
www.cnblogs.com/wkfvawl/p/1…