java written test questions and answers (for reference only)

Keywords: Java less

1. Operator priority. What is the result of the following code?

public class Test {

public static void main(String[] args) {  
    int k = 0;  
    int ret = ++k + k++ + ++k + k;  
    // What is the value of ret  
    System.err.println(ret);  
}  

}
Answer: mainly investigate the difference between + + i and i + +. ++In the first place, the value is automatically increased and then assigned; in the second place, the value of + + is first assigned and then added. Therefore, the result is 8.

2. Operator problem. What are the following codes output?

public class Test {

public static void main(String[] args) {  
    int i1 = 10, i2 = 10;  
    System.err.println("i1 + i2 = " + i1 + i2);  
    System.err.println("i1 - i2 = " + i1 - i2);  
    System.err.println("i1 * i2 = " + i1 * i2);  
    System.err.println("i1 / i2 = " + i1 / i2);  
}  

}
Answer: it mainly focuses on two points: the priority of the operator and the + in the string and number are the join symbols. In the first article, all of them are additive, so the sequential operation from the front to the back is to add strings and numbers, and then connect them to a string, and then add them to the following numbers, and then connect them to a string again, so the result is "i1 + i2 = 1010". The second one is wrong. The string cannot be connected to the number with a minus sign. The priority of multiplication and division in Article 3 and Article 4 is high, which will be calculated first and then connected with the string, so the results are respectively: "I1 I2 = 100", "i1i2 = 1".

3. What is the result of the following code?

public class Test {

  
public void myMethod(String str) {  
    System.err.println("string");  
}  
  
public void myMethod(Object obj) {  
    System.err.println("object");  
}  
  
public static void main(String[] args) {  
    Test t = new Test();  
    t.myMethod(null);  
}  

}
Answer: this question investigates the call problem when the overloaded method parameter has inheritance relationship, and the understanding of null. If an object with inheritance relationship is used as a parameter, see the reference of the object, such as:
class A {
}

class B extends A {
}

public class Test {

public static void main(String[] args) {
    A b1 = new B();
    B b2 = new B();
    get(b1);// A
    get(b2);// B
}

public static void get(A a) {
    System.out.println("A");
}

public static void get(B a) {
    System.out.println("B");
}

}
In this problem, Object is the parent of all classes and has inheritance relationship. What does null point to? Null is the initial value of any reference type. The initial values of string and Object are all null. However, null will preferentially match the method whose reference type parameter is string, so the answer to this question is string. Suppose there are other overloaded methods of the same reference type in this problem? Such as:
public void myMethod(Integer obj) {

System.err.println("Integer");  

}
If this is the case, an error will be reported when calling the null parameter passed in this method. He does not know which method to select for the matching call.

4. Suppose today is September 8, what is the output of the following code?

public class Test {

public static void main(String[] args) {  
    Date date = new Date();  
    System.err.println(date.getMonth() + " " + date.getDate());  
}  

}
Answer: this question investigates that the month obtained from the date starts from 0, so it will be 1 less than our daily month. The answer to this question is 8 8.

5. What is the output result of the following code?

public class Test {

public static void main(String[] args) {  
    double val = 11.5;  
    System.err.println(Math.round(val));  
    System.err.println(Math.floor(val));  
    System.err.println(Math.ceil(val));  
}  

}
Answer: here are three ways to get an integer for Math. Round () is to round off the evidence, floor () is to round off the decimal places, ceil () is to move up. Floor is the floor ceil is the ceiling, if one is under, it will be discarded, if one is on, it will go up 1. Should the result be 12, 11, 12? Also consider the return value type. The return value type of round() is long, and the return value of floor() and ceil() is double. Therefore, the correct answer should be 12, 11.0 and 12.0.

6. Program and output all directories and file names under a directory, and use tab between directories.

public class Test {

public static void main(String[] args) {  
    new Test().read("D:/test", "");  
}  
  
public void read(String path, String tab) {  
    File file = new File(path);  
    File[] childFiles = file.listFiles();  
    for (int i = 0; childFiles != null && i < childFiles.length; i++) {  
        System.err.println(tab + childFiles[i].getName());  
        if (childFiles[i].isDirectory()) {  
            read(childFiles[i].getPath(), tab + "\t");  
        }  
    }  
}  

}
This is mainly to investigate some knowledge points of IO.

