I'm trying to print "Hello World" from a Java program, but I am a little confused with the main method:
public static void main(String[] args)
and
public static void main(String args[])
Both these functions perform the same task. How does this happen?
I know the function of String but not of the args.
In Java:
String args[]
is exactly equivalent to:
String[] args
You are defining a method named "main" which is public (anyone can call it), static (it's a class method, not an instance method), and returns void (does not return anything), and takes a parameter named args that is a String array.
In Java you can declare a String array as:
String[] args
or
String args[]
You can define an array in Java in two equivalent manners (as you written):
String[] args
String args[]
So it doesn't really matters. The first way is a bit more common, though.
In java your array declaration can be after the type or the name of the variable, so it is ok both methods to perform the same functionality.
args are used to store command line arguments.
Like
java YourClass arg1 arg2
arg1 and arg2 will be stored in args array at indexes args[0] and arg[1].
The args variable is for inputs to your program. See tutorial on command-line arguments.
Im gonna try to explain all the parts of this line
public static void main(String[] args)
main: its a Java convention inherited from C.. the first method to run its the one called main.
void: this method should return nothing, which in java its called void
static: you don't need to create an instance of this class to run this method(completely logic if is the first one to run)
public: it is possible to call this method from other classes, even outside of the package(again its logic been the firsts method to be called)
Now to your question String[] args is completely equivalent to String args[] or to String[] name... anyway, it means that args(or name in the last case) its the name of the array of Strings that the method is receiving. Its an array because of the symbols [] and in java is valid to put the symbols in front of the type(String for this case) or in front of the name of the variable(args).
If you run your program from a terminal with a command like "java myprogram argument1 argument2" inside the method main the value of args will be args = ["argument1", "argument2"]
There is exactly no difference between the two, though according to the Java standards, the convention for making an array is:
String[] args
rather than,
String args[]
and equally valid form using the ellipses as well (only for infinite array):
String...args
A brief overview of the psvm() in Java:
public: the method can be accessed anywhere within the class or outside the class or even outside the package.
static: the method is shared by all the objects and it does not need any objects to be created to call this method.
void: this particular main() method cannot return any value so here we have to use void; it is the syntax which need to be followed.
main(): this is the entry point of the code or the class you execute. In most cases, this is also the exit point of the code.
String[]args: these are run-time commands line arguments, whether you pass them or not you have to mention them in the arguments.
Related
This question already has answers here:
What is the "String args[]" parameter in the main method?
(18 answers)
Closed 5 years ago.
In java main method, what's the purpose of String args[] in
public static void main (String args[]) ?
The main method has only one because it's a form for standardisation. Oracle does not know how many arguments a programmer will need and what types of them. For this reason, with the args[] of type String you can pass N arguments to your program. You can then parse it to any primitive type in Java.
Here is an example of passing arguments to an application with Java:
java MyApp arg1 arg2 arg3 arg4 ... argN
Every value passed is separated by spaces and based in the position, you can retrieve and manipulate them, for example, if you need the arg at position 4 and convert it to a double, you can do this:
String toDouble = args[4];
double numericalValue = Double.parseDouble(toDouble);
Also, this form was thought to pass some parameters to define and configure some behaviour of your application, so with an unique array this can be accomplished.
args[] is an String array. So you can pass more than one String to your method:
args[0] = "Hello";
args[1] = "World";
...
When you run your program from the command line or specify program arguments in your IDE, those arguments are split by spaces ("hello world" becomes "hello" and "world", for example) and given to your program in the first argument. Even if the other array existed, there would be no use for it.
You are questioning why Java (and at the same time C/C++) Main threads have only two arguments. Java class has a requirement to use the main method defined in the main class. You would see an error otherwise:
"The program compiled successfully, but main class was not found.
Main class should contain method: public static void main (String[] args)."
This is just a Java requirement you need to adhere to (under silent protest if you wish).
As opposed to that, in C/C++/C++11 you need to have an int main method, but need not have any arugment. i.e. the following is allowed by the C++ main class requirement:
#include <iostream>
int main(void) { return 0; }
Note that in C/C++, you can also pass an integer as argument in the main.
#include <iostream>
int main(int argc){ return 0;}
To summarise, C/C++/Java each have got their own standards which you have to adhere to. You can argue that something isn't right, but as long as you are one of those people who are in the standards committe, I don't think you can change anything much.
A question regarding C main has been answered here. Also, the necessity of the main method with String[] args has probably been explained here already.
Object is the super type of all classes in Java. Consider my following class
public class Test {
public static void main1(Object[] args) {
System.out.println("I accept an object array");
}
public static void main(String[] args) {
main1(args);
}
}
Due to object superiority object array can accept any object type arrays. But Still java doesn't consider following class contains a main method.
public class Test {
public static void main(Object[] args) {
}
}
Why java never give this opportunity while object is ultimate supper type for all classes in java.
because java looks explicitly for public static void main(String[] args) when running.
specified in 12.1.4 of the jls
The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:
Object wouldn't make sense, because you can not pass an other object through the console.
The main Method of Java is specified with strings as parameters. So the compiler can't detect the main-method with objects as args. I guess the resaon for this is, that the main method are usally called due an console command, and there you have only the opportunity to set strings as parameters.
The String[] were for command-line arguments, strings are what the user enters at the command line. Objects can't be entered from Command line.
From JLS:
The method main must be declared public, static, and void. It must
specify a formal parameter whose declared type is array of String.
Therefore, either of the following declarations is acceptable:
public static void main(String[] args)
public static void main(String... args)
there are a few ways to answer this
"because". the main() entry point to a program is specified like this and canot be overloaded to accept other arguments
as hinted by assylias, the main() method is expected to be invoked from a comamnd line or shell. this means that the arguements will always be strings. whatever you type on a command line is a string.
One point as all explain there is no way to pass object from console so it's meaningless.
Still as I also think Object is super class so why jvm does not understand it, but there is also other point that if jvm allowed to accept Object arguments than user can pass non-string variable as well so there jvm will create error that's why I think jvm make restrict to pass string variable.
JVM calls main() as a thread. When we call main() from another method in java, we call it as function or method.
Actually the confusion here is " why auto casting is not applicable when we try to call main(Object args) from console."
May be this restriction has been put in native methods of JVM to avoid the complications.
I you guys observe same case u will find for
catch(Object e)
Summery line: it is the native methods code of JVM which restricts the auto casting, to avoid complications.
The arguments passed to the main method are from command line. So they are String
main method can also be written like this
public static void main(String... args) {
}
I'm the product of some broken teaching and I need some help. I know that there is this thing called the "main method" in Java and I'm sure other programming languages. I know that you need one to make your code run, but how do you use it to make your run? What does it do and what do you need to have it put in it to make your code run?
I know it should look something like this.
But almost nothing more.
static void main(String[] args){
}
Breaking this down, point-by-point, for the general case:
All Java applications begin processing with a main() method;
Each statement in the main executes in order until the end of main is reached -- this is when your program terminates;
What does static mean? static means that you don't have to instantiate a class to call the method;
String[] args is an array of String objects. If you were to run your program on the command line, you could pass in parameters as arguments. These parameters can then be accessed as you would access elements in an array: args[0]...args[n];
public means that the method can be called by any object.
its the entry point for any java program, it does whatever you tell it to do. all you need to do is declare it in one of your source java files and the compiler will find it.
Firstly it should be public static void main(String[] args){...}.
It must be public
Take a look at The main method
The JVM will look for this method signature when it runs you class...
java helloWorld.HelloWorld
It represents the entry point for your application. You should put all the required initialization code here that is required to get your application running.
The following is a simple example (which can be executed with the command from above)
package helloWorld;
public class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
Summary
void means the method returns no value. String[] args represents a string of arguments in an Array type that are passed to the program. main is the single point of entry in to most Java programs.
Extended
Glossing over why it should be public static void... (You wouldn't build a door without a doorknob), methods (equivalent of functions (or subs) in other languages) in Java have a return type. It just so happens that the main method in Java has to return void. In C or C++, the main method can return an int and usually this indicates the code status of the finished program. An int value of 0 is the standard for a successful completion.
To get the same effect in Java, we use System.exit(intValue)
String[] args is a string array of arguments, passed to the main function, usually for specific application use. Usually these are used to modify a default behavior or for flags used in short command line executable applications.
main just means to the JVM, start here! Same name in C and C++ (and probably more).
when you execute your class, anything in the main method runs.
You should have a main class and a main method. And if you want to find something in the console, you need have one output command at least in the method, like :
System.out.println("Hello World!");
This makes the code running lively.
I am trying to learn Java now and this is the hello world program and it already have started to baffle me. I am used to python and I found this tutorial (ebook) simple and concise for programmers who have python background.
Hello world program in Java from the book:
public class Hello {
public static void main (String[] args) {
System.out.println("Hello World!");
}
}
As the book says, the equivalent code for this in python is:
class Hello(object):
#staticmethod
def main(args):
print "Hello World!"
I completely understand the python code. However, I have a problem with Java code and I want to be clear before I proceed further so that I get the root knowledge of language in my brain.
The book says (as copied from book):
...we have one parameter. The name of the parameter is args however,
because everything in Java must have a type we also have to tell the
compiler that the value of args is an array of strings. For the moment
You can just think of an array as being the same thing as a list in
Python. The practical benefitt of declaring that the method main must
accept one parameter and the parameter must be a an array of strings
is that if you call main somewhere else in your code and and pass it
an array of integers or even a single string, the compiler will flag
it as an error.
This does not make any sense to me. Why can I not pass anything since my function doesn't require anything? What happens if I just pass (String args).
Since I am completely newbie to Java, please bear with me.
Well, you are passing in something. Whenever you run a java program, command line arguments are passed in as the args argument, so you need to accept those, even if you don't use them.
Well, there are two things going on here. First, is function signatures - since you declare main to expect and accept only an array of strings, it'll raise an error if you try to pass it something else. But not because the function refuses to accept it, but because the compiler won't know what you're trying to call. See, you can have multiple functions with the same name, but different arguments. So if you were trying to call main(1), the compiler would look for a function main that accepts one (or more) integers, not find it, and raise an exception.
The other thing going on here is that when you start a program, the compiler looks for this particular signature - public static void main (String[] args) and nothing else. Can't find it? The program won't run.
As you know, Python uses "duck typing": it doesn't matter what type something is, only what it can do. As a result, you never need to declare types for your variables.
In Java, that's not true: every variable has a declared type, and the compiler enforces that type. Trying to store, for example, a String reference in an int-declared variable will produce a compile-time error. Proponents of duck typing claim that this decreases flexibility, but strong-typing enthusiasts point out that compile-time errors are easier to fix than run-time bugs.
But the same is true of your method arguments. Since your method requires an argument of type String[], it must be provided an argument of type String[]. Nothing else will do.
Fortunately, since it's the main method, the Java interpreter takes care of passing in an argument: specifically, an array of the command-line args with which your program was executed. If you'd like to ignore it, feel free. Your program will run just fine without paying attention to the argument, but it's invalid if one isn't passed in.
(By the way, if this were any method but the main method, you'd be free to declare it with whatever argument types you'd like, including no arguments at all. But since the Java interpreter will be passing in an array of the command line arguments, this particular method must be prepared to accept them.)
In Java, there is no top-level code as in Python (i.e. there is no direct equivalent to just
print('Hello world')
). Nevertheless, a Java program needs some kind of entry point so that it can start executing code. Like many other languages (i.e. C/C++, C#, Haskell), a function with the name main serves for this purpose and is called by the runtime (i.e. Java interpreter).
When calling the main function, the runtime uses a certain number (and types) of arguments. The function must match these. You're free to then call other methods with any signature you like:
public class Hello {
public static void hi() {
System.out.println("Hello World!");
}
public static void main (String[] args) {
hi();
}
}
Every program has an entry point/starting point from where its execution would start. Java searches for a specific method signature it will start from in a class to run your application which is the 'main' method.
public static void main(String args[]);
This must be implemented in order for you to start your program ( in a class you want to start off from). And because of this rule/restriction we must pass array of strings ( which are similar to list of strings in Python) as arguments.
Now for the second part, if your program does not require any parameters at startup, dont pass any. You will get args as an empty String array in main method. The following line would print out the length of arguments passed to your main method.
System.out.println("Length of arguments = " + args.length);
You might also want to look at Sun's Java guide for starters.
I hope this answers your question.
If your function does not require anything (so it has no parameters) then you are allowed to avoid passing anything, this is done by declaring it as
void noArgumentsFunction() {
// body
}
But the main function, that is a boiler plate, must accept an array of Strings. That's why you are forced to declare the signature to accept it (and then ignore it in case). The funcion must accept this parameter because it's the entry point for your program and any Java program must support a array of parameters that is passed with command line (exactly as every C/C++ program, also if you are not forced to do it).
First of all, note that the main method is called by the JVM to start the program and passed the command line arguments. It can be called by Java code, but this is very rarely done.
Anyway, this is the signature of the method:
public static void main (String[] args)
It says that it requires a parameter that is an array of Strings. If you call it like this:
main(new String[1]);
or this:
main(methodThatReturnsAStringArray());
it will work. But these will cause a compiler error:
main(new int[0]);
main("test");
Because the type of the parameter in the call does not match the type the method signature requires. You can pass a null pointer:
main(null);
Because arrays are a reference type, and null is a valid value for all reference types. But then the method will have to test for that case, otherwise it will throw a NullPointerException when it tries to access the array.
Another thing you can do is overloading, by declaring another method:
public static void main (String args)
So when you call
main("test");
the compiler would determine that there is a method with a matching signature and call that.
Basically, the point of all this is that many programmer errors are caught by the compiler rather than at runtime (where they may only be discovered in some special circumstances if it's a rarely executed code path).
When you execute your programme from command line, Commandline parameter can be more than one string.
eg.
Java myprogramme param1 param2 param3
all this parameters - param1, param2, param3 are passed as string[].
This is common for all program, who pass zero, one or more params.
As a programmer your responsibility to check those command line params.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does “String[] args” contain in java?
I want to know the significance of the term written inside the bracket in definition of main function in java i.e.string[] args. What does it mean in public static void main(string[] args)? Is it always necessary to write it?
More over how many engines mysql server has and what is the default engine?
Public -> makes member accessible outside the class
static -> allows main( ) to be called without having to instantiate a particular instance of the class
void -> main() doesnt return value
main(0 -> it is the method called when a Java application begins
string[] args -> Its parameters. String args[ ] declares a parameter named args, which is an array of instances of the class String. In this case, args receives any command-line arguments present when the program is executed.
public class MainClass{
public static void main(String[] args){}
}
When we run in the command line
java MainClass
The JVM here tries to find a method main, We are basically accessing the method main outside the class and package so the method is Public.
We are running this program by referring the class name and we are not creating any object,so to access the method without creating an instance it has to be static. JVM does not handle the output of the method and hence the return type is void.
We can pass series of arguments through command line and String can enclose all the primitive type in Java and we do not know the number of arguments that can be passed so it declared with String array.
For MySQL engine types please refer the link Engines
The Java contruct for main() is the equivalent of C's "void main(int argc, char **argv)". Java's main() receives an array of strings, from which one can obtain the length with args.length; no need for argc, the count. It can also be written "String args[]"; both ways specify an array of strings.
The mysql question rightly belongs in another SO question altogether.
As written , string shows that args variable is of type String and [] shows args is an array.
Inside main() is because, Main() is called whenever program is executed, So this args will hold everything you give it at run time i.e. at the call of main()