Fundamentals of java interview

1.JDK,JRE,JVM

JDK: short for Java Development Kit, Java Development Kit, provides the development environment and running environment of Java.

JRE: short for Java Runtime Environment, Java Runtime Environment, which provides the required environment for the operation of Java. Including Java virtual machine and core class library required by Java program.

JVM: Java virtual machine. Java programs run on the virtual machine. Different platforms have their own processors, so Java can cross platforms.

You need to run java programs, just install JRE. To write java programs, you need to install JDK.

2.JAVA data type

Basic typedigitbyte
int324
short162
long648
byte81
char162
float324
double648
booleanfalsetrue

Reference data type: class, interface, array

3.String and new String

String str ="lymn";
String newStr =new String ("lymn");

String str ="lymn"

First, find out whether there is a lymn object in the constant pool. If so, let str point to that lymn. If not, create a new lymn object in the constant pool and let str point to the newly created object lymn in the constant pool.

String newStr =new String ("lymn")

new String("lymn") first looks in the constant pool, if not, creates "lymn", and then creates an object in heap memory through new to copy and assign "lymn".

4.equals, hashCode and==

==

  • If it is a basic type, = = means to judge whether their values are equal;
  • If it is a reference object, = = means to judge whether the memory addresses pointed to by the two objects are the same.

equals

The equals method is an instance method in the base class Object. In the Object class, the equals method is used to compare whether the references of two objects are equal, that is, whether they point to the same Object.

public boolean equals(Object obj) {
    return (this == obj);
  }
  • If the equals method is not overridden, compare the address of the object pointed to by the reference type variable;

  • If classes such as String and Date rewrite the equals method, compare the contents of the object pointed to.

equals rewrite principle

  • Symmetry: if x.equals(y) returns true, y.equals(x) should also return true;

  • Reflexivity: x.equals(x) must return true;

  • Analogy: if x.equals(y) returns true and y.equals(z) returns true, then z.equals(x) should also return true;

  • Consistency: if x.equals(y) returns true, as long as the contents of X and Y remain unchanged, no matter how many times you repeat x.equals(y), the return is true;

hashCode

The instance native method in Object will return different integers for different objects.

public native int hashCode();

5.hashCode() and equals()

  • If two objects have equal equals, their hashcode must be equal;
  • If the equals of two objects are not equal, their hashcode s may be equal or unequal;
  • hashCode() is not equal, and equals must not be equal;
  • Objects that override the euqls method must also override the hashCode() method.

hashcode is used by the system to quickly retrieve objects, and equals method is used to judge whether the referenced objects are consistent.

String override

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }
//h=val[0]*31^(n-1) + val[1]*31^(n-2) + ... + val[n-1]  

First call the hashCode method of this element, and then calculate the position of the element in the array according to the obtained value. If there is no element in this location, store it directly in this location;

