Common interview questions

Why is there only value passing in Java?

First, let's review some technical terms in programming language about passing parameters to methods (or functions). Call by value means that the method receives the value provided by the caller, while call by reference means that the method receives the variable address provided by the caller. A method can modify the variable value corresponding to the passed reference, but cannot modify the variable value corresponding to the passed value call. It is used to describe various programming languages Method parameter passing in (not just Java).

Java programming language always calls by value. That is, a method gets a copy of all parameter values, that is, a method cannot modify the contents of any parameter variables passed to it.

Here are three examples to illustrate

example 1

public static void main(String[] args) {
    int num1 = 10;
    int num2 = 20;

    swap(num1, num2);

    System.out.println("num1 = " + num1);
    System.out.println("num2 = " + num2);
}

public static void swap(int a, int b) {
    int temp = a;
    a = b;
    b = temp;

    System.out.println("a = " + a);
    System.out.println("b = " + b);
}

result:

a = 20
b = 10
num1 = 10
num2 = 20

Resolution:

In the swap method, the values of a and b are exchanged without affecting num1 and num2. Because the values in a and b are only copied from num1 and num2. That is, a and b are equivalent to copies of num1 and num2. No matter how the contents of the copies are modified, they will not affect the original itself.

Through the above example, we have learned that a method cannot modify parameters of a basic data type, but object references are different as parameters. See example 2

example 2

	public static void main(String[] args) {
		int[] arr = { 1, 2, 3, 4, 5 };
		System.out.println(arr[0]);
		change(arr);
		System.out.println(arr[0]);
	}

	public static void change(int[] array) {
		// Change the first element of the array to 0
		array[0] = 0;
	}

result:

1
0

Resolution:

Array is initialized. The copy of arr is the reference of an object, that is, array and arr point to the same array object. Therefore, external changes to the reference object will be reflected on the corresponding object.

We have seen from example 2 that it is not difficult to implement a method to change the parameter state of an object. The reason is very simple. The method obtains a copy of the object reference, and the object reference and other copies reference the same object at the same time.

Many programming languages (especially C + + and Pascal) provide two ways to pass parameters: value call and reference call. Some programmers (even the author of this book) In fact, this understanding is wrong. Because this misunderstanding is universal, a counterexample is given below to illustrate this problem in detail.

example 3

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Student s1 = new Student("Xiao Zhang");
		Student s2 = new Student("petty thief");
		Test.swap(s1, s2);
		System.out.println("s1:" + s1.getName());
		System.out.println("s2:" + s2.getName());
	}

	public static void swap(Student x, Student y) {
		Student temp = x;
		x = y;
		y = temp;
		System.out.println("x:" + x.getName());
		System.out.println("y:" + y.getName());
	}
}

result:

x:petty thief
y:Xiao Zhang
s1:Xiao Zhang
s2:petty thief

Resolution:

Before exchange:

After exchange:

It can be clearly seen from the above two figures that the method does not change the object references stored in variables s1 and s2. The parameters x and y of the swap method are initialized as copies of the two object references, which are exchanged by this method

summary

The Java programming language does not call objects by reference. In fact, object references are called by reference
Value passed.

The following is a summary of the use of method parameters in Java:

  • A method cannot modify a parameter of a basic data type (that is, numeric or Boolean)
  • A method can change the state of an object parameter.
  • A method cannot have an object parameter reference a new object.

reference resources:

Basic knowledge of Java core technology Volume I, 10th edition, Chapter 4, subsection 4.5

II = = and equals (important)

==: it is used to judge whether the addresses of two objects are equal, that is, whether the two objects are the same object. (the basic data type compares the value, and the reference data type compares the memory address)

equals(): it is also used to judge whether two objects are equal. However, it is generally used in two ways:

  • Case 1: the class does not override the equals() method. When comparing two objects of the class through equals(), it is equivalent to comparing the two objects through "= =".
  • Case 2: the class overrides the equals() method. Generally, we override the equals() method to ensure that the contents of two objects are equal; if their contents are equal, it returns true (that is, the two objects are considered equal).

for instance:

