I'm new to Java and had some very basic questions:
Why must the main method always take in a String[]? --> public static void main(String[] args)
With regards to primitives, what is the difference between a float and a double?
I'm new to Java and had some very basic questions:
Why must the main method always take in a String[]? --> public static void main(String[] args)
With regards to primitives, what is the difference between a float and a double?
The main method takes String[] as a parameter because it holds the program's command-line arguments.
$ javac Args.java
$ java Args hello goodbye
hello
goodbye
public class Args {
public static void main(String[] args) {
for (String s : args) {
System.out.println(s);
}
}
}
For difference between float and double, http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Why must the main method always take in a String[]? --> public static void main(String[] args)
When you run a Java program from the command line (terminal), the syntax is
java SomeClass [list of arguments, space-separated]
This means that you can invoke your program with different options. The args variable contains the command-line arguments. If you don't care about them (which often you won't), just don't use the variable.
Here are some things you could do with the argument(s):
If you wanted to use the arguments, you could do so as follows.
public static void main(String[] args) {
String first, last;
if (args.length >= 2) {
// The user provided a first and last name.
first = args[0];
last = args[1];
} else {
// [ prompt user for name ]
}
}
With regards to primitives, what is the difference between a float and a double?
A double has twice (double) the precision of a float. Consequently, it also takes up twice as much memory.