If there is already an element in this position, call its equals method to compare with the new element: if it is the same, it will not be saved. Otherwise, it will be stored in the linked list corresponding to this position.

 	   int i2 = 128;
	   int i3 = 128;
	   Integer i4 = new Integer(128);
	   Integer i5 = 128;
	   System.out.println(i2==i3);//true
	   //i4 and i5 will automatically box 128 into Integer type during assignment, and then when = = comparison is used, i4 and i5 will automatically unpack into int, so in essence, two ints are compared
	   System.out.println(i2==i4);//true
	   System.out.println(i2==i5);//true
	   System.out.println(i4==i5);//false
	   
	   /*Integer i = 2 
	    Pass 2 through Integer The valuesof method generates an Integer object and assigns the address to a number whose i is between - 128 and 127. Then the returned Integer is an array of Integer cache [], otherwise it is new Integer(i)*/
	   Integer i=2;
	   Integer j=2;
	   Integer m=new Integer(2);
	   Integer i1=156;
	   Integer j1=156;
	   Integer m1=new Integer(156);
	   Long g=new Long(2);
	   System.out.println(i==j);//true 
	   System.out.println(i1==j1);//false
	   System.out.println(i==m);//false
	   System.out.println(i.equals(m));//true
	   System.out.println(i==2);//true
	   //The instance method Integer intValue() of m was called 
	   //int i=2;i==m 
	   System.out.println(m==2);//true
	   System.out.println(m1==156);//true
	   System.out.println(g==2L);//true
	   System.out.println(g==2);//true
	   System.out.println(i.equals(g));//false
	   //g.equals(Integer.valueOf(2))
	   System.out.println(g.equals(2));//false
	   System.out.println(g.equals(2L));//true
  • For some = = comparisons of Integer class, we should pay attention to the existence of automatic boxing mechanism. If the range (- 128 ~ 127) is assigned by = =, it returns the reference in the IntegerCache [] array. Beyond this range, a new Integer object is returned
  • new Integer and value (for example, when comparing 2). By analyzing the bytecode, we know that the new Integer object calls the intValue() method when comparing. In fact, the comparison is whether the values are equal
  • Each object overrides the equals () method, which is used to compare whether the contents of two objects of the same type are equal. And integer Equals (long) must be unequal
  • In the wrapper class corresponding to the basic type, the cache pools of Byte, Short, Integer, Long and Character are [- 128, 127]. The cache pool of Boolean is special, with only two Boolean objects: true and false.
  • The packing method corresponding to int is Integer#valueOf , the unpacking method is Integer#intValue().
  	   String s1 = "Java";
       String s2 = "Java";
       String s3 =new String( "Java");
       String s4 = new String("Java");
       System.out.println(s1 == s2);//true
       System.out.println(s3 == s4);//false
       System.out.println(s1 == s3);//false
	   String s5="hello";
	   String s6="world";
	   String s7="helloworld";
	   String s8=s5+"world";
	   String s9=s5+s6;
	   //final modified s1 can recognize s11="hello"+"world" at compile time
	   final String s10 = "hello";
	   String s11=s10+"world";
	   System.out.println("hello"+"world"==s7);//true
	   System.out.println(s7==s8);//false
	   System.out.println(s7==s9);//false
	   System.out.println(s8==s9);//false
	   System.out.println(s7==s11);//true     
	   //In jdk1 In 6, you will get two false constant pools to allocate memory in the permanent generation, which is physically isolated from the memory of the Java heap. The intern method virtual opportunity copies the string in the constant pool and returns a reference; If the string already exists, the reference of the constant object in the constant pool will be returned directly.
	   //In JDK7 and 8, you will get a true and a false intern method. If the corresponding string cannot be found in the constant pool, the string will not be copied to the constant pool, but only a reference to the original string will be generated in the constant pool. To put it simply, what is put in the constant pool has changed: when it cannot be found in the constant pool, copy a copy to the constant pool. After 1.7, copy the address reference on the heap to the constant pool. Of course, at this time, the constant pool is moved from the method area to the heap.
	   String str1 = new StringBuilder("computer").append("Software").toString();
	    System.out.println(str1.intern() == str1);//true
	    //Due to the particularity of the JVM, some methods are called when the JVM is started, and the "java" string constant has been generated in the constant pool.
	    String str2 = new StringBuilder("ja").append("va").toString();
	    System.out.println(str2.intern() == str2);//false

	    //When str3, there is only one heap String object. At this time, there is no constant object "str01" in the constant pool. At this time, str4 creates "str01" and str3 in the constant pool Reference to str4 returned by intern()
	    String str3 = new String("str")+new String("01");
	    String str4 = "str01";
	    System.out.println(str3==str4);//false
	    System.out.println(str3.intern()==str3);//false
	    System.out.println(str3.intern()==str4);//true
	    System.out.println(str3==str4);//false
        //At str5, there is only a heap of String objects and then called intern. There is no "str02" constant object in the constant pool, so a reference to the string object in the heap is generated in the constant pool. When assigning a value to str6, because it is in quotation marks, go to the constant pool and find the constant object. If you find the constant object, you will return the reference of the constant object, that is, the address of the string object in the heap pointed to by str5 reference.
	    String str5 = new String("str")+new String("02");
	    str5.intern();
	    String str6 = "str02";
	    System.out.println(str5==str6);//true
  • String d = "big flower1" + "big flower1" is equivalent to String d =big flower1big flower1 at bytecode level, that is, two or more string constants are added, and "+" will be optimized during precompiling, which is equivalent to automatically synthesizing two or more string constants into a string constant
  • In order to optimize the string addition of non pure constants, the JVM automatically introduces the StringBuilder class in the overload of the "+" operator
  • If there is a new string ("big flower"), then using = = to compare must return false, which will always be different objects. You can only compare the contents of two objects through equals
  • When using = = to compare two strings, you should pay attention to the existence of constant pool
  • javap -v XXX checks the compiled code and finds that new String will create this string in the string constant pool for the first time, that is, one or two objects may be created by creating a string through new

6. Differences between string, Stringbuffer and StringBuilder

