Interview 12 questions every day

Posted by rline101 on Sat, 15 Jan 2022 16:43:42 +0100

1. Differences between static variables and instance variables

Static variable: because static variables do not belong to any instance object and belong to a class, there will only be one copy in memory. During class loading, the JVM will allocate memory space for static variables only once.
Instance variable: each time an object is created, the memory space of member variables will be allocated for each object. Instance variables belong to instance objects. In memory, when an object is created several times, there are several member variables.

2. Differences between static variables and ordinary variables

Static variables are also called static variables. The difference between static variables and non static variables is that static variables are shared by all objects and have only one copy in memory. It will be initialized when and only when the class is first loaded. Non static variables are owned by objects. They are initialized when creating objects. There are multiple copies, and the copies owned by each object do not affect each other.

Another point is that static member variables are initialized in the defined order.

3. What is the difference between static method and instance method?

The difference between static method and instance method is mainly reflected in two aspects:

When calling static methods externally, you can use either "class name. Party name" or "object name. Method name". The instance method has only the latter method. That is, calling a static method eliminates the need to create an object.
When accessing members of this class, static methods only allow access to static members (i.e. static member variables and static methods), but not instance member variables and instance methods; Instance methods do not have this restriction

4. Why is it illegal to call a non static member in a static method?

Because static methods can not be called through objects, other non static variables and non static variable members cannot be called in static methods.

5. What is the return value of a method? What is the function of the return value?

The return value of a method refers to the result obtained after the code in a method body is executed! (provided that the method may produce results). Function of return value: receive the result so that it can be used for other operations!

6. What is an internal class?

In Java, you can put the definition of one class inside the definition of another class, which is the inner class. The internal class itself is an attribute of the class, which is consistent with the definition of other attributes.

7. What are the classifications of internal classes

Internal classes can be divided into four types:

Member inner classes, local inner classes, anonymous inner classes, and static inner classes.

Static inner class
A static class defined inside a class is a static inner class.

public class Outer {

    private static int radius = 1;

    static class StaticInner {
        public void visit() {
            System.out.println("visit outer static  variable:" + radius);
        }
    }
}

Static internal classes can access all static variables of external classes, but not non static variables of external classes; Static internal class creation method, new external class Static inner class (), as follows:

Outer.StaticInner inner = new Outer.StaticInner();
inner.visit();

Member inner class
A non static class defined within a class and at a member location is a member inner class.

public class Outer {

    private static  int radius = 1;
    private int count =2;
    
     class Inner {
        public void visit() {
            System.out.println("visit outer static  variable:" + radius);
            System.out.println("visit outer   variable:" + count);
        }
    }
}

Member inner classes can access all variables and methods of outer classes, including static and non-static, private and public. The inner class of the member depends on the instance of the outer class, and its creation method is the instance of the outer class new inner class (), as follows:

Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.visit();

Local inner class
The internal class defined in the method is the local internal class.

public class Outer {

    private  int out_a = 1;
    private static int STATIC_b = 2;

    public void testFunctionClass(){
        int inner_c =3;
        class Inner {
            private void fun(){
                System.out.println(out_a);
                System.out.println(STATIC_b);
                System.out.println(inner_c);
            }
        }
        Inner  inner = new Inner();
        inner.fun();
    }
    public static void testStaticFunctionClass(){
        int d =3;
        class Inner {
            private void fun(){
                // System.out.println(out_a);  Compilation error. Local classes defined in static methods cannot access instance variables of external classes
                System.out.println(STATIC_b);
                System.out.println(d);
            }
        }
        Inner  inner = new Inner();
        inner.fun();
    }
}

The local class defined in the instance method can access all variables and methods of the external class, and the local class defined in the static method can only access the static variables and methods of the external class. The creation method of the local internal class, in the corresponding method, new internal class (), is as follows:

 public static void testStaticFunctionClass(){
    class Inner {
    }
    Inner  inner = new Inner();
 }

Anonymous Inner Class

Anonymous internal classes are internal classes without names, which are often used in daily development.

public class Outer {

    private void test(final int i) {
        new Service() {
            public void method() {
                for (int j = 0; j < i; j++) {
                    System.out.println("Anonymous Inner Class " );
                }
            }
        }.method();
    }
 }
 //Anonymous inner classes must inherit or implement an existing interface 
 interface Service{
    void method();
}

