[Java Basic Grammar] Arrangement, nice writing

1. Basic Data Types and Encapsulation Types

  • Integer: byte, int, short, long
  • Floating point type: float, double
  • Character type: char
  • boolean: boolean

1. Conversion valueOf() between base type and encapsulated type data

public class StringtoNum { //The main class name needs to match the file name
 //This is a main function
public static void main(String[] args)
//Retrieved from a database num yes String type
String num ="123";
//adopt Integer Encapsulate classes for data conversion
int intVal = Integer.valueOf(num);
//adopt Float Encapsulate classes for data conversion
float fltVal = Float.valueOf(num);
//adopt Long Encapsulate classes for data conversion
long longVal = Long.valueOf(num);
//Output three converted variables in turn
System.out.println(intVal);
System.out.println(fltVal);
System.out.println(longVal);

2. Suggestions for using i++ and ++ I

  • i++ means i plus 1 after expression operation
  • ++ i is the value of an expression after i is added to 1

To improve the readability of the code, it is recommended that left plus and right plus operations not (or as little) be mixed with other operators and written separately if necessary.

int i = 10;
int j = 10;
int k;
//k = i++ *3 not recommended!!!++ I is the same
k = i * 3 ;
i ++;

3. Trinomial operation instead of if statement

Expression 1? Expression 2: Expression 3;

Syntax: Determines the return value of expression 1, executes expression 2 if true, otherwise executes expression 3.

int x = 1001;
String yhx = "nice";
if(x > 1000)
    yhx = "good";
else
    yhx = "nice";
//Trinomial operation
x > 1000 ? yhx = "good": yhx = "nice";

4, ==Differences from equals

  • For base types, ==is the comparison value equal; for encapsulation types, ==is the comparison of addresses that exist in memory equal.
  • For encapsulation types, equals compares whether their values are equal.
public class BasicGrammer {
    public static void main(String[] args) {
        boolean flags = true;
        int i = 10;
        int j = 10;
        flags = (i == j) ? true : false;
        System.out.println(flags);  //true
        Integer x = new Integer("10");
        Integer y = new Integer("10");
        System.out.println(x.equals(y));  //true
        System.out.println(x == y);       //false
    }
}

5. Common Interview Questions

(1) Briefly describe & and the differences between {and}.

A: & and | are bitwise operators, not commonly used; and | are logical operators, usually used in if, while, for.

(2) Run short s1 = 1, s1 = s1 + 1; what happens? Run short s1 = 1; s1 += 1; what happens?

A: Running the first one will result in an error because 1 is of type int and s is of type short, which is automatically converted to type int after the + operation. Error Tip: Error:(21, 17) java: Incompatible type: Converting from int to short may cause loss
Run the second correctly, s1=2, +1 is an int type operation, s1 automatically converts the int type

(3) Use the most efficient method to calculate how much 2 times 8 equals.

Shift operator: int i = 2 << 3;

(4) "==" What is the difference between the equals method and the equals method?

==In base type, compare values equal, compare addresses in memory in encapsulation type
equals compares whether values are equal in encapsulation types.

(5) What is the difference between Integer and int.

Integer is the encapsulation type, contains the basic operations of the int basic type, int is the basic type

12 , -12

(7) Is float f = 3.4 correct?

No!! Incorrect precision, float f = 3.4f or float f = (float)3.4

2. Process Control

1,if ...else

Take leap year as an example

public class BasicGrammer {
    public static void main(String[] args) {
       int year = 2020;
       if((year % 4 ==0 && year % 100 != 0) || (year % 400 == 0)){
           System.out.println("yes");
       }else {
           System.out.println("no");
       }
    }
}

Note: Do not use logical expressions &&and || more than once in an expression. If the requirements are complex, you should break up multiple if...else statements.

2. Avoid short-circuit effect

The main point here is & and || used in if statements!

  • If (expression 1 &&expression 2) If expression 1 is false, expression 2 will not be executed regardless of whether expression 2 is true or false, and if statement is false, it is meaningless