String

  • String is the final class and cannot be inherited. (as one of the most commonly used classes, string class cannot be inherited and rewritten, which can improve efficiency; many of the string classes call the underlying local methods and call the API of the operating system. If the methods can be rewritten, they may be implanted with malicious code and destroy the program.)
  • Once a String class is created, the value cannot be modified (the operation on a String object in Java is actually a process of constantly creating new objects and recycling old objects)
  • String overrides the equals() method and hashCode() method

StringBuffer

  • Inherits AbstractStringBuilder, which is a variable class
  • StringBuffer is thread safe and inefficient
  • Data can be constructed dynamically through the append method

StringBuilder

  • It inherits from AbstractStringBuilder and is a variable class
  • StringBuilder is non thread safe and efficient

When modifying strings, especially when string objects are often changed, you need to use StringBuffer and StringBuilder classes.

In the following String object generation, String efficiency is much faster than StringBuffer.

//String S1 = "This is only a simple test"; 
String S1 = "This is only a" + " simple" + " test";
StringBuffer Sb = new StringBuffer("This is only a").append(" simple").append(" test");

7. Create a Java Lang. string class. Can this class be loaded by class loader?

may not. Because JDK is in consideration of security, based on the parental delegation model, the String class of JDK is preferentially loaded if Java Lang.String has been loaded, it will not be loaded again.

Common methods of String class

  • indexOf(): returns the index of the specified character
  • charAt(): returns the character at the specified index
  • replace(): string replacement
  • trim(): remove whitespace at both ends of the string
  • split(): splits a string and returns an array of split strings
  • getBytes(): returns an array of byte types of strings
  • length(): returns the length of the string
  • toLowerCase(): converts a string to lowercase
  • toUpperCase(): converts a string to uppercase characters
  • substring(): intercept string
  • equals(): string comparison

Invert string

  • Using the reverse method of StringBuilder or StringBuffer essentially calls the reverse method implementation of their parent class AbstractStringBuilder. (JDK1.8)
  • Use the chatAt function and output it backwards

8.Java object creation method

  • Create object objectname with new statement obj = new objectname(); New creates an object instance (the object instance is in heap memory), and the object reference points to the object instance (the object reference exists in stack memory)
  • Use the newinstance() method of the reflected Class objectname obj = objectname Class. newInstance();
  • Use the newinstance() method of the reflected Constructor class objectname obj = objectname class. getConstructor. newInstance();
  • Call the clone() method of the object objectname obj = obj clone();
  • Using deserialization means, call Java io. readObject() method of objectinputstream object
  • Use unsafe sun misc. Unsafe this class mainly provides some direct access to system memory resources
package com.lymn
import java.io.Serializable;
import java.util.Objects;

public class Employee implements Serializable, Cloneable {
	private static final long serializableUID = 1L;
	private String name;
	public Employee() {
		System.out.println("Employee Constructor Called...");
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o)
			return true;
		if (o == null || getClass() != o.getClass())
			return false;
		Employee employee = (Employee) o;
		return Objects.equals(name, employee.name);
	}
	@Override
	public int hashCode() {
		return Objects.hash(name);
	}
	@Override
	public String toString() {
		return "Employee{" + "name='" + name + '\'' + '}';
	}
	@Override
    public Employee clone() {
        Employee clone = null;
        try {
            clone = (Employee) super.clone();
        } catch (CloneNotSupportedException e) {
 
        }
        return clone;
    }
}

package com.lymn;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import sun.misc.Unsafe;

public class ObjectCreate {
	private static final String FILE_NAME = "employee.obj";
	 
    public static void main(String[] args) throws Exception {
        // Create an object using the new keyword
        Employee employee = new Employee();
        employee.setName("Zhang San");
        System.out.println("new Object method:" + employee);
        // Use the newInstance() method of Class
        // Employee employee2 = (Employee) Class.forName("Employee").newInstance();
        Employee employee2 = Employee.class.newInstance();
        employee2.setName("xxx2");
        System.out.println("Class Class newInstance()method:" + employee2);
 
        // Use the newInstance() method of the Constructor class
        Employee employee3 = Employee.class.getConstructor().newInstance();
        employee3.setName("xxx3");
        System.out.println("Constructor Class newInstance()method:" + employee3);
 
        // Use clone() method: the class must implement the clonable interface and override its clone() method
        Employee employee4 = (Employee) employee.clone();
        // employee4.setName("xxx4");
        System.out.println("object clone()method:" + employee4);
 
        // Use the readObject() method of deserializing ObjectInputStream: the class must implement the Serializable interface
        // serialize
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME))) {
            oos.writeObject(employee);
        }
        // Deserialization
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_NAME))) {
            Employee employee5 = (Employee) ois.readObject();
            System.out.println("Deserialization:" + employee5);
        }
        //unSafe method
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);
        Employee employee6 = (Employee) unsafe.allocateInstance(Employee.class);
        employee6.setName("xxx4");
        System.out.println("unSafe method:" + employee6);

    }