In addition to having no name, anonymous inner classes have the following characteristics:

Anonymous inner classes must inherit an abstract class or implement an interface.
Anonymous inner classes cannot define any static members and static methods.
When the formal parameter of the method needs to be used by the anonymous inner class, it must be declared as final.
Anonymous inner classes cannot be abstract. They must implement all abstract methods of inherited classes or implemented interfaces.
Anonymous inner class creation method:

new class/Interface{ 
  //Anonymous inner class implementation part
}

8. Advantages of internal classes

Why should we use inner classes? Because it has the following advantages:
● an internal class object can access the contents of the external class object that created it, including private data!
● the internal class is not seen by other classes in the same package and has good encapsulation;
● the internal class effectively implements "multiple inheritance" and optimizes the defects of java single inheritance.
● anonymous inner classes can easily define callbacks.

9. What are the application scenarios of internal classes

  1. Some multi algorithm occasions
  2. Solve some non object-oriented statement blocks.
  3. Proper use of internal classes makes the code more flexible and extensible.
  4. When a class is no longer used by other classes except its external class.

10. When local inner classes and anonymous inner classes access local variables, why must final be added to the variables?

Because the inner class cannot be modified

11. There are five students. Each student has the scores of three courses. Input the above data from the keyboard (including student number, name and scores of three courses), calculate the average score, and store the original data and the calculated average score in the disk file "study".

package test2;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Scanner;

class Student {
	String num;
	String name;
	double[] score;
	double agv;

	Student() {
		num = null;
		name = null;
		score = new double[3];
		for (int i = 0; i < 3; i++) {
			score[i] = 0;
		}
	}

	Student(String num, String name, double s1, double s2, double s3) {//There are no requirements for this topic
		this.num = num;
		this.name = null;
		score = new double[3];
		score[0] = s1;
		score[1] = s2;
		score[2] = s3;
	}

	double agv(double[] n) {
		double v = 0;
		for (int i = 0; i < n.length; i++) {
			v += n[i];
		}
		return v / n.length;
	}
}

public class test50 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		Student[] student = new Student[5];
		;
		for (int i = 0; i < 5; i++) {
			student[i] = new Student();
		}
		Scanner sc = new Scanner(System.in);
		BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
		for (int i = 0; i < 5; i++) {
			System.out.println("Please enter page" + (i + 1) + "Students' grades");
			student[i].num = sc.next();
			student[i].name = sc.next();
			student[i].score[0] = sc.nextDouble();
			student[i].score[1] = sc.nextDouble();
			student[i].score[2] = sc.nextDouble();
			student[i].agv = (student[i].score[0] + student[i].score[1] + student[i].score[2]) / 3;
		}
		try {
			BufferedWriter w = new BufferedWriter(
					new OutputStreamWriter(new FileOutputStream("C:\\360Downloads\\stud")));
			for (int i = 0; i <5; i++) {
				w.write(student[i].num);
				w.write(student[i].name);
				w.write(String.valueOf(student[i].score[0]));//Converts a score of type double to a score of type String
				w.write(String.valueOf(student[i].score[1]));//Because the write method cannot write a value of type double
				w.write(String.valueOf(student[i].score[2]));
			}
			w.flush();
			w.close();
			System.out.println("ture");//The output was saved successfully
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

}

12. A company uses a public telephone to transmit data. The data is a four digit integer and is encrypted in the transmission process. The encryption rules are as follows: add 5 to each number, then replace the number with the remainder of sum divided by 10, and then exchange the first and fourth bits, and the second and third bits.

public class work2 {
    public static int shuru() {
        Scanner s = new Scanner(System.in);
        System.out.println("Please enter a four digit integer:");
        int su = s.nextInt();
        return su;
    }
    public static void suan(int i) {
        int a = i / 1000;
        int b = i / 100 % 10;
        int c = i / 10 % 10;
        int d = i % 10;
        a += 5;
        b += 5;
        c += 5;
        d += 5;
        a = a % 10;
        b = b % 10;
        c = c % 10;
        d = d % 10;
        System.out.println(d +""+ c +""+ b +""+ a);
    }
    public static void main(String[] args) {
        int i = shuru();
        suan(i);
    }
}

Topics: Java Interview