  • If (expression 1 || expression 2) If expression 1 is true, expression 2 will not be executed regardless of whether expression 2 is true or false, and the if statement is true

    public class BasicGrammer {
        public static void main(String[] args) {
        int a = 2 ;
        int b = 3 ;
        if(a > 0 || b-- > a ){
            System.out.println(b);   //b = 3
        }if (a < 0 && ++b > 0){
            }else {
                System.out.println(b);  // b = 3
            }
        }
    }
    

3. default and break in swtich

public class BasicGrammer {
    public static void main(String[] args) {
        char grade = 'A';
        switch (grade){
            case 'A':{
                System.out.println("1000");
                break;
            }
            case 'B':{
                System.out.println("8000");
                break;
            }
            case 'C':{
                System.out.println("600");
                break;
            }
            case 'D':{
                System.out.println("400");
                break;
            }
            case 'E':{
                System.out.println("200");
                break;
            } default:{
                System.out.println("nice");
            }
        }
    }
}

** For each case statement, break is added. Without break, the output will change. Cases without break will output!!** If no break is added, subsequent branch statements will be executed even after the execution of the case branch in this section.

No default error, but add strongly!!!

4. Common Interview Questions

(1) Can the switch statement work on byte, long, String?

  • Can be used on byte, int, short, char, and their encapsulation classes
  • Cannot use long, double, float, boolean, and encapsulation classes on other base types
  • jdk1.7 and above, can be used as a string
  • Can be used for enumeration types

(2) How to jump out of the current multiple nested loop in Java.

Break or continue; break jumps out of the entire cycle; continue jumps out of the current cycle.

(3) What is the difference between while and do while?

  • While is judgement before execution; do... while is execution before judgement, under the same conditions, the latter executes more than once.

(4) Have you ever used the keyword goto? Briefly describe what you think.

Not recommended! It will destroy the structure of the program and make it less readable

3. String Objects

String objects are simple, but "memory content is immutable"

1. String defines variables and constants

String str = "abc";               //Define a constant to store in the constant pool
String str =new String ("abc");  //Defines a variable to store in heap space
  • String constants are stored in constant oil. Java Virtual Machine for optimization considerations 1 allows consistent objects to share memory blocks, but variables are stored in heap space, and memory addresses for different variables with new meaning will not be the same.
  • String constant connection constant, or constant, is still managed by the constant pool, but variable connection constant is a variable.

2. String to understand "Memory value is immutable"

    ......main Method Omitting
	String a =" 123456789 ";
    System.out.println(a.substring(0,5)) ;//12345
    String b = "123456789 ";             //Assume that memory number 1000 is 123456789
    b.substring(0,5);                   //2000 memory, 12345 stored, but not returned, b value unchanged
    //b = b.substring(0,5); //Open up 3000 memory for 12345
    System.out.println(b);               //1000 memory is still 123456789
  • Use constants whenever possible, such as String a=123, and avoid variables such as String a=new String("123").
  • Avoid large-scale String operations, such as connection strings, as this can cause frequent memory fragmentation, which can cause memory performance problems. If you encounter this business need, you should use the StringBuilder object mentioned later.
  • If necessary, use c = c.replace ('1','2') instead of writing c.replace ('1','2').

3. Difference between String and String Builder View memory optimization

String Builder, which is variable and does not fragment memory like String, should be used when manipulating strings frequently

public class StringBuilderdemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();  //Create an object
        sb.append("yhx love ").append("lwh");    
        //Sb = sb.append ("yhx love"). append ("lwh"); is wrong 
        System.out.println(sb.substring(3,8));    //love
        //String val = sb.substring(3,8); not StringBuilder receive object 
        System.out.println(sb);                  //yhx love lwh
        sb.replace(3,8," very like");             //replace
        System.out.println(sb);                    //yhx very like lwh
        sb.deleteCharAt(0);
        System.out.println(sb);                    //hx very like lwh
    }
}

