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

View all comments

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.