Wie man eine neue Java-Datei im Terminal erstellt

JavaJavaBeginner
Jetzt üben

💡 Dieser Artikel wurde von AI-Assistenten übersetzt. Um die englische Version anzuzeigen, können Sie hier klicken

Introduction

Java is a popular programming language used for a wide range of applications, from desktop software to mobile apps and web services. In this tutorial, you will learn how to create a new Java file, compile it, and run the resulting program using the command line. These fundamental skills form the foundation of Java development, regardless of which tools or frameworks you might use in the future.

By the end of this tutorial, you will understand the basic workflow of Java development and be able to create and execute simple Java programs from the terminal.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java(("Java")) -.-> java/ConcurrentandNetworkProgrammingGroup(["Concurrent and Network Programming"]) java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java/BasicSyntaxGroup -.-> java/output("Output") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("Classes/Objects") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("Class Methods") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("Packages / API") java/ConcurrentandNetworkProgrammingGroup -.-> java/working("Working") subgraph Lab Skills java/output -.-> lab-413984{{"Wie man eine neue Java-Datei im Terminal erstellt"}} java/classes_objects -.-> lab-413984{{"Wie man eine neue Java-Datei im Terminal erstellt"}} java/class_methods -.-> lab-413984{{"Wie man eine neue Java-Datei im Terminal erstellt"}} java/packages_api -.-> lab-413984{{"Wie man eine neue Java-Datei im Terminal erstellt"}} java/working -.-> lab-413984{{"Wie man eine neue Java-Datei im Terminal erstellt"}} end

Creating Your First Java File

In this step, you will create your first Java file using the WebIDE interface. Java files have the .java extension and contain the source code for your Java programs.

Setting Up Your Project Directory

First, let's create a directory structure for your Java project. Open the terminal and follow these commands:

  1. Make sure you are in the project directory:

    cd ~/project
  2. Create a new directory for your Java project:

    mkdir -p java-hello-world/src
  3. Navigate to the source directory:

    cd java-hello-world/src

The terminal should now show that you are in the ~/project/java-hello-world/src directory.

Creating the Java File

Now, let's create a Java file named HelloWorld.java using the WebIDE:

  1. In the file explorer panel on the left side of the WebIDE, navigate to the project/java-hello-world/src folder.

  2. Right-click on the src folder and select "New File".

  3. Name the file HelloWorld.java and press Enter.

  4. The file will open in the editor. Add the following Java code to the file:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
  1. Save the file by pressing Ctrl+S or by going to File > Save.

Understanding the Java File You Created

Let's take a moment to understand the code you just wrote:

  • public class HelloWorld { ... }: This defines a class named HelloWorld. In Java, each public class must be stored in a file with the same name (case-sensitive).

  • public static void main(String[] args) { ... }: This is the main method, which serves as the entry point for your Java application. The Java Virtual Machine (JVM) starts execution from this method.

  • System.out.println("Hello, World!");: This line outputs the text "Hello, World!" to the console.

Congratulations, you have created your first Java file. In the next step, you will learn how to compile this file.

Examining the Java File Structure

Before compiling your Java file, let's take a closer look at how Java files are structured and organized.

Java File Organization

Java files are organized into a structure that reflects the logical organization of your code. The key components include:

  1. Package Declaration (optional): Packages are a way to organize related classes.
  2. Import Statements (optional): These allow you to use classes from other packages.
  3. Class Definition: The main content of your file, which defines a Java class.

For larger projects, the package declaration is important as it helps organize code. Here's how you could modify your HelloWorld.java file to include a package declaration:

  1. Open HelloWorld.java in the editor if it's not already open.

  2. Update the file to include a package declaration at the top:

package com.example.hello;

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
  1. Save the file (Ctrl+S).

Moving the File to Match Package Structure

In Java, the file structure should match the package structure. Let's organize your file accordingly:

  1. Create the directory structure to match the package:

    cd ~/project/java-hello-world/src
    mkdir -p com/example/hello
  2. Move your Java file to the new location:

    mv HelloWorld.java com/example/hello/
  3. Verify the file has been moved:

    ls -l com/example/hello/