Summary:

  • StringBuilder thread not secure, StringBuffer thread safe
  • StringBuffer performance is slightly lower than StringBuilder to maintain thread security
  • Using StringBuilder with a single thread

4. The toString method that will be called unconsciously

public class toString {
    public static void main(String[] args) {
        int val = 1001;
        System.out.println(val);
        float floatValue = 10;
        System.out.println(floatValue);
        char c = 'a';
        System.out.println(c);
        Integer integer = new Integer("1001");
        System.out.println(integer.toString());
        StringBuilder builder = new StringBuilder();
        builder.append("1001");
        System.out.println(builder);
        System.out.println(builder.toString());
    }
}

  • The System.out.println() method completes the output appropriately based on different types of input parameters (such as int, float, lnteger, etc.)

    Action is called polymorphism.

  • When you define a class yourself, you need to define the toStirng method yourself in Pluto if you want this class to output the appropriate values.

5. String object needs attention

  • String a=123"is defined as a constant in this way, String a=new String("123");Variables are defined in this way.
  • ==is to compare whether address values are consistent and **equals is to compare whether content is consistent.
  • String constants (not only String, Integer, and so on) are placed in a constant pool. Constants with the same value share the same block of memory, and their memory address values are the same by ==comparison.
  • The values defined by String are immutable in memory. If String is operated frequently, memory fragmentation will occur. Unfortunately, IJ is managed in memory performance. In this case, String Builder and String Buffer are recommended. If single-threaded, String Builder is recommended for performance reasons.
  • Through System.out.When println outputs, the default I also calls the toString method. If you define your own class, you can define the output of your class through toString.

6. Common interview questions

(1) Is String our most basic data type? Can it be inherited?

Can't be inherited, it's just an object

(2) String s = new String("xyz"); how many String objects have been created? What is the difference between the two?

Two objects, one xyz in memory, one s, pointing to xyz

(3) What is the difference between String and String Buffer?

  • String operates on strings frequently, creating memory fragmentation that is immutable
  • String Buffer does not fragment memory and is variable

(4) What is the difference between String Buffer phase String Builder?

  • StringBuilder thread not secure, StringBuffer thread safe
  • StringBuffer performance is slightly lower than StringBuilder to maintain thread security
  • Using StringBuilder with a single thread

(5) String classes are immutable classes. Take String as an example to briefly describe what an immutable class is.

(6) String a = "12345";A.substring (0,2); what is the value of a at this point?

a = "12345" because it did not return

(7) String a = "1"; String B = "1", is the value of a==b true or false? Explain the reason.

true, because a and b are constants

4. Encapsulation: Classes and Methods

1. Differences between classes and instances

The class keyword defines the class, and the new keyword creates an object (instance)

2. Reasonable Access Controller Encapsulation

  • If there is no special requirement, set the attribute variables inside the class to private, and let them be used externally through public get and set magic. There are also many people who will be set to public to save time and cumbersome if they accumulate more.
  • If there is a special need, set the class's constructor to public, otherwise it cannot be used externally.
  • Whenever possible, add access controllers before classes, methods, and attribute variables.
Access ControllersimilarSame PackageSubclassDifferent packages
publicAccessibleAccessibleAccessibleAccessible
protectedAccessibleAccessibleAccessibleNot accessible
defaultAccessibleAccessibleNot accessibleNot accessible
privateAccessibleNot accessibleNot accessibleNot accessible

3. Static methods and static variables

Only static methods and static variables can be used in static classes

public class Static {
 private static int value = 1001;
 static void setStatic(){
     System.out.println(Math.abs(value));
 }
 public static void main(String[] args) {
     Static.setStatic();
 }
}
  • Since you can use everything without using new, some programmers will define a lot of static methods to save time; this will break class encapsulation, and

    It also increases the coupling between classes, so you can only define static classes if needed.

  • Static variables are equivalent to global variables, so only variables that will be used throughout the project are set to static.

  • Use static classes and methods in as small a range as possible.

5. Inheritance: Class Inheritance and Interface Implementation