========================================================
     /*  Employee Constructor Called...
        new Object method: Employee{name = 'Zhang San'}
        Employee Constructor Called...
        Class Class: Employee{name='xxx2 '}
        Employee Constructor Called...
        Constructor Class: Employee{name='xxx3 '}
        Name = 'clone() method' {employee}
        Deserialization: Employee{name = 'Zhang San'}
        unSafe Method: Employee{name='xxx4 '}*/
}

9. Access modifiers public,private,protected, and default

private: visible in the same class. Use objects: variables and methods. Note that classes cannot be modified

default: visible within the same package without any modifiers. Using objects: classes, interfaces, variables, methods

protected: visible to all subclasses in the same package. Use objects: variables and methods. Note that classes (external classes) cannot be modified

public: visible to all classes, using objects: classes, interfaces, variables, and methods

10. The difference between overloading and rewriting

  • Method overloading and rewriting are the ways to realize polymorphism. The difference is that the former realizes the polymorphism at compile time and the latter is the polymorphism at run time
  • Overload: occurs in the same class. The method name is the same but the parameter list is different (number, type and order). It has nothing to do with the method return value and modifier, that is, the overloaded methods cannot be distinguished according to the return type
  • Rewriting: occurs in parent-child classes. The method name and parameter list are the same. The return value is less than or equal to the parent class. The exception thrown is less than or equal to the parent class. The access modifier is greater than or equal to the parent class (Richter substitution principle); If the method access modifier of the parent class is private, it is not overridden in the subclass.

11. Abstract classes and interfaces

Abstract class is the abstraction of class, which is a kind of template design. Interface is the abstraction of behavior and the specification of behavior.

Defining an abstract class allows other classes to inherit. If it is defined as final, the class cannot be inherited, which will conflict with each other. Therefore, final cannot modify an abstract class.

  • Neither interfaces nor abstract classes can be instantiated

  • Both contain abstract methods, and their subclasses must override these abstract methods

  • Abstract classes should be inherited by subclasses, and interfaces should be implemented by subclasses

  • Abstract is the keyword of abstract class and interface is the keyword of interface

  • A class can implement multiple interfaces, but can only inherit one parent class

  • Abstract classes can have constructors, but interfaces cannot have constructors

  • Abstract classes can have ordinary member variables, and variables in interfaces can only be public static constants

  • Interfaces can only make method declarations. Abstract classes can make method declarations or method implementations

  • Abstract classes can have main methods and can run. Interfaces cannot have main methods

12. General and abstract classes

  • Ordinary classes cannot contain abstract methods, and abstract classes can contain abstract methods.
  • Abstract classes cannot be instantiated directly. Ordinary classes can be instantiated directly.

13. Difference between final, finally and finalize

  • final is used to modify attributes, methods and classes, respectively indicating that attributes cannot be re assigned, methods cannot be overwritten, and classes cannot be inherited
  • Finally is a part of the exception handling statement structure. It generally appears as try catch finally. Finally, the code block indicates that it is always executed. It is generally used to store some code to close resources
  • Finalize is a method of the Object class, which is generally called by the garbage collector to call system When using the GC () method, the garbage collector calls the finalize() method to collect garbage

14. Does Java support multiple inheritance?

  • In consideration of security, if the subclass inherits multiple parent classes with the same method or property, the subclass will not know which one to inherit
  • Java provides interfaces and internal classes to realize multi inheritance and make up for the defect of single inheritance

15. Can switch work on byte, long and String

  • Before Java 5, it could only be byte, short, int and char
  • Start with Java 5 and add enum types
  • Start with Java 7 and add String
  • switch can act on the wrapper class corresponding to char byte short int
  • switch cannot act on long double float boolean and their wrapper classes

16. Common knowledge

  • Math.round(11.5) = 12
  • Math.round(-11.5) = -11
  • float f =(float)3.4; Or written as float f =3.4F
  • Shift left 2 < < 3 = = 2 times 8
  • short s1 = 1; s1 = (short) (s1 + 1); Or short s1 = 1; s1 += 1;
  • Logic and &, logic or | and short circuit &, short circuit | (& & the left expression value is false)