You should see output similar to:

total 4
-rw-r--r-- 1 labex labex 135 ... HelloWorld.java

Now your file structure matches the package declaration, which is a best practice in Java development.

Understanding the Relationship Between Files and Packages

The relationship between Java files and packages can be visualized as follows:

  • Package: com.example.hello
  • Directory structure: com/example/hello/
  • File: HelloWorld.java inside the directory structure

This organization helps manage code in larger projects and prevents naming conflicts between classes.

Compiling Your Java Program

After creating your Java file, the next step is to compile it. Compilation is the process of converting human-readable Java code into bytecode that the Java Virtual Machine (JVM) can execute.

The Java Compilation Process

When you compile a Java program:

  1. The Java compiler (javac) reads your .java file
  2. It checks for syntax errors
  3. If no errors are found, it generates a .class file containing bytecode

Compiling Your HelloWorld Program

Now, let's compile the Java file you created:

  1. Navigate to the source directory:

    cd ~/project/java-hello-world/src
  2. Run the Java compiler with your file:

    javac com/example/hello/HelloWorld.java

If there are no errors in your code, the command will complete without any output. This means the compilation was successful.

  1. Verify that a .class file was created:
    ls -l com/example/hello/

You should see output similar to:

total 8
-rw-r--r-- 1 labex labex 416 ... HelloWorld.class
-rw-r--r-- 1 labex labex 135 ... HelloWorld.java

The HelloWorld.class file is the compiled bytecode that can be executed by the JVM.

Handling Compilation Errors

If you made a mistake in your code, the compiler would display error messages. For example, if you forgot to include a semicolon at the end of a statement, you would see an error similar to:

com/example/hello/HelloWorld.java:5: error: ';' expected
        System.out.println("Hello, World!")
                                           ^
1 error

If you encounter any errors, go back to your Java file, fix the issues, and try compiling again.

Running Your Java Program

After successfully compiling your Java program, the final step is to run it. Java programs are executed by the Java Virtual Machine (JVM), which interprets the bytecode in your .class file.

Understanding the Java Runtime Environment

The Java Runtime Environment (JRE) includes the JVM and provides everything needed to run compiled Java programs. When you run a Java program:

  1. The JVM loads the .class file
  2. It verifies the bytecode
  3. It executes the bytecode, starting from the main method

Running Your HelloWorld Program

To run your compiled Java program:

  1. Make sure you are still in the source directory:

    cd ~/project/java-hello-world/src
  2. Use the java command to run your program:

    java com.example.hello.HelloWorld

You should see the following output:

Hello, World!

This confirms that your Java program ran successfully. The text "Hello, World!" was printed to the console, just as you specified in your code.

Important Notes About Running Java Programs

When running Java programs, keep in mind:

  1. You must be in a directory where the compiler can find your package structure (in this case, the src directory).

  2. The java command takes the fully qualified class name (including the package), not the file name.

  3. Do not include the .class extension when running the program.

Making a Change and Running Again

Let's modify your program to print a different message:

  1. Open com/example/hello/HelloWorld.java in the editor.

  2. Change the message in the println statement:

    package com.example.hello;
    
    public class HelloWorld {
        public static void main(String[] args) {
            System.out.println("Java programming is fun!");
        }
    }
  3. Save the file.

  4. Recompile the program:

    javac com/example/hello/HelloWorld.java
  5. Run the program again:

    java com.example.hello.HelloWorld

You should now see the new message:

Java programming is fun!

Congratulations! You have successfully created, compiled, and run a Java program. This workflow forms the foundation of Java development.

Summary

In this tutorial, you have learned the fundamental workflow for Java development:

  1. Creating a Java file with the .java extension
  2. Organizing Java files into package structures
  3. Compiling Java code using the javac command
  4. Running compiled Java programs using the java command

These skills provide a solid foundation for Java development. While modern development often involves integrated development environments (IDEs) that automate many of these steps, understanding the underlying processes is crucial for becoming a proficient Java developer.

Now that you know how to create, compile, and run Java programs from the terminal, you can start exploring more complex Java features and building more sophisticated applications.