From a syntax point of view, the parent class can be inherited through extends, and the interface can be implemented through implements.
From a project perspective, generic code is typically placed in parent classes and interfaces to avoid large repetitions of code.

What is the difference between an interface and an abstract class?

From the design level, abstraction is the abstraction of classes, a template design, an interface is the abstraction of behavior, and a specification of behavior.

1. Methods for subclasses to override parent classes

class person(){
    protected void speck(){}
}
class ChinesePerson extends person(){
     protected void speck(){}
}

(1)Subclass methods do not reduce access to parent methods. For example, when overriding a parent method in line 5 above, the modifier can be protected or a larger public, but not a reduced private. Private methods defined in the parent cannot be seen by the subclass, so there is no issue of reducing access if protected, public are defined in the parent classOr the default method is always expected to be used or overridden by subclasses, but if you narrow down the scope, such as reducing the protected line 5 to private, your subclasses of ChinsePerson will not see the speak method of your grandparents (that is, the Person class), which will cause the "parent method to be lost".
(2) The subclass method cannot throw more exceptions than the parent method. As to the cause, we will analyze the exception handling later.

2. unavoidable final keyword

The final keyword has a direct relationship to inheritance and override of methods. It can work on classes, methods, and attributes.

  • final works on classes that cannot be inherited
final class Student{
    String id;
    public String get Id () {return id;}
    public void setid(String id) { this . id = id;}

 class subStudent extends Student {}//This sentence will go wrong
  • final works on methods that cannot be overridden (cannot be overridden by subclasses)
class Student{
final void print() {}
}
  • final acts on an attribute that is equivalent to a constant and cannot be changed if an initial value is given
final Stirng a = "1";
String b = "1";
String c = "123";
String d = b + "23"; //At this point D is a variable, not equivalent to String d = "1" + "23"; this D is a constant
System.out.println(c==d);  //false
String e = a + "23"; //e is a constant because final modifies a and a is a constant
System.out.println(c==e);  //true
//a = "4"; ✖

3. Understand finalize methods, but do not override them

Java Virtual Machines provide a special mechanism for slope recycling, where all unused classes are recycled by Java Virtual Machines. This recycling action is transparent to programmers.
When a virtual machine recycles a class, the finalize wildcard of that class is automatically called. If it is not defined in the class, the finalize in the Object class is used, while the finalize wildcard in the Object is blank.

  • To find out what the finalize method does and when it will be called;

  • Do not override finalize methods in custom classes. Writing incorrectly will result in a class that cannot be recycled, resulting in

    A memory overflow error was thrown at the end of a straight increase in memory usage.

6. Polymorphism: The same method has different effects depending on the input

1. Method overload for polymorphism

class demo{
    public void print();
    public void print(int row){
        System.out.println("with 1 int param");
    }
    public void print(int row,int column){
        System.out.println("with 2 int param");
    }
    public void print(int row,String type){
        System.out.println("with 1 int param,with 1 String param");
    }
    ...
}

Note:

  1. When determining overload, the Java compiler only looks at the parameter type, not at the parameter name

    public void print(int row)
    public void print(int column)
    
  2. Modifying the return value of a method for overloading

    public void print(int row,int column)
    public String print(int row,int column)
    

2. Method overload and override

Overload and Override of methods are common points for interviews

class Base{
 public void print () { )
 //Is overloaded because the parameters are different
 public void print (int row) {)
 //Is overloaded because the parameter types are different
 public void print(String type){}
 class Child extends Base{
 //Is override, overrides the parent class's parameterless method with the same name
 public void print() {}
 //Anchor out because the parent already has a method with the same name with an int parameter
 public String print(int row){}
 //Is an override that overrides the method of the same name with a String parameter of the parent class
 public void print(String type){}
     //Is overloaded because the number of parameters is different
 public void print(int row, String type ) {}
 }

