In this chapter, we will explore what each keyword in the main method actually means as it relates to object-oriented programming and the scope of the method.
By now, you should have seen the main method dozens of times.
Main.java
class Main{
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Code language: JavaScript (javascript)
Recall that the main method is the entry point to the program. It’s the block of code that gets executed first by the JVM when a Java program runs. All Java programs need a main method in order to function.
Public Keyword
Recall from the last chapter that objects may be declared as private or public. This defines the scope of the variable or a method. There are a few other scopes, but we won’t worry about them yet.
The main method must be public, so its code can be executed from outside the class file. Remember, public means any file can access the code and use its objects or methods. Private means only the functions within the class file itself may use the objects or methods.
When we launch a program, we’re not launching it from within the project itself. We’re launching it from somewhere else. So the method must be public so the JVM can access it.
Static Keyword
The main method itself is part of a larger class file. As we learned in the previous chapter, classes are like blueprints for objects. The class containing the main method is usually named after the app itself or simply called the “Main” class.
Consider the classes created in the previous chapter. They all had constructors. Why doesn’t the Main class have a constructor?
The class file containing the main method behaves a little differently than other classes. We will not instantiate more instances of the “Main” class after the program is running. It wouldn’t make sense for the program to launch additional copies of itself.
This all relates to the static keyword, which was briefly introduced way back in chapter 6. Remember, the static keyword means that a method can be used without having to instantiate an object. We can call static methods from the Main class without having to create new “Main” objects.
Void Keyword
The next keyword in the main method declaration is “void.” Recall that methods may be defined with return types, and send back information to the methods which called them. Void methods are simply methods that do something but return nothing. The main method itself is just executed. It’s not sending information back to somewhere else in the same Java program. Once the JVM’s gone through all the code in the main method (and whatever methods it calls), the program is done executing and it closes. So it must be void.
Note that considerable variances exist between programming languages with regard to the main method. For example, in C++, the main function is of type int and returns an exit status.
main(String[] args)
Of course, the main method must be called the “main” method, or it wouldn’t be the main method. So “main” is officially the method’s identifier.
Since the main method isn’t a constructor, its letters are all lowercase.
That part’s simple enough, but what about (String[] args)
?
Well, we know methods can have arguments (which is what args is short for) that should go between the parenthesis following the method identifier. We know a String refers to a sequence of characters, such as words or sentences, and finally we know that the square brackets [] mean it must be an array.
So when combined, (String[] args)
means we’re receiving an array of Strings as the main method’s arguments. Normally, when we get arguments, we do something with that information. We might print out a calculation or return another value. But until now, we’ve done nothing with the arguments provided by “args”.
Why is this a required standard part of the main method if we never use that information?
First, let’s see what the args array contains. I’ll start by seeing how long it is.
class Main{
public static void main(String[] args) {
System.out.println("The length of the args array is: " + args.length);
}
}
Code language: JavaScript (javascript)
The length of the args array is: 0
Okay… so it’s an empty array. The question that follows is what’s the point of giving us an empty array? Can we just omit this entirely?
public static void main() {
System.out.println("Hello World!");
}
Code language: JavaScript (javascript)
Error: Main method not found in the file, please define the main method as: public static void main(String[] args)
So we cannot just skip the args array, even if we don’t use it.
What’s the Main Method’s args array for?
The args array contains the arguments passed to the program when it is run. Java programs, and any program, really, can be executed from the command line. In Windows, this is Command Prompt or PowerShell, in Mac and Linux it’s called the Terminal. I’m just going to refer to it as the terminal from now on.
When we execute programs from the terminal, we usually pass some information along. For example, if you open the command prompt in Windows and type:
notepad myfile.txt
Then hit enter, the notepad application will attempt to open “myfile.txt” from whatever directory you’re in. If it cannot find “myfile.txt” notepad asks if you want to create it. Here, I passed the argument “myfile.txt” from the command line to the program when I asked for it to be executed.
We can do the same with the main method in Java files. These arguments, anything typed after the program’s name when we’re opening it from the terminal, are passed in to the args array as Strings, where each element in the array is the individual argument, separated by a space.
Main Arguments Example
First, you must understand how to run Java applications from the terminal or command line. I’ll walk you through the basics of doing this in Windows.
To begin, I created the following “main.java” file to test this out with.
class Main{
public static void main(String[] args) {
System.out.println("Hello, world.");
System.out.println("The length of the args array is: " + args.length);
}
}
Code language: JavaScript (javascript)
Save that as “main.java” on your desktop.
Open your terminal. By default, it should place you in your user or home directory. On Windows, this is C:/users/your_username.
To execute a .java file, we first need to tell the terminal where it is. There are two ways to do this. First, we can change the directory the terminal’s looking at to a different directory using the “cd directory_here” command (cd stands for change directory). You can either type the full path of the folder you want to go to, or change the directory relative to your current directory.
My “main.java” file is on my desktop. The “desktop” folder is in my user directory, which is where the terminal starts by default. So to get to the desktop, I can just type “cd desktop” and hit enter.
Alternatively, I could have typed the full path. e.g. “cd C:/users/kevin/desktop”
You can see what files are in the current directory by typing the “dir” command in Windows or the “ls” command in Linux/Mac. “ls” should also work in Windows PowerShell. If your main.java file is in the desktop folder, it should show up in the list, along with any other files/folders on your desktop.
To execute the java program, all I have to do now is type “java main.java” – This tells the computer to use the “java” application and open the “main.java” file. The command will automatically compile and execute the file.
Note that if you get an error, it likely has something to do with your system path variable. Just search the web for “add java to path” to find answers.
This is what my terminal looks like when I run the file I created after typing “java main.java”.
C:\Users\Kevin\Desktop>java main.java Hello, world. The length of the args array is: 0
The args array is 0 in length because I didn’t provide any additional arguments. If I want to add more arguments, I can simply type them after the name of the file I’m running. For example, the command java main.java test one
produces this output:
Hello, world. The length of the args array is: 2
In this scenario, the two arguments I provided were “test” and “one”. So the length of the array is 2.
Finally, let’s do something with the information gained from the arguments. I’ll simply loop through the array with a for each loop and print each argument back out to the screen.
import java.security.DrbgParameters.NextBytes;
class Main {
public static void main(String[] args) {
System.out.println("Contents of args: ");
for (String arg : args) {
System.out.print(arg);
}
}
}
Code language: JavaScript (javascript)
Now I issue the command:
java main.java test one two three
The output is:
Contents of args: testonetwothree
Notice that it printed the words back out to me, in the same order I typed them when I asked Java to run the program using the command. The arguments array does not include the spaces, so they were omitted from the printout. I could have manually added them back in, but I wanted to demonstrate this.
While this may seem rather trivial, as you continue on your quest of being a developer, you’ll likely use command line applications more frequently. Being able to pass programs arguments upon execution is important if you want them to perform specific tasks. They’re simply options or pieces of information the program uses to run. So now you know what the args part of the main method is for and how to use it.
Argument Example: Ipsum Generator
Let’s look at an example of passing a useful argument to the main method of a program that prints out placeholder text.
Lorem Ipsum are the first two latin words in a piece of text commonly used as placeholder text. Originally, this text was used to format print designs – like in newspapers or magazines where editors wanted to preview the general appearance of a piece before the actual content was written. This tradition has extended to the tech world and it’s still commonly used in design previews for user interfaces or websites.
I want to create a simple program that generates the Lorem Ipsum placeholder text. The program will:
- Generate a certain amount of characters of this placeholder text
- Determine the number of characters to generate based on an argument passed to the main method at runtime
How It Functions
I made it so my program contains only the first paragraph of the “IPSUM” text. There are many more paragraphs, but for this lesson I’m just using the first.
static final String IPSUM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
Code language: JavaScript (javascript)
When the program runs, if it doesn’t receive any arguments, it just prints out the first 100 characters of the string. This is easily achieved using the String.substring method.
Placeholder Text Generator Generating 100 characters of placeholder text. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore
However, if I provide the –chars argument when I run it from the console, followed by a number, it will print out that amount of characters.
java Ipsum --chars 50 Placeholder Text Generator Generating 50 characters of placeholder text. Lorem ipsum dolor sit amet, consectetur adipiscing
If I enter a number larger than the length of the paragraph, it just repeats the same paragraph until we reach the set amount.
Using what you know about Strings, the main method, and loops, can you figure out how I did that? I’d encourage you to give it a go before reading the full explanation below!
The Code
class Ipsum{
static final String IPSUM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
public static void main(String[] args){
// say hi
System.out.println("Placeholder Text Generator");
//set initial # of chars to generate
int numCharsToGenerate = 100;
//loop through args
for (int i = 0; i < args.length; i++){
//look for a --chars arg
if (args[i].equals("--chars")){
//make sure theres something after it
if (i+1 < args.length){
//set numCharsToGenerate to the next # following --chars
numCharsToGenerate = Integer.parseInt(args[i+1]);
}
}
}
System.out.println("Generating " + numCharsToGenerate + " characters of placeholder text.");
generateChars(numCharsToGenerate);
}
public static void generateChars(int amount){
int lengthOfIpsum = IPSUM.length();
//check if amount is < length of IPSUM
if (amount < lengthOfIpsum){
//print out the first amount characters of IPSUM
System.out.println(IPSUM.substring(0, amount));
} else {
// figure out how many times IPSUM can fit into amount
int timesToRepeat = amount / lengthOfIpsum;
// figure out how many characters are left over
int remainder = amount % lengthOfIpsum;
// print out IPSUM timesToRepeat times
for (int i = 0; i < timesToRepeat; i++){
System.out.print(IPSUM);
}
// print out the first remainder characters of IPSUM
System.out.print(IPSUM.substring(0, remainder));
}
}
}
Code language: PHP (php)
I began by declaring a constant IPSUM at the class level, holding the text I want to use. If I was developing this to be more production ready, I probably would have stored the text in an external text file and read it with a file reader. But for demonstration, this suffices.
Next, I set a default length of 100. This is what will be used if no value is found or provided.
I then looped through the arguments array and checked if any of the arguments equal the text “–chars” exactly. If I find this, I check if another argument exists after it. If so, I use the parseInt method to turn the string argument into an int I can work with. This information is then passed along to the generateChars method, which handles the actual printing.
If the length of characters being printed is less than the total length of the IPSUM constant (line 33), it just prints out the substring up to the correct amount of chars.
If it’s longer than IPSUM, we need to repeat it. So it determines the number of repeats to make, the remainder, and uses a simple loop to print it out on repeat.
Now, I can run the program using the java command and a –chars argument. It prints out the specified amount of characters.