public class test1 {
    public static void main(String[] args) {
        String a = new String("ab"); // A is a reference
        String b = new String("ab"); // b is another reference, and the content of the object is the same
        String aa = "ab"; // Put in constant pool
        String bb = "ab"; // Find from constant pool
        if (aa == bb) // true
            System.out.println("aa==bb");
        if (a == b) // false, not the same object
            System.out.println("a==b");
        if (a.equals(b)) // true
            System.out.println("aEQb");
        if (42 == 42.0) { // true
            System.out.println("true");
        }
    }
}

explain:

  • The equals method in String has been overridden because the equals method of object is the memory address of the object to be compared, while the equals method of String compares the value of the object.
  • When creating an object of String type, the virtual opportunity looks for an existing object with the same value as the one to be created in the constant pool. If so, assign it to the current reference. If not, recreate a String object in the constant pool.

III. hashCode and equals (important)

The interviewer may ask you, "have you rewritten hashCode and equals, and why do you have to rewrite the hashCode method when rewriting equals?"

Introduction to hashCode()

hashCode() is used to obtain hash code, also known as hash code; it actually returns an int integer. The function of this hash code is to determine the index position of the Object in the hash table. hashCode() is defined in Object.java of JDK, which means that any class in Java contains hashCode() In addition, it should be noted that the hashcode method of Object is a local method, that is, it is implemented in c language or c + +. This method is usually used to convert the memory address of the Object into an integer and return it.

    /**
     * Returns a hash code value for the object. This method is
     * supported for the benefit of hash tables such as those provided by
     * {@link java.util.HashMap}.
     * <p>
     * As much as is reasonably practical, the hashCode method defined by
     * class {@code Object} does return distinct integers for distinct
     * objects. (This is typically implemented by converting the internal
     * address of the object into an integer, but this implementation
     * technique is not required by the
     * Java&trade; programming language.)
     *
     * @return  a hash code value for this object.
     * @see     java.lang.Object#equals(java.lang.Object)
     * @see     java.lang.System#identityHashCode
     */
    public native int hashCode();

The hash table stores key value pairs. Its feature is that it can quickly retrieve the corresponding "value" according to the "key". This makes use of the hash code! (you can quickly find the required object)

Why hashCode

Let's take "how HashSet checks for duplicates" as an example to illustrate why there is a hashCode:

When you add an object to the HashSet, the HashSet will first calculate the hashcode value of the object to determine the location of the object. At the same time, it will also compare with the hashcode values of other added objects. If there is no matching hashcode, the HashSet will assume that the object does not appear repeatedly. However, if an object with the same hashcode value is found, equals() will be called Method to check whether the objects with equal hashcodes are really the same. If they are the same, the HashSet will not let them join successfully. If they are different, they will be re hashed to other locations. (excerpted from my java enlightenment book Head fist java, Second Edition). In this way, we greatly reduce the number of equals and greatly improve the execution speed.

hashCode() and equals()

  1. If two objects are equal, the hashcode must be the same
  2. If the two objects are equal, calling the equals method on the two objects returns true
  3. Two objects have the same hashcode value, and they are not necessarily equal
  4. Therefore, if the equals method is overridden, the hashCode method must also be overridden
  5. The default behavior of hashCode() is to generate unique values for objects on the heap. If hashCode() is not overridden, the two objects of the class will not be equal in any case (even if they point to the same data)

Why do two objects have the same hashcode value and they are not necessarily equal?

Explain here the problem of a little partner. The following is taken from Head Fisrt Java.

Because the hashing algorithm used by hashCode() may just cause multiple objects to return the same hash value. The worse the hash algorithm is, the easier it is to collide, but this is also related to the characteristics of data value range distribution (the so-called collision means that different objects get the same hashCode).

We just mentioned the HashSet. If the HashSet has multiple objects in the same hashcode during comparison, it will use equals() to judge whether it is really the same. In other words, hashcode is only used to reduce the search cost.

reference resources:

https://blog.csdn.net/zhzhao999/article/details/53449504

https://www.cnblogs.com/skywang12345/p/3324958.html

https://www.cnblogs.com/skywang12345/p/3324958.html

https://www.cnblogs.com/Eason-S/p/5524837.html

Keywords: Java Interview

Added by blackcell on Sun, 26 Sep 2021 22:17:23 +0300