 publiC class DifferenceDemo {
 public static void main (String [] args) {
 }
  • If the method name, parameters, and return type are identical, it can be said that the method of the subclass overrides the method of the parent class.

  • If the method has the same name, the number of parameters, or the type is different, there is no need to look at the return type, which is an overload.

  • When a method in a subclass is moved to a parent class, the two method parameters with the same name are identical, but the return type is different. This is a syntax error, Java

    The compiler will report an anchor error for Defining Duplicate Methods.

3. Constructors can overload but cannot override, this and super

A constructor is a special method with no return value that is called when a class, such as new, is created.

Error demonstration:

class parent{
    private int val;
    public parent(int val){this.val = val}
}
class Subclass extends parent{
    public Subclass(int i){  //By default, the system adds super() to invoke the parent class parameterless construction, while there is no parameterless construction in the parent class
        //super(i);Method 2: Add parameterless construction to parent class
    }  
}

Usually used:

class Parent{
    private int value ;
    private String msg ;
    //Calling a constructor with two parameters through this in a constructor without parameters
    public Parent(){ this(O ," call with No Param Function ");}
    public Parent (int val )
    {this . value =val ;  //value assignment to this class via this
     System.out.println ( " with one param ");
    }
    public Parent (int val , String msg){
        System.out.println ("msg is :"+ msg) ;
        System.out.println (" with 2 param");
    }
}
class Subclass extends Parent{
    public Subclass (int i) {//Using super, call the parent class's constructor with one parameter
        super(i);
        System.out.println (" in subclass ");
    }
}
public class ConstructDemo {
    public static void main(String[] args) {
        Parent pO =new Parent();    //msg is:call with No Param Function + with 2 param
        Parent pl =new SubClass(l); // with one param + in subclass
        Parent p2 =new Parent(l ,"new Parent"); //msg is new Parent + with 2 param
        //Subclass s =new Parent(l); //error
    }
}

General use of overloading constructors in projects with inheritance:

  • Multiple constructors can be defined in a class, and this is often seen in constructors.Writing value = xx, which assigns values to the properties of this object based on the input parameters. You can also often see this (xx,'xxx'), which calls the true constructor in a constructor.

  • In the constructor body of a subclass, if nothing is written, the Java compiler defaults to super(), which calls the parameterless constructor in the parent class. If there is no parameterless constructor in the parent class, a syntax error is prompted. To resolve this syntax error, you can define a parameterized constructor in the parent class, or add a super statement.

This points to this class of the method in which it is located

  • Scenario 1: this.value = xxx, copy to this object based on the input parameters
  • Scenario 2: this (O, xxx), calls the construction method of this class with two parameters

Super is the parent class that points to the method in which it is located, for example, where super(xx) is used to call the parent class's constructor

4. Reduce code modification costs through polymorphism

The problem to be solved by polymorphism is to separate abstract business logic from specific implementation details. Generally speaking, polymorphism can be divided into "what to do" and "how to do".

Polymorphisms have two major benefits: modifying points to enrich and barrier-free expansion.

  • Modification point isolation means that when a user modifies the internal implementation details of a business method, the caller can continue to use it without knowledge.
  • "Barrier-free extension" means that if you encounter the need to add new functionality, you can complete the addition without much modification to existing code.

Inheritance + Overwrite

abstract class Employee
{ protected abstract void talkBusiness() ;
 //Sales inherits Employee
 class Sales extends Employee {
     public void talkBusiness()
     {System.out.println(" Sales talk business. ");}
 }
 //Manager inherits Employee
 class Manager extends Employee{
     public void talkBusiness ()
     {System.out.println ("Manager talk business.");}
 }
 public class ExpandDemo {
     public static void main(String[) args){
         Employee sales =new Sales();
         sales.talkBusiness();  //Sales talk business
         Employee manager =new Manager();
         manager.talkBusiness(); //Manager talk business.
     }
}
  • If you want to modify the business code that the salesperson communicates with the customer, you only need to modify the methods of the Sa l e class without changing other classes and methods.
  • If the company wants to add a new business, such as "General Manager and Customer Exchange" business action, simply add a new General Manager class, let it inherit the Employee class, and then define the Talk Business method in it.

5. Common interview questions of object-oriented thinking

1. Openness. Briefly describe your understanding of object-oriented thinking?

Key point 1: First, basic concepts, such as object-oriented thinking, including encapsulation, inheritance, polymorphism, and then syntax, such as the ability to inherit classes through Extends and Implement interfaces through Implements.
Key point 2: Briefly describe the specific benefits of object-oriented thinking in the projects you've worked on, such as combining a specific example (e.g. telecommunications systems)Introduces how to define methods in the parent class, then extend them by inheriting subclasses, which can improve the code structure and reduce the amount of maintenance after code modification by more or less. Note that you cannot just talk about theory, but combine examples from your project.

2. What is the difference between an interface and an abstract class?

From the design level, abstraction is the abstraction of classes, a template design, an interface is the abstraction of behavior, and a specification of behavior.

3. What is the difference between Overload and Override?

Differenceheavy loadRewrite (Overwrite)
parameter listMust be modifiedMust not be modified
Return typeCan be modifiedMust not be modified
abnormalCan be modifiedCan be reduced or deleted, and must not throw new or wider exceptions
VisitCan be modifiedMust not make more restrictions (can reduce restrictions)

Overriding and overloading of methods are different manifestations of java polymorphisms. Overloading is a manifestation of polymorphisms between parent and child classes. Overriding can be interpreted as a specific manifestation of polymorphisms.

  • (1) Method overload is a class that defines multiple methods with the same name, and whose parameters have the same number or number but different types and orders, which is called method overload.
  • (2) Method overrides are methods that have the same name as methods of the parent class in the presence of a subclass, and that return values are the same as the number of parameters and types, called overrides.
  • (3) Method overload is a polymorphism of a class, while method override is a polymorphism of a subclass and a parent.

4. Meaning of this and super

This points to this class of the method in which it is located

  • Scenario 1: this.value = xxx, copy to this object based on the input parameters
  • Scenario 2: this (O, xxx), calls the construction method of this class with two parameters

Super is the parent class that points to the method in which it is located, for example, where super(xx) is used to call the parent class's constructor

5. What is the effect of finalize method?

  • finalize method is called when the class is recycled;

  • Usually this magic is not overridden in a project because it can cause problems with memory recycling

6. The key meaning of final.

  • final works on classes that cannot be inherited
  • Functions on methods that cannot be overridden (cannot be overridden by subclasses)
  • Acts on attributes and is equivalent to a constant, which cannot be changed if an initial value is given

7. Can the constructor be overridden or overloaded?

Can overload, can't overwrite

8. What are the differences between static and instance variables?

  • Static variables are stored in the method area and belong to all classes. Instance variables are stored in the heap and their references exist in the current thread stack.
  • Syntax: static variable plus static, instance variable without
  • Static variables can be referenced directly using the class name without creating an instance object; instance variables can only be used if space is allocated after the instance object is created.
  • Static variables belong to classes, which do not produce objects and can be invoked by class names; instance variables belong to objects of this class and must be generated before instance variables can be invoked.

9. Whether calls to non-static methods can be made from within a static method.

No. Static methods are static methods, methods that belong to classes, and non-static methods are methods that belong to objects. Because non-static methods are associated with objects, you must create an object before you can call non-static methods through this object. Static methods can be called directly through class names without creating objects. That is, in oneWhen a static method is called, no instance object may be created, and if a call to a non-static method is made from within the static, the non-static method cannot be associated with the object.

static is meant to facilitate calls (methods/variables) without creating objects.

10. Briefly describe the differences between the scopes public, private, protected and not written.

Access ControllersimilarSame PackageSubclassDifferent packages
publicAccessibleAccessibleAccessibleAccessible
protectedAccessibleAccessibleAccessibleNot accessible
defaultAccessibleAccessibleNot accessibleNot accessible
privateAccessibleNot accessibleNot accessibleNot accessible

Tags: Java Interview

Posted on Fri, 10 Sep 2021 23:24:12 -0400 by Jagand