The First Java Program
The First Java Program
3.1HelloWorld.java
1 | public class HelloWorld{ |
3.2Code Explanation
-
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 withpublic
should have a class name that matches the file name, such as in the code in 3.1. The file name isHelloWorld.java
, so the class name must beHelloWorld
, otherwise the program will throw an error when running. -
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 themain
function.String[] args
represents the parameters of themain
function, indicating string arguments.The role of
String[] args
: When running Java from the command line, thejava
command is used:java Test value1 value2
, followed by two parameters. Inside themain
function,args[]
is an array of two lengths, wherevalue1
exists inargs[0]
andvalue2
exists inargs[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, usejava filename args parameters
. Theargs
array can receive these parameters. -
Output statements:
System.out.println();
outputs content and moves to the next line.System.out.print();
outputs content without moving to the next line.
-
Every executable statement must end with a
;
. -
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.Semicolon error in Chinese
3.3Output Types
3.3.1Text Output
Enclose the content to be output with ""
double quotes.
1 | System.out.println("HelloWorld!"); |
''
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 | System.out.println('G'); |
3.3.2Numeric Output
Directly output the number. If it includes operators, it will perform the calculation.
1 | System.out.println(1); |
3.3.3Variable Output
Directly output the variable name. Use the +
plus sign to concatenate content.
1 | String a = "你好世界!"; |