7. Read in 10 integers from the keyboard, and then output from large to small.

public class Test {

public static void main(String[] args) {  
    Scanner in = new Scanner(System.in);  
    // Notice that the array here is not int's  
    Integer[] arr = new Integer[10];  
    for (int i = 0; i < 10; i++) {  
        arr[i] = in.nextInt();  
    }  
    Arrays.sort(arr, new Comparator<Integer>() {  
        @Override  
        public int compare(Integer o1, Integer o2) {  
            if (o1 > o2) return -1;  
            if (o1 < o2) return 1;  
            return 0;  
        }  
          
    });  
    System.err.println(Arrays.toString(arr));  
}  
  

}

8. What is the result of the following code?
public class Test extends Base {

public static void main(String[] args) {  
    Base b = new Test();  
    b.method();  
      
    Test t = new Test();  
    t.method();  
}  

@Override  
public void method() {  
    System.err.println("test");  
}  
  

}

class Base {

public void method() throws InterruptedException {  
    System.err.println("base");  
}  

}
Answer: the output of both calls is test. In the case of polymorphism, although it is a reference of the parent class, the method of the child class is still called when the method is called.

9. What is the result of the following code?

package test;  
  
public class Test extends Base {  
  
    public static void main(String[] args) {  
        new Test().method();  
    }  
  
    public void method() {  
        System.err.println(super.getClass().getName());  
        System.err.println(this.getClass().getSuperclass().getName());  
    }  
      
}  
  
class Base {  
}  

Answer: the first output is test.Test, and the second output is test.Base. It's easy to think that super calls the parent class, but it's still the same class. I didn't understand the specific reasons. Please leave a message if you understand.

10,true or false?

public class Test {

public static void main(String[] args) {  
    String str1 = new String("abc");  
    String str2 = new String("abc");  
    System.err.println(str1.equals(str2));  
      
    StringBuffer sb1 = new StringBuffer("abc");  
    StringBuffer sb2 = new StringBuffer("abc");  
    System.err.println(sb1.equals(sb2));  
}  

}
Answer: the first is true, the second is false. String overrides the equals method in Object. It will split string into character arrays and compare each character one by one. The code is as follows:

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;
}

The r equests method in Object is as follows:

public boolean equals(Object obj) {
    return (this == obj);
}

11. What is the output result?
public class Test {

public static void main(String[] args) {  
    System.err.println(new Test().method1());  
    System.err.println(new Test().method2());  
}  
  
public int method1() {  
    int x = 1;  
    try {  
        return x;  
    } finally {  
        ++x;  
    }  
}  
  
public int method2() {  
    int x = 1;  
    try {  
        return x;  
    } finally {  
        return ++x;  
    }  
}  

}
Answer: the first returns 1, and the second returns 2. The code in finally must be executed after the code in try is executed. Therefore, if return returns in try, the return value in try will be overwritten.
What if?

public class Test {

public static void main(String[] args) {  
    System.err.println(method());  
}  
  
public static boolean method() {   
     try {   
        return true;   
    } finally {   
      return false;  
    }   
}  

}
Obviously the return value should be false.

12. Is there any difference between method m1 and method m2?

public class Test {

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

public synchronized void m1() {  
}  

public static synchronized void m2() {  
}  

}
Answer: what we are looking at here is the synchronization method. When synchronized modifies a method, it locks the object that calls the method. It does not make multiple objects calling the method mutually exclusive in execution order, so static modifiers are necessary. So when static is not applicable, create multiple objects to execute the method, and the locks are not the same. What else can we synchronize? Therefore, only after static decoration can we achieve the desired effect.

13,true or false?

public class Test {

public static void main(String[] args) {  
    Integer i1 = 127;  
    Integer i2 = 127;  
    System.err.println(i1 == i2);  
      
    i1 = 128;  
    i2 = 128;  
    System.err.println(i1 == i2);  
}  

}
Answer: This is an investigation of the sharing pattern applied in the Integer packing type. Please take a look at the details http://blog.csdn.net/m0_37240709/article/details/78644341

14,true or false?

