Compile and run Java on the command line

Introduction This article is a record of what I understand for those who are studying Java.

The Java functions and description methods are described in the following list.

-Variables and types, type conversion -Variable Scope ・ Character string operation (in preparation) ・ Array operation (in preparation) ・ Operator (in preparation) ・ Conditional branch (in preparation) ・ Repeat processing (in preparation) -Exception handling ・ About class (in preparation) ・ Abstract class (in preparation) ・ Interface (in preparation) ・ Encapsulation (in preparation) ・ About the module (in preparation)

However, in this article, apart from the list, I will describe the execution on the command line that was done in the article.

What is the command line

When I first heard this word, I didn't understand it, but it seems that the line displayed at the command prompt on windows and the terminal on mac is called the command line. In this article, I will assume that Java is installed and try running Java at the command prompt of mac terminal and windows. There is also an article I mentioned earlier about environment construction, so I hope you can refer to it. Java development environment

I have some code to compile, so I made Hello World.

class Test{
    public static void main(String args[]){
        System.out.println("Hello World!");
    }
}

This is the first Hello World statement that often appears when learning a program. A simple code that outputs Hello World.

compile

Let's compile the above code. By the way, compiling is simply rewriting the code in a computer-readable sentence.

$javac The java file you want to compile

Compile test.java with the above code in the test folder.

test$ javac test.java

This command loads test.java, looks at the classes in your code, and generates a class file. By the way, if there are multiple classes in the java file, all the class files will be generated.

class Test{
    public static void main(String args[]){
        System.out.println("Hello World!");
    }
}

class Sample{}

class Mikan{}

I created a Sample class and a Mikan class, but nothing is described in them. Compile this code.

test$ javac test.java

You have now generated three class files: Test.class, Sample.class, and Mikan.class.

Run

$java Class file name you want to execute

This command executes inside the main method in the class. Let's enter the above at the command prompt (terminal).

test$ java Test

Result is

Hello World!

The output statement in the main method in the Test class is displayed.

That's all for running at the command prompt (terminal), but there is one thing to keep in mind.

Since it is executed inside the main method, if there is no main method, even if the compilation is successful, an error will occur.

class Test{}

I compile this code, but I can generate a class file (Test.class) without error.

test$ javac test.java

Let's run it with the created file.

test$ java Test

I got an error when I ran it.

error:The main method cannot be found in class Test. Define the main method as follows:
   public static void main(String[] args)

Remember that the class you run needs a main method.

Debug execution

You can also debug on the command line. To put it simply, debug execution is to check how the implemented program works. Let's actually do it on the command line.

test.java

class Main{
    int instans = 60;
    static int global = 95;

    static void debug(){
        System.out.println();
        System.out.println("Debug execution");
    }

    void print(){
        System.out.println("print()");
    }

    public static void main(String args[]){
        Main.debug();
        System.out.println("main start");

        int x = 50;

        String str = "Character type";

        Main m = new Main();

        x = 100;

        str = "Character type conversion";

        m.print();

        System.out.println("main end");
    }
}

Compile the java file described above, but there are some things to be careful of when you want to debug.

$ javac -g test.java

Let's set -g as a compile-time option. Now you can use the debug function called jdb that comes standard with the JDK. Let's start jdb at once.

$ jdb Main
> 

You can debug by typing various commands on the above arrows, but first you can't do anything unless you run it, so let's put in the run command. Now the vm works.

> run
VM started: 
Debug execution
main start
print()
main end

However, with just the run command, jdb will be terminated just by executing it. Therefore, set a breakpoint in advance. A breakpoint is a location that stops working during execution, and you can specify that location with a command.

> stop in Main.debug

I think that the command input state will be entered when the debug method running in the main method starts running. Let's actually run it.

> run
VM started:Delayed breakpoint Main.debug settings

Hit breakpoint: "thread=main", Main.debug(),line=8 bci=0
8            System.out.println();
main[1] 

This state indicates that the program is stopped at this location. For a closer look, let's use the list of execution location confirmation commands.

main[1] list
4        int instans = 60;
5        static int global = 95;
6    
7        static void debug(){
8 =>         System.out.println();
9            System.out.println("Debug execution");
10        }
11    
12        void print(){
13            System.out.println("print()");

It will be displayed. I think it's easier to see that it's stopped at the output of the debug method.

Step execution

Let's proceed with the program stopped by the above code. This step will allow you to step through the code line by line. Let's continue with the above.

step
Step completed: "thread=main", Main.debug(),line=9 bci=6
9            System.out.println("Debug execution");

Step execution was performed. Look at the list again.

5        static int global = 95;
6    
7        static void debug(){
8            System.out.println();
9 =>         System.out.println("Debug execution");
10        }
11    
12        void print(){
13            System.out.println("print()");
14        }

Before the step execution, it stopped at the 8th line, but now it is the 9th line. It means that you are proceeding line by line. Let's step further and display the list

step
>Debug execution

By stepping, the output processing is working.

Check the list after performing the step.

list
6    
7        static void debug(){
8            System.out.println();
9            System.out.println("Debug execution");
10 =>     }
11    
12        void print(){
13            System.out.println("print()");
14        }
15    

Also, I think it's easy to understand that you are reading the one-line code.

So far, we have introduced the commands and operations of step execution, but from here, we will explain the usefulness of step execution.

First of all, let's perform step execution until the execution wait is as follows in list.

20            int x = 50;
21    
22            String str = "Character type";
23    
24 =>         Main m = new Main();
25    
26            x = 100;
27    
28            str = "Character type conversion";
29    

At the time when the processing up to this point is operating, values are entered in the variables x and str, respectively. I'm assigning another value after this code, but during this step you can see the value of the variable at this point.

Use the locals command to display the values of local variables.

main[1] locals 
Local variables:
x = 50
str = "Character type"

As you can see, the current value of the local variable is displayed.

As you proceed with this code, the value will be rewritten, so let's step through until the end of the assignment.

26            x = 100;
27    
28            str = "Character type conversion";
29    
30 =>         m.print();
31    
32            System.out.println("main end");
33        }
34    }

