Getting started with Java

Keywords: Java Programming

As we all know, the syntax of each language has its own characteristics. When we frequently switch programming languages, we always have to check the cheatsheet. The easiest way is to remember the particularity of a language. The following summarizes the special points of Java to quickly switch from C++/Python to Java.

  1. A Java source code can only define a class of public type, and the class name and file name should be exactly the same. Example of program entry:
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}
  1. The boolean type is Boolean
  2. char type uses single quotation mark 'and has only one character, which should be distinguished from String type String with double quotation mark'.
  3. When defining a variable, if you add the final modifier, the variable becomes a constant.
  4. The compiler will automatically infer that the type of variable sb is StringBuilder according to the assignment statement:
var sb = new StringBuilder();
StringBuilder sb = new StringBuilder();
//They are equivalent
  1. Forced Transformation:
int i = 12345;
short s = (short) i; // 12345
  1. Starting from Java 13, strings can be represented as Text Blocks with ""... "". For example:
public class Main {
    public static void main(String[] args) {
        String s = """
                   SELECT * FROM
                     users
                   WHERE id > 100
                   ORDER BY name DESC
                   """;
        System.out.println(s);
    }
}
  1. Array operation:
public class Main {
    public static void main(String[] args) {
        // Results of 5 students:
        int[] ns = new int[5];
        ns[0] = 68;
        System.out.println(ns.length); // 5

		int[] ns = new int[] { 68, 79, 91, 85, 62 };
		int[] ns = { 68, 79, 91, 85, 62 };//Further abbreviation
		System.out.println(ns.length); // The compiler automatically calculates the array size to 5

		String[] names = {"ABC", "XYZ", "zoo"};
    }
}
  1. println is the abbreviation of print line, which means to output and wrap lines. Therefore, if you don't want to wrap lines after output, you can use print().
  2. Input:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // Create Scanner object
        System.out.print("Input your name: "); // Print tips
        String name = scanner.nextLine(); // Read one line of input and get the string
        System.out.print("Input your age: "); // Print tips
        int age = scanner.nextInt(); // Read a line of input and get an integer
        System.out.printf("Hi, %s, you are %d\n", name, age); // Format output
    }
}
  1. To determine whether the contents of variables of reference types are equal, you must use the equals() method:
public class Main {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "HELLO".toLowerCase();
        System.out.println(s1);
        System.out.println(s2);
        if (s1.equals(s2)) {
            System.out.println("s1 equals s2");
        } else {
            System.out.println("s1 not equals s2");
        }
    }
}
  1. Use yield to return a value as the return value of the switch statement:
public class Main {
    public static void main(String[] args) {
        String fruit = "orange";
        int opt = switch (fruit) {
            case "apple" -> 1;
            case "pear", "mango" -> 2;
            default -> {
                int code = fruit.hashCode();
                yield code; // Return value of switch statement
            }
        };
        System.out.println("opt = " + opt);
    }
}
  1. Traversal array:
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 1, 2, 3, 5, 8 };
        System.out.println(Arrays.toString(ns));
    }
}
  1. Variable parameters are defined by type... And are equivalent to array types:
class Group {
    private String[] names;

    public void setNames(String... names) {
        this.names = names;
    }
}

Group g = new Group();
g.setNames("Xiao Ming", "Xiao Hong", "Xiao Jun"); // Pass in 3 strings
g.setNames("Xiao Ming", "Xiao Hong"); // Pass in 2 strings
g.setNames("Xiao Ming"); // Pass in 1 String
g.setNames(); // 0 strings passed in
  1. Java uses the extends keyword to implement inheritance:
class Person {
    private String name;
    private int age;

    public String getName() {...}
    public void setName(String name) {...}
    public int getAge() {...}
    public void setAge(int age) {...}
}

class Student extends Person {
    // Do not repeat the name and age fields / methods,
    // You only need to define the new score field / method:
    private int score;

    public int getScore() { ... }
    public void setScore(int score) { ... }
}
  1. If an abstract class has no fields and all methods are abstract methods, you can rewrite the abstract class as interface. In Java, you can use interface to declare an interface:
interface Person {
    void run();
    String getName();
}

The so-called interface is a pure abstract interface that is more abstract than an abstract class, because it cannot even have fields. Because all methods defined by the interface are public abstract by default, these two modifiers do not need to be written (the effect is the same whether they are written or not).
17. When a specific class implements an interface, you need to use the implements keyword. For example:

class Student implements Person {
    private String name;

    public Student(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println(this.name + " run");
    }

    @Override
    public String getName() {
        return this.name;
    }
}
  1. We know that in Java, a class can only inherit from another class, not from multiple classes. However, a class can implement multiple interface s, such as:
class Student implements Person, Hello { // Two interface s are implemented
    ...
}
  1. If Xiaojun writes an Arrays class, and the JDK happens to have an Arrays class, how to solve the class name conflict? Xiaojun's Arrays class is stored under the package mr.jun, so the full class name is mr.jun.Arrays:
package mr.jun; // Declare package name mr.jun

public class Arrays {
}
  1. JavaBeans are mainly used to transfer data, that is, to combine a group of data into a JavaBean for easy transmission. In addition, JavaBeans can be easily analyzed by ide tools to generate code for reading and writing properties, which is mainly used in the visual design of graphical interfaces. Getters and setter s can be quickly generated through IDE. For example, in Eclipse, enter the following code first:
public class Person {
    private String name;
    private int age;
}

Then, right-click, select "Source", "Generate Getters and Setters" in the pop-up menu, select the fields to Generate Getters and Setters in the pop-up dialog box, and click OK to complete all method codes automatically by the IDE.

Posted by glansing on Tue, 21 Sep 2021 18:34:30 -0700