public static void main(String[] args) {
        int i = 1;
        i = i++;
        int j = i++;
        int k = i + ++i * i++;
        System.out.println("i=" + i);
        System.out.println("j=" + j);
        System.out.println("k=" + k);
    }
--------
i=4
j=1
k=11

17. What methods are defined in object?

  • getClass(); Get class structure information
  • hashCode() get hash code
  • equals(Object) defaults to whether the address values of the comparison object are equal. Subclasses can override the comparison rules
  • clone() for object cloning
  • toString() converts an object into a string
  • Wake up function in notify() multithreading
  • notifyAll() the function of waking up all waiting threads in multithreading
  • wait() lets the thread holding the object lock enter the wait
  • wait(long timeout) lets the thread holding the object lock enter the wait, and sets the timeout milliseconds
  • wait(long timeout, int nanos) lets the thread holding the object lock enter the wait, and sets the timeout nanoseconds

18. Can we cast int to byte variable? What happens if the value is larger than the range of byte type?

Yes, we can do forced conversion, but in Java, int is 32 bits and byte is 8 bits. If forced conversion, the top 24 bits of int type will be discarded.

public class Test {
    public static void main(String[] args)  {
        int a =129;
        byte b = (byte) a;
        System.out.println(b);
        int c =10;
        byte d = (byte) c;
        System.out.println(d);
    }
}
Output:
-127
10

19.this and super keywords

  • When this class is called to construct, it must be placed in the first line of the construction method; When super calls the parent class construction, it must be placed in the first line of the subclass construction method
  • This accesses the properties and methods in this class, and super accesses the properties and methods in the parent class
  • this() and super() cannot exist in the same constructor. Both this() and super() must be written in the first line of the constructor
  • This and super cannot be used for static modified variables, methods or code blocks. Because this and super refer to objects (instances)

20.static

  • The variable or method modified by static is independent of any object of the class and is shared by the instance object of the class
  • When the class is loaded for the first time, the static decorated part will be loaded, and initialization will only be performed when the class is loaded for the first time
  • Variables or methods modified by static are better than objects. They can be accessed even if there is no object
  • Static can only access static
  • Non static means you can access non static or static

21. Access non static variables in static environment?

Static variable belongs to class in Java, and its value is the same in all instances. When the class is loaded by the Java virtual machine, the static variable will be initialized. Because static members belong to a class, they are loaded into the memory of the static method area with the loading of the class. When the class is loaded, there may not be instances created at this time. Without instances, non static members can not be accessed. Class loading precedes instance creation, so you cannot access non static objects in a static environment!

22. Can I make a call to a non static method from within a static method?

may not.

  • Non static methods are closely related to object instances. You must create an object before you can call non static methods on the object. Static methods are related to classes and do not need to create objects. They can be called directly by classes.
  • When a static method is called, no instance object may have been created. If a static method calls a non static method, which object is the non static method associated with? This logic is untenable
  • Therefore, a static method cannot make calls to non static methods.

23. Instantiation order of classes

Class instantiation order: parent static code block / static field - > child static code block / static field - > parent non static code block - > parent constructor - > child non static code block - > child constructor

public class Parent {
    {
        System.out.println("Non static code block of parent class");
    }
    static {
        System.out.println("Parent static block");
    }
    public Parent() {
        System.out.println("Parent constructor");
    }
}
public class Son extends Parent {
    public Son() {
        System.out.println("Subclass constructor");
    }
    static {
        System.out.println("Subclass static code block");
    }
    {
        System.out.println("Subclass non static code block");
    }
}
public class Test {
    public static void main(String[] args) {
        Son son = new Son();
    }
}
public class Father {
    private int i = test();
    private static int j = method();

    static{
        System.out.println("(1)");
    }
    Father() {
        System.out.println("(2)");
    }
    {
        System.out.println("(3)");
    }
    public int test(){
        System.out.println("(4)");
        return 1;
    }
    public static int method() {
        System.out.println("(5)");
        return 1;
    }
}
public class Son extends Father {
    private int i = test();
    private static int j = method();
    static {
        System.out.println("(6)");
    }
    Son() {
        super();
        System.out.println("(7)");
    }
    {
        System.out.println("(8)");
    }
    public int test(){
        System.out.println("(9)");
        return 1;
    }
    public static int method() {
        System.out.println("(10)");
        return 1;
    }

    public static void main(String[] args) {
        Son son = new Son();
        System.out.println();
        Son son1 = new Son();
    }
}
--------
(5)
(1)
(10)
(6)
(9)
(3)
(2)
(9)
(8)
(7)