At this point, we have replaced the values for x and str, respectively. Let's check it again with the locals command.

main[1] locals
Local variables:
x = 100
str = "Character type conversion"
m = instance of Main(id=422)

The values have been rewritten because the x and str value changes are working at the current step execution stage. Also, since the variable m is declared and the instance is assigned, the variable m is also newly displayed.

In this way, you can see the state of the value at the time when the program is running and looking at it, so when you check the operation, you can check whether the value you intended is included at any time.

By the way, when you want to check one local variable, you can also check the contents of instance variables and static variables by using the print command.

Local variables

main[1] print str
str = "Character type conversion"

Instance variables

main[1] print m.instans
m.instans = 60

static variable

main[1] print Main.global
Main.global = 95

At the end

In this article, I tried stepping Java while compiling, executing, and debugging at the command prompt (terminal). After installing Java, you will be able to do it, so why not give it a try?

However, I think that the tools installed in the development environment etc. are easier to use than the debug execution from the command line. Please also refer to the following article for debugging with eclipse.

Debug execution in IDE

Recommended Posts

Compile and run Java on the command line
Compile Java at the command prompt
Instructions for installing and using the AWS command line (awscli) on CentOS
Run PostgreSQL on Java
Compile with Java 6 and test with Java 11 while running Maven on Java 8
Decomposing the Docker run command. .. ..
Run java applet on ubuntu
How to run React and Rails on the same server
I want to use Java Applet easily on the command line without using an IDE
Run Java EE applications on CICS
OpenJDK 8 java and javac command help
Run the AWS CLI on Docker
Consideration on the 2017 Java Persistence Framework (1)
Run tomcat shell script on java8
Enable Java 8 and Java 11 SDKs on Ubuntu
Notes on Java path and Package
Install Java 9 on windows 10 and CentOS 7
Install the memcached plugin on MySQL and access it from Java
How to run a Kotlin Coroutine sample from the command line
Comparison of processing times based on awk, shell command, and Java
Install Ubuntu20.04 on RaspberryPi 4 and build Kubernetes to run the container
My thoughts on the equals method (Java)
A note on the differences between interfaces and abstract classes in Java
How to run a GIF file from the Linux command line (Ubuntu)
Kick ShellScript on the server from Java
Install OpenJDK (Java) on the latest Ubuntu
[Java] Create a jar file with both compressed and uncompressed with the jar command
How to download and run a Jar package directly from the Maven repository with just the command line
Looking back on the basics of Java
Run SystemSpec (RSpec) and Rubocop on CircleCI
Execute Java code stored on the clipboard.
[Java8] Search the directory and get the file
Create an ARM-cpu environment with qemu on mac and run java [Result → Failure]
Run Docker environment Rails MySQL on Heroku. devise and hiding the twitter API
[Java] Understand the difference between List and Set
Install java and android-sdk on Mac using homebrew
Put Java 11 and spring tool suite on mac
[Java beginner] Command line arguments ... I don't know ~
[Java] The confusing part of String and StringBuilder
I compared the characteristics of Java and .NET
Summarize the differences between C # and Java writing
I touched on the new features of Java 15
Run Mecab on Win10 + Eclipse + Java + cmecab-java (January 2020)
[Java] Memo on how to write the source
Upload and download notes in java on S3
Run Dataflow, Java, streaming for the time being
XXE and Java
Write ABNF in Java and pass the email address
[Tutorial] Download Eclipse → Run the application with Java (Pleiades)
Please note the division (division) of java kotlin Int and Int
[Java] Sort the list using streams and lambda expressions
Import the instance and use it on another screen
Run Rubocop and RSpec on CircleCI and deploy to ECS
Deploy Java apps on the IBM Cloud Kubernetes service
Organizing the current state of Java and considering the future
Java language from the perspective of Kotlin and C #
[Android] Display images and characters on the ViewPager tab
Install java and maven using brew on new mac
Run the Android emulator on Docker using Android Emulator Container Scripts
[JAVA] What is the difference between interface and abstract? ?? ??
I couldn't run it after upgrading the Java version