Reputation: 301
My scenario:
I have a Main.java file that simply does System.out.println("Hello")
.
I run it by first, compiling with javac Main.java
and then excecuting the command java Main
.
Now what I want is that instead of printing "Hello", it will print whatever the user wants, but I don't want to change the source code whenever I want a different output. So I replaced the System.out.println("Hello")
with System.out.println(${MESSAGE})
. But this gives error "Cannot resolve symbol MESSAGE".
Ultimately, I want a Main.class file and run with something like java Main -env MESSAGE=whateverIPutHere
and it should print out whateverIPutHere.
Is it possible?
Upvotes: 1
Views: 2620
Reputation: 4553
You can either read it from args as mentioned above, or, if you know how to add a library to your project, try args4j. You'll get way cleaner code as you can use it to separate commandline argument processing to a dedicated class.
Upvotes: 1
Reputation: 11
In this example, we are printing all the arguments passed from the command-line. For this purpose, we have traversed the array using for loop. The arguments passed in command line is captured by args argument.
class test{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac test.java
run by > java test sonoo jaiswal 1 3 abc
Output:
sonoo
jaiswal
1
3
abc
Upvotes: 1
Reputation: 3632
You can use system properties
public final class Test {
public static void main(String[] args) {
System.out.println(System.getProperty("port") + " port");
}
}
And then compile and run
javac Test.java
java -Dport=8080 Test
Output is : 8080 port
Upvotes: 3
Reputation: 140631
Now what I want is that instead of printing "Hello", it will print whatever the user wants, but I don't want to change the source code.
Simply not possible without changing code.
System.out.println("Hello")
Prints that string. End of story. And:
System.out.println(${MESSAGE})
is simply not valid Java. If you want to read an environment variable, see here how to do that.
But then: that is really a detour here. You can simply pass arguments on the command line:
java Main "some string" "and another one"
and then retrieve those two strings via the String args[]
parameter that your main method receives!
The real answer here: you learn a new language by researching how that language works. You don't assume how syntax might look like, based on experiences from other languages. Meaning: $ENV_VAR
is a "shell language" concept. Your idea: "maybe Java has the same" is a very inefficient strategy to go about this.
Upvotes: 2
Reputation: 1637
You can use the input arguments:
public static void main(String[] args) {
System.out.println(args[0]);
}
And then call it like this: java Main whateverIPutHere
Simple as that! args
is an array containing all the arguments that you pass in the command line.
Upvotes: 1