For our first Java program, we didn’t use an IDE (Integrated Development Environment) — Development tools.
Use whatever editor you like — notepad, notepad++, vscode, sublime, etc. — but don’t use an editor like word, which can throw in special formatting that can cause compiler errors. Then write the following lines of code.
public class Demo {
public static void main(String[] args) {
System.out.println("Hello, world!"); }}Copy the code
Then, save the file as demo.java and keep the file suffix Java to indicate that it is a Java code file with the same name as after the class keyword.
Let’s run the program and walk through the lines.
Run your first Java program
To run Java code, it first needs to be turned into bytecode files, and Javac may compile.java files into.class bytecode files.
Step 1. Run the following command on the terminal to compile the file.
javac Demo.java
Copy the code
We’ll get a bytecode file named demo.class under the current directory.
Step 2. Run the command Java.
java Demo
Copy the code
You’ll see a line like this on the terminal:
Hello, world!
Copy the code
Program executed successfully!
The code on
Unlike C++, python, etc., Java code always appears in classes. How to define a class:
public class Demo {}Copy the code
Public and class are Java keywords and reserved Java characters. We cannot use these reserved names. Public: The Demo class is public and can be accessed by other classes. The class keyword is used to modify classes, so Demo is a class. Classes will be covered in more detail in a later section, but here you just need to know that it is a class.
In the Demo class, we define a method (also called a function) named main. The main method is the entry point for Java programs to run.
public static void main(String[] args) {
System.out.println("Hello, world!");
}
Copy the code
The public modifier means that this is a public method and can be accessed by external classes, and the static modifier means that this is a static method.
Void void is the return type of this function. Void is the return type of this function.
Main is the method name.
String[] args is enclosed in parentheses and is an input parameter to the method. String[] is an array of strings, and args is the parameter name.
Statements in braces are method bodies. In this case, it prints a string “Hello, world!” To standard output (terminal).
Methods in programming languages are somewhat similar to functions in mathematics. Here’s an analogy.
conclusion
main
Methods are entrances to Java programs that are defined in classes;- The name of a program file must be the same as that in it
public
Modify the same name. - use
javac
Compile the source file as a bytecode file, usingjava
Command to run bytecode.
Question
A Java program can have more than one source filepublic
Modified class?