(9)
(3)
(2)
(9)
(8)
(7)

24. Can constructors be rewritten?

Constructors cannot be inherited, because the class name of each class is different, and the constructor name is the same as the class name, so there is no inheritance. Since the constructor cannot be inherited, the corresponding cannot be rewritten. Constructor has no return value, but cannot declare constructor with void.

25. The function of defining a constructor that does nothing and has no parameters in Java

If the superclass () has no parameters, it will call the method in the superclass () to execute the method before the superclass () is constructed. Therefore, if only the constructor with parameters is defined in the parent class, and the constructor of the subclass does not use super() to call the specific constructor in the parent class, an error will occur during compilation, because the Java program cannot find a constructor without parameters in the parent class for execution. The solution is to add a constructor that does nothing and has no parameters to the parent class.

26. How to jump out of the current multiple nested loop

In Java, if you want to jump out of multiple loops, you can define a label in front of the outer loop statement, and then use the labeled break statement in the code of the inner loop body to jump out of the outer loop.

public static void main(String[] args) {
    ok:
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            System.out.println("i=" + i + ",j=" + j);
            if (j == 5) {
                break ok;
            }
        }
    }
}

27. How to realize object cloning?

  • Combined with serialization (JDK java.io.Serializable interface, JSON format, XML format, etc.), complete deep copy
  • Implement the clonable interface and rewrite the clone() method.
  • The clone() method of Object is a shallow copy, that is, if the attribute in the class has a custom reference type, only the reference is copied, and the Object pointed to by the reference is not copied.
  • The Class of the object attribute also implements the clonable interface. When cloning the object, the attribute is also cloned manually to complete the deep copy
package com.lymn;

public class Text implements Cloneable{
	private int age;
	private Name name;
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Name getName() {
		return name;
	}
	public void setName(Name name) {
		this.name = name;
	}
	@Override
	protected Object clone(){
		try {
			return super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return null;
	}
	public static void main(String[] args){
		 Name name1=new Name();
		 name1.setName("name1");
		 Text t1=new Text();
		 t1.setAge(12);
		 t1.setName(name1);
		 Text t2=(Text) t1.clone();
		 System.out.println(t2.getName().getName());
		 name1.setName("name2");
		 System.out.println(t2.getName().getName());
		}
}
class Name{
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
-------------
name1
name2
 Because it just calls the parent class directly clone Method, which does not process the member properties, so it is being modified t1 attribute name When the value of, t2 attribute name The value of will also change.
package com.linln.boot;

public class Text implements Cloneable{
	private int age;
	private Name name;
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Name getName() {
		return name;
	}
	public void setName(Name name) {
		this.name = name;
	}
	@Override
	protected Object clone(){
		Text text=null;
		try {
			text=(Text) super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		text.setName((Name) text.getName().clone());
		return text;
	}
	public static void main(String[] args){
		 Name name1=new Name();
		 name1.setName("name1");
		 Text t1=new Text();
		 t1.setAge(12);
		 t1.setName(name1);
		 Text t2=(Text) t1.clone();
		 System.out.println(t2.getName().getName());
		 name1.setName("name2");
		 System.out.println(t2.getName().getName());
		}
}
class Name implements Cloneable{
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	protected Object clone(){
		try {
			return super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return null;
	}
}
----------
name1
name1

28. Method parameter transfer mechanism

package com.linln.boot;

import java.util.Arrays;

public class Exam {
	public static void main(String[] args) {
		int i = 1;
		String str = "hello";
		Integer num = 200;
		int[] arr = { 1, 2, 3, 4, 5 };
		MyData my = new MyData();

		change(i, str, num, arr, my);

		// arr my changed
		System.out.println("i= " + i);//1
		System.out.println("str= " + str);//hello
		System.out.println("num= " + num);//200
		System.out.println("arr= " + Arrays.toString(arr));//[2, 2, 3, 4, 5]
		System.out.println("my.a= " + my.a);//11
	}

	public static void change(int j, String s, Integer n, int[] a, MyData m) {
		j += 1;
		s += "world";
		n += 1;
		a[0] += 1;
		m.a += 1;
	}
}

class MyData {
	int a = 10;
}
--------
i= 1
str= hello
num= 200
arr= [2, 2, 3, 4, 5]
my.a= 11

29. Internal class

30. Date category

Keywords: Java

Added by smoked1 on Thu, 17 Feb 2022 12:52:36 +0200