What’s the difference between a String and a StringBuffer or a StringBuilder? Why is String immutable?
StringBuffer and StringBuilder
The mutable String class uses character arrays :private final char Value [] holds strings, so strings are immutable. AbstractStringBuilder and StringBuffer both inherit from AbstractStringBuilder classes. AbstractStringBuilder also uses character arrays to store strings, char[] values, both of which are mutable.
Thread safety
Objects in strings are immutable, which means they are considered constants, thread-safe. AbstractStringBuilder AbstractStringBuilder is a common parent of StringBuilder and StringBuffer. AbstractStringBuilder defines some basic string operations, such as expandCapacity, Append, insert, indexOf and other public methods. StringBuffer places synchronization locks on methods or on invoked methods, so it is thread-safe. StringBuilder does not lock methods synchronously-so it is not thread-safe.
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.
Summary of the use of the three:
- If you want to manipulate a small amount of data, use = String
- Single thread manipulation of large amounts of data in string buffer = StringBuilder
- Multithreaded manipulation of large amounts of data in string buffers = StringBuffer
Why is String immutable?
The String class uses a final char array to store characters.
/** The value is used for character storage. */
private final char value[];
Copy the code
Is String really immutable?
I think if someone asks this question, the answer should be fixed. Here are just two typical examples:
1) String is immutable but does not mean references cannot be
String str = "Hello";
str = str + " World";
System.out.println("str=" + str);
Copy the code
Results:
str=Hello World
Copy the code
Resolution:
In fact, the contents of the original String remain the same, except that the STR has changed from the memory address pointing to “Hello” to the memory address pointing to “Hello World”, which means that an extra memory area is allocated to the “Hello World” String.
2) It is possible to modify so-called “immutable” objects through reflection
// Create the string "Hello World" and assign the reference s
String s = "Hello World";
System.out.println("s = " + s); // Hello World
// Get the value field of the String class
Field valueFieldOfString = String.class.getDeclaredField("value");
// Change the access permission of the value attribute
valueFieldOfString.setAccessible(true);
// Get the value property of the s object
char[] value = (char[]) valueFieldOfString.get(s);
// Change the 5th character in the array referenced by value
value[5] = '_';
System.out.println("s = " + s); // Hello_World
Copy the code
Results:
s = Hello World
s = Hello_World
Copy the code
Resolution:
Reflection allows you to access private members and then reflect the value attribute in the String, changing the structure of the array by obtaining the value reference. But normally we don’t do that, just to mention that there is this thing.
What is the reflex mechanism? What are the application scenarios of reflection mechanism?
Introduction to reflection Mechanism
The JAVA reflection mechanism allows you to know all the properties and methods of any class in the running state. For any object, you can call any of its methods and properties; This ability to dynamically retrieve information and invoke methods on objects is called the Reflection mechanism of the Java language.
Static and dynamic compilation
- ** Static compilation: ** Determines the type and binds the object at compile time
- ** Dynamic compilation: ** Runtime determines the type and binds the object
Pros and cons of reflection
- Advantages: Runtime type judgment, dynamic loading classes, improve code flexibility.
- Disadvantages: Performance bottleneck: Reflection is equivalent to a series of interpreted operations telling the JVM what to do, and performance is much slower than direct Java code.
Reflection application scenarios
Reflection is the soul of frame design.
In our daily project development process, reflection mechanism is rarely used directly, but this does not mean that reflection mechanism is useless, in fact, there are a lot of design and development related to reflection mechanism, such as modular development, through reflection to call the corresponding bytecode; Reflection is also used in dynamic proxy design patterns, as well as in frameworks like Spring/Hibernate that we use every day.
For example: ① We use class.forname () to load the driver of the database by reflection when connecting to the database using JDBC; ② The Spring framework also uses many reflection mechanisms, the most classic of which is the CONFIGURATION schema of XML. Spring loads beans through XML configuration schema: 1) Loads all XML or Properties configuration files in the program into memory; 2) The Java class parses the content in XML or Properties to get the bytecode string and related attribute information of the corresponding entity class; 3) Use reflection to get an instance of a Class based on this string; 4) Dynamically configure instance properties
Recommended reading:
- Reflection: Application scenarios of the Java Reflection mechanism
- Java Basics – Reflection (very important)
What is the JDK? What is JRE? What is the JVM? The connection and difference between the three
These are very basic very basic things in Java, but I believe there must be a lot of people do not understand! Why is that? Because most of the time we don’t think about these things when we use off-the-shelf compilation tools and environments.
JDK: As its name implies, it is a development toolkit for developers, for application developers to use. It includes the complete JRE (Java Runtime Environment), the Java Runtime Environment, and other toolkits for developers.
JRE: Common users only need to install the Java Runtime Environment (JRE) to run Java programs. Developers must install the JDK to compile and debug applications.
JVM: When we run a program, the JVM is responsible for converting bytecode to specific machine code, providing memory management/garbage collection, security mechanisms, etc. This independence from hardware and operating system is why Java programs can be written and executed multiple times at once.
Differences and connections:
- JDK for development, JRE for running Java programs;
- JVMS are included in both the JDK and JRE;
- The JVM is at the heart of the Java programming language and is platform independent.
What is bytecode? What are the biggest benefits of bytecode adoption?
Take a look at compilers and interpreters in Java:
Java introduced the concept of a virtual machine, a virtual machine with a layer of abstraction between the machine and the compiler. This virtual machine provides a common interface for compilers on any platform. The compiler simply faces the virtual machine, generates code that the virtual machine understands, and then the interpreter translates the virtual machine code into system-specific machine code for execution. In Java, this code for the virtual machine to understand is called bytecodes (files with a.class extension), which are not oriented to any particular processor, just to the virtual machine. The interpreter for each platform is different, but the virtual machine implemented is the same. Java source programs are compiled by the compiler into bytecodes, which are interpreted and executed by the virtual machine. The virtual machine sends each byte code to be executed to the interpreter, which translates it into machine code on a particular machine and runs it on that particular machine. This explains the coexistence of compilation and interpretation in Java.
Java source code — — — — — — — — > > compiler JVM executable Java bytecode (that is, the virtual instruction) — — — — — — — — > > JVM JVM interpreter — — — — — > machine executable binary machine code — — — — > program is running.
Advantages of using 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.
The difference between Java and C++
I know many people have never learned C++, but the interviewer likes to compare Java with C++. No way!! Even if you haven’t learned C++, write it down!
- Both are object-oriented languages that support encapsulation, inheritance, and polymorphism
- Java does not provide Pointers to access memory directly; program memory is more secure
- Java classes are single inheritance, C++ supports multiple inheritance; Although Java classes cannot be multiinherited, interfaces can.
- Java has automatic memory management mechanisms that do not require programmers to manually free unwanted memory
What is the difference between interfaces and abstract classes?
- The default method of the interface is public. All methods cannot be implemented in the interface. Abstract classes can have non-abstract methods
- Instance variables in interfaces are final by default, but not necessarily in abstract classes
- A class can implement multiple interfaces, but only one abstract class at most
- A class that implements an interface must implement all the methods of the interface, not necessarily an abstract class
- Interfaces can not be instantiated with new, but can be declared, but must reference an object to implement the interface from the design level, abstraction is the abstraction of class, is a template design, interface is the abstraction of behavior, is a behavior specification.
What are the differences between a member variable and a local variable?
- Syntactically, a member variable belongs to a class, while a local variable is a variable defined in a method or a method parameter. Member variables can be modified by modifiers such as public,private, and static, while local variables cannot be modified by access-control modifiers or static. However, both member variables and local variables can be modified by final;
- In terms of how variables are stored in memory, member variables are part of objects, while objects exist in heap memory and local variables exist in stack memory
- In terms of the lifetime of variables in memory, a member variable is a part of an object, which exists with the creation of the object, while local variables disappear automatically with the call of methods.
- If a member variable is not initialized, it is automatically assigned to the default value of the type (an exception is that member variables that are final but not static must be explicitly assigned); Local variables are not automatically assigned.
The difference between overloading and overwriting
Overloading: Occurs in the same class, the method name must be the same, the parameter type must be different, the number of arguments must be different, and the method return value and access modifier can be different. This occurs at compile time.
Overwrite: occurs in the parent class, the method name, parameter list must be the same, the return value range is less than or equal to the parent class, the exception range is less than or equal to the parent class, access modifier range is greater than or equal to the parent class; If the superclass method access modifier is private, the subclass cannot override the method.
Character constants and string constants
- Form: A character constant is a single character caused by a single quotation mark. A string constant is several characters caused by a double quotation mark
- A string constant represents an address value (where the string is stored in memory).
- Memory size Character constant takes up only one byte String constant takes up several bytes (at least one end of character flag)
Write in the last
Open Source Document Recommendation
Java Interview Customs Manual (Java Study Guide) Star: 1.9 k.
Github address: github.com/Snailclimb/…
This is an open source document for Java backend engineers, both new to Java and already a Java engineer.
Reference:
Segmentfault.com/a/119000001…
Blog.csdn.net/sinat_38259…
If you are in full bloom, breeze. Welcome to follow my wechat official account: “Java Interview Clearance Manual”, a wechat official account with temperature. Public account has a lot of information, reply keyword “1” you may see what you want oh!