The First Java Program

3.1HelloWorld.java

1
2
3
4
5
public class HelloWorld{
public static void main(String[] args){
System.out.println("HelloWorld!");
}
}

Output

3.2Code Explanation

  1. Java is an object-oriented programming language, and the basic component of a program is a class. A program can declare multiple classes, and classes can be modified using access modifiers like public. A class modified with public should have a class name that matches the file name, such as in the code in 3.1. The file name is HelloWorld.java, so the class name must be HelloWorld, otherwise the program will throw an error when running.

  2. The main function of the program is main, which can be understood as the entry point of the program. String[] args must be added, otherwise the program cannot execute.

    In Java, String[] args is the formal parameter of the main function. String[] args represents the parameters of the main function, indicating string arguments.

    The role of String[] args: When running Java from the command line, the java command is used: java Test value1 value2, followed by two parameters. Inside the main function, args[] is an array of two lengths, where value1 exists in args[0] and value2 exists in args[1].

    In Java, there is a statement: public static void main(String[] args). Here, args is the command-line argument in Java. When executing Java programs in DOS, use java filename args parameters. The args array can receive these parameters.

  3. Output statements:

    • System.out.println(); outputs content and moves to the next line.
    • System.out.print(); outputs content without moving to the next line.
  4. Every executable statement must end with a ;.

  5. Before writing the program, make sure to switch the input method to English. All symbols in Java, such as ,;:''""!(){}[], must be entered using the English input method. Using Chinese will result in an error.

    Error

    Semicolon error in Chinese

3.3Output Types

3.3.1Text Output

Enclose the content to be output with "" double quotes.

1
2
3
4
System.out.println("HelloWorld!");
//output:HelloWorld!
System.out.println("你好世界!");
//output result:你好世界!

'' single quotes can only output a single character, which is of the char type. If there are multiple characters inside the single quotes, it will result in an error.

1
2
3
4
System.out.println('G');
//output:G
System.out.println('好');
//output result:好

3.3.2Numeric Output

Directly output the number. If it includes operators, it will perform the calculation.

1
2
3
4
System.out.println(1);
//output:1
System.out.println(1 + 3);
//output:4

3.3.3Variable Output

Directly output the variable name. Use the + plus sign to concatenate content.

1
2
3
4
5
6
String a = "你好世界!";
String b = "今天天气真好。"
System.out.println(a);
//output result:你好世界!
System.out.println(a + b);
//output result:你好世界!今天天气真好。