public class Test {

public static void main(String[] args) {  
    String str1 = "a";  
    String str2 = "a";  
    String str3 = new String("a");  
      
    System.err.println(str1 == str2);  
    System.err.println(str1 == str3);  
    str3 = str3.intern();  
    System.err.println(str1 == str3);  
}  

}
Answer: This is the investigation of String Pool. See http://blog.csdn.net/m0_37240709/article/details/78642110

15,true or false?

public class Test {

public static void main(String[] args) {  
    System.err.println(12 - 11.9 == 0.1);  
}  

}
Answer: the result is false. I just want to say what I think about this problem. 12-11.9 will be converted into an object after calculation, not the basic data type, so it will be false when making identity judgment.

16. What is the following code output?

public class Test {

public static void main(String[] args) {  
    BigInteger one = new BigInteger("1");  
    BigInteger two = new BigInteger("2");  
    BigInteger three = new BigInteger("3");  
    BigInteger sum = new BigInteger("0");  
    sum.add(one);  
    sum.add(two);  
    sum.add(three);  
    System.out.println(sum.toString());  
}  

}
Answer: This is a study of large integers. Is the result 6? It looks like there's nothing wrong, but it's not. sum.add(one) is different from our basic type sum+=one. The former does not assign the result to the sum object, and the result is assigned the return value of this statement. So no matter how add, the value of sum object is unchanged, so the result is 0.

17. What is the output result?

public class Test {

public static void main(String[] args) {  
    Set<String> set = new HashSet<String>();  
    set.add("one");  
    set.add("two");  
    set.add("three");  
    set.add("four");  
    set.add("five");  
    for (Iterator<String> it = set.iterator(); it.hasNext();) {  
        System.err.println(it.next());  
    }  
}  

}
Answer: the order of the results is four one two three five. Students who understand are welcome to leave comments.

18. How to iterate the Map container?

Map<String, String> map = new HashMap<>();
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for(Map.Entry<String, String> entry : entrySet){
    String key = entry.getKey();
    String value = entry.getValue();
}

Set<String> keySet = map.keySet();
Iterator<String> it1 = keySet.iterator();
if(it1.hasNext())
    System.out.println(it1.next());

Collection<String> values = map.values();
Iterator<String> it2 = values.iterator();
if(it2.hasNext())
    System.out.println(it2.next());

19. Output result of the following code

public class Test {  
  
    public static void main(String[] args) {  
        System.err.println(args.length);  
    }  
      
}  
/* 
A. null     B. 0        C. Test 
D. Exception in thread "main" java.lang.NullPointerException 
*/  

Answer: 0.

20. The following is a single example of the implementation code. Please point out several errors or irrationalities in the code and correct them.

public class Test {  
      
    public Test instance = null;  
      
    public static Test getInstance() {  
        if (instance == null) {  
            instance = new Test();  
            return instance;  
        }  
    }  
}  

Answer: the single instance mode should meet three requirements: 1. Privatization construction method; 2. Creating private static objects; 3. Providing public static methods to obtain unique instances. Therefore, the error contains: 1. The constructor is not privatized, 2. The object is not privatized, and 3. The return in the method to get the instance should not be included in the condition.
--------
I feel that the answers to the seventeen questions are random. The results I print are different from yours. The Hashset set set is disordered and the elements are not repeated, so when inserting data, it is random. Therefore, the results will not be printed in the order of one two there four five.
1@Test
2 public void test2() {
3 Set set = new HashSet();
4 set.add("one");
5 set.add("two");
6 set.add("three");
7 set.add("four");
8 set.add("five");
9 for (Iterator it = set.iterator(); it.hasNext();) {
10 System.err.print(it.next()+" ");
11 //two five one three four
12 }
13 }
In 2019, as long as the price list of popular models of Alibaba cloud's double 11 activity is new users, they can buy directly, without the need to group, without any threshold.
(https://www.aliyun.com/1111/2019/group-buying-share?spm=a2c4e.11153940.0.0.59e85d407TbQ62&ptCode=4F3EAAA24826E82EB0B79C1A87FF53FE647C88CF896EF535&userCode=btodw2md&share_source=copy_link) (the price is really low 86 / year. If you want to study, you can think of a |)

Posted by 3dron on Mon, 04 Nov 2019 22:33:52 -0800