r/learnjava • • May 24 '21

Java Environment and "how it works"

As everyone learning Java I started my first lesson with "you don't care about that weird public static void main(String[] args) bit, we explain later" months after, tutorials, and people never explained whats going on within that method, and going deeper how java actually works.

I banged into this problem and lack of explanation when I was trying to make VSC work as Java Dev Environment. I have so many questions...like what is actually java_home how does that work. How does Maven project differs from basic projects I was making in Netbeans, how is JavaFX part of Java packages but when running project it never compiles correctly.

I'm sure these are very naive questions with layers and layers of knowledge that I should have but never got to learn. Is there a good tutorial series or video playlist (pls dont link basic Java docs) that I could learn these things from?

55 Upvotes

7 comments sorted by

4

u/sparkless12 May 24 '21

thanks for replies, I get that post is tl;dr. But my question wasnt't about deconstruction of public static void main(String[] args). Thank you for that tough, I will think about presenting my question better next time

6

u/GuyWithLag May 24 '21

So, a main method gets called* in the middle of a really large amount of other stuff that is going on. Assuming you just have a System.out.println("Hello World!"); in your main method, a fractal high-level representation of what happens when you run your program is:

  • The OS gets an instruction to execute a Java program (this could be your double-clicking an icon on your desktop, debugging something in IntelliJ, running a CLI command; all these are different methods)

  • The OS starts executing the java program with a bunch of parameters (these are set from one of the above methods). Why this one? Because it ws determined so from the initial point. What does "start executing it" mean? Locating it on disk{1} loading it and any dependencies into RAM and creating the necessary OS-specific structures. Locating it on disk depends on the current PATH (based on some of the above methods), which uses JAVA_HOME (in some of the methods).

  • java will then start to initialize stuff. Memory, heap, stacks, thread, loading the boot class path, setting up System in/out/err, setting up the class path from the command line options or environment variables, locating JARs on disk, loading up the main class.

  • At this point your main method gets interpreted; it writes something to System.out, and that something percolates out to the OS. It might end up in the terminal, in a file, in an IntelliJ window - but your program doesn't care.

  • After main returns, the JVM is shutting down; waiting for and closing threads, freeing resources, and terminating its thread

  • The OS then cleans up any resources that were in an intermediate stage.

Now, note that this is about executing stuff, and some of the questions you have fit into this: JavaFX isn't part of the classpath by default, so unless you add it manually, it's not going to be there. Maven does dependency management, so it will track dependencies, including transitive dependencies, download everything and set up the class path for mvn java:exec to work correctly.

41

u/Cmgeodude May 24 '21

There are other good explanations here, but if you, like me, sometimes get lost in the technical jargon when you're learning, hopefully a demonstration will help.

I'm going to start at the end: what is String[] args? It looks like an array of strings, right? That's exactly what it is. It stores information you pass into the program when you open it for execution. Copy the following code into a text file called Sample.java:

public class Sample {

    public static void main(String[] args) {

        System.out.println("Hello, " + args[0] + "! You are " + 
                            args[1] + " years old.");

    }
}

Now, when you go to run that, open the command line (command prompt or terminal), navigate to the folder containing the Sample file, and type in something like:

javac Sample.java

[Enter/Return]

java Sample John 29

You'll see that the Sample file sends "John" and "29" as arguments to main. They are stored in the args array, which we then called in our print statement.

Incidentally, args as an array name is just a convention. You'll sometimes see argv (short for "argument vector"), especially from people who learned C/C++ first. You can call it whatever you want, though args is the preferred convention.

Ok, now public. Have you done any OOP? I'm going to assume you have. You know how you can set fields to private so that they can't be accessed outside their class?

private String name;

private int age;

etc?

You can do that to methods as well. public in the main method ensures that every part of your program is allowed to access main (necessary to make the program function).

static is a bit trickier. In Java, basically everything is an object. The primitives that exist (int, double, float, boolean) are relatively few and have generics/wrappers that govern their methods (maybe you've seen Integer.parseInt() or Integer.valueOf() before). static basically makes it so that you don't need to treat the contents like an object: there's no need to call Main.[variable].

Finally, void. You see this in functions all the time. It means the same thing here. Do you know any C/C++? The convention in C programming is:

int main() {
    return 0;
}

Notice that main is expected to return an int value (most often 0, signifying that everything ran smoothly without throwing exceptions and crashing).

Java protects you from a lot of the exceptions that C/C++ would otherwise throw (think about forced exception handling when working with IO Streams). Additionally, the JVM has its own exit codes that it may return. As a result, you don't need to return an exit code from main. You don't need a return statement at all, hence void.

Hopefully this helps!

6

u/sweetno May 24 '21

args parameter of the method main is how Java provides command line arguments from the operating system (OS). If you ever started your Java app from command line via java, you can define them there, see the documentation of java for how to do that. Otherwise, there is an option in your IDE run settings.

Unix-based OSes and Windows provide a number of resources to every process:

  • current directory

  • command line arguments

  • environment variables

  • standard input, output and error handles

They are set when the process starts. Each OS has means to set them. For example, for Linux and sh-compatible command interpreter it can look like

MY_VAR=value java MyClass arg1 arg2 arg3 <input.txt >output.txt

Here we assume that files MyClass.class, input.txt and output.txt are located in the current directory. This command line starts Java application with default environment variables and environment variable MY_VAR set to value, command line arguments arg1, arg2 and arg3. Standard input is taken from file input.txt while standard output is written to output.txt. Execution of the application starts in method MyClass.main which should be present in the compiled file MyClass.class.

Java designers decided that they give access to command line arguments via the parameter of the method main. This is in line with the existing tradition in C and C++. Environment variables are available via System.getenv and standard input, output and error handles are associated with System.in, System.out and System.err streams.

In practice not a lot of Java applications are command-line applications, so all of this is not terribly important.

P.S. args name is a tradition, you can name it however you want.

7

u/shaybra May 24 '21

It's the main method that's public, static so it can be accessed without making an object of the class via ClassName.methodName, void meaning it returns nothing, main is just the methods name, and String[] args means the main method takes in a string of arguments when called on like when you put in flags when calling on an exe. Hope that helps.

2

u/knoam May 25 '21

JavaFX used to be part of the official JDK, so you could just assume it was always available, just like how you don't need a library for Math.sqrt. But Oracle wanted to slim down the JDK and spin off and/or open source anything that wasn't a core part of Java. So for newer versions JavaFX is now a library that has to be imported.

2

u/large_crimson_canine May 24 '21

It's where whatever sequence of operations that the program requires for that moment starts. Like...a user clicks some button and it runs one of the many main() methods that exists in the architecture somewhere, interacting with a potentially huge number of classes and other files to achieve some output or result.