The main method has a mechanism to accept input when run from the terminal.
Run from terminal
Let’s say I have this class
public class Main {
public static void main(String[] args) {
System.out.println("hello, world!");
}
}
This code is saved in Main.java
file under my desktop. In order to run it from the terminal, I will need to navigate with my terminal to my desktop and execute these commands:
javac Main.java
— to compile the source code into java byte code.
java Main
— to run without any arguments.
Run from the terminal with arguments
public class Main {
public static void main(String[] args) {
String name = args[0];
System.out.println("hello, " + name);
}
}
Now, I have a little different code. The main method has String[] argument. Basically, when running the code from the terminal we can pass data for this argument.
java Main John
— run with one argument. The above code will print hello, John
. After the name of the class name, we can list arguments separated by a space. Each argument will be assigned to a string array.
Let’s see another example
public class Main {
public static void main(String[] args) {
System.out.println("1. " + args[0]);
System.out.println("2. " + args[1]);
System.out.println("3. " + args[2]);
System.out.println("4. " + args[3]);
}
}
If we want to combine two separate words as one argument, we can use double quotes.
Please take my Java Course for video lectures.This article is part of the series of articles to learn Java programming language from Tech Lead Academy:Introduction to programming
OS, File, and File System
Working with terminal
Welcome to Java Programming Language
Variables and Primitives in Java
Convert String to numeric data type
Input from the terminal in Java
Methods with Java
Java Math Operators and special operators
Conditional branching in Java
Switch statement in Java
Ternary operator in Java
Enum in Java
String class and its methods in Java
Loops in Java
Access modifiers in Java
Static keyword in Java
The final keyword in Java
Class and Object in Java
Object-Oriented Programming in Java
OOP: Encapsulation in Java
OOP: Inheritance in Java
OOP: Abstraction in Java
OOP: Polymorphism in Java
The method Overriding vs Overloading in Java
Array in Java
Data Structures with Java
Collection framework in Java
ArrayList in Java
Set in Java
Map in Java
Date and Time in Java
Exception in Java
How to work with files in Java
Design Patterns
Generics in Java
Multithreading in java
Annotations in Java
Reflection in Java
Reflection & Annotations - The Powerful Combination
Run terminal commands from Java
Lambda in Java
Unit Testing in Java
Big O Notation for coding interviews
Top Java coding interview questions for SDET