Main method in java only accept String[] - java

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) {
}

Related

Static Error: This class does not have a static void main method accepting String[]. Java do not know why [duplicate]

I am not sure what this means, whenever before you write a code, people say this
public static void main(String[] args) {
What does that mean?
Here is a little bit detailed explanation on why main method is declared as
public static void main(String[] args)
Main method is the entry point of a Java program for the Java Virtual Machine(JVM). Let's say we have a class called Sample
class Sample {
static void fun()
{
System.out.println("Hello");
}
}
class Test {
public static void main(String[] args)
{
Sample.fun();
}
}
This program will be executed after compilation as java Test. The java command will start the JVM and it will load our Test.java class into the memory. As main is the entry point for our program, JVM will search for main method which is declared as public, static and void.
Why main must be declared public?
main() must be declared public because as we know it is invoked by JVM whenever the program execution starts and JVM does not belong to our program package.
In order to access main outside the package we have to declare it as public. If we declare it as anything other than public it shows a Run time Error but not Compilation time error.
Why main must be declared static?
main() must be declared as static because JVM does not know how to create an object of a class, so it needs a standard way to access the main method which is possible by declaring main() as static.
If a method is declared as static then we can call that method outside the class without creating an object using the syntax ClassName.methodName();.
So in this way JVM can call our main method as <ClassName>.<Main-Method>
Why main must be declared void?
main() must be declared void because JVM is not expecting any value from main(). So,it must be declared as void.
If other return type is provided,the it is a RunTimeError i.e., NoSuchMethodFoundError.
Why main must have String Array Arguments?
main() must have String arguments as arrays because JVM calls main method by passing command line argument. As they are stored in string array object it is passed as an argument to main().
According to the Java language specification, a Java program's execution starts from main() method. A main() method should follow the specific syntax, it can be explained as:
public static void main(String[] args)
public - Access specifier, shows that main() is accessible to all other classes.
void - return type, main() returns nothing.
String args[] - arguments to the main() method, which should an array of type string.
static - Access modifier. A main method should always be static, because the `main()' method can be called without creating an instance of the class.
Let us assume, we are executing a Helloworld java program.
While executing the program, we use the command
java Helloworld.
Internally, this command is converted into
Helloworld.main()
By making main() method static, JVM calls the main() method without creating an object first.
In Java your main method must always be:
public static void main(String args[])
The program execution starts with main() function, hence the main() function.
It must be public so that it is accessible to the outside environment.
The main() method is always static because, as you know that the program execution starts at main() method and there is no instance of the class containing main() method is initiated. Hence as the static method can run without need of any instance it is declared of static.
Java is platform independent, hence you may try to compile the java file on one system and try to execute the class file on another. Each machines' bit architecture may be different hence the return type of the main function must always be main().
Hope this helps.
Public = This method is visible to all other classes.
static = This method doesn't need an instance to be ran.
void = This method doesn't return anything.
main() = Main method (First method to run).
String[] = Array of strings.
args = Array name.
public --> Access specifier. Any other class can access this method.
static --> The method is bound to the class, not to an instance of the class.
void --> Return type. The method doesn't return anything.
main(String[] args) --> method name is main(). It takes an array of String's as argument. The String[] args are command line arguments.
Note: The main() method defined above is the entry point of a program, if you change the signature, then your program might not run.
Please go through this video link ->
https://youtu.be/ggsRGcA8hnQVery for a clear and to the point explanation of public static void main(String args[]) method.

Why the need to call static voids from other static voids?

I have a Computer Programming-K course at my high school, and we use Java as our language. I noticed that you seem to NEED to have the public *static* void main(String[] args) at the beginning of every script. Our main structure is this:
public class
( void main()
void input()
void process()
void output() )
And we have to make all void methods static, to be able to call one another, because we can't use a non-static main. Why? What does static mean in Java?
First and foremost, main being declared as public static void is mandated by the Java Language Specification:
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.
That's simply the way it is; without it, Java will not execute your script due to there being a lack of a main method.
It also doesn't matter where you put it - it could be in the middle of that class, at the top, at the bottom, or in a completely different file - so long as your program has a main method for it to actually run.
As for the meaning of static - well, that depends on the context.
If you're using static on a field (that is, a variable contained in a class), then there will only ever be one instance of that field.
If you're using static on a method (like main, or another method), then that is a class method, and does not require an instance of the object for it to be invoked and used. These particular methods shouldn't rely on the internal state of the class in which they're being invoked.
As an example, you'll get into a discussion about Integer.parseInt sometime later; this is a static method, which is tied to Integer, which doesn't require an instance of an Integer to invoke.
Next, don't think that the declaration of static methods is going to be commonplace for your code. To be frank, that represents purely procedural programming (that is, defining methods to do these specific things with no regard to state, instead of an object-oriented design that may or may not take into account state).
The only time you're ever forced to declare something to be static is if you're using it within a static context yourself. Since you don't create an instance of your class (through the new keyword), you won't be able to use any of the methods you've declared in it.
This will not compile, as main doesn't have a way to reference that method.
public class Foo {
public static void main(String[] args) {
invokeBar();
}
public void invokeBar() {
System.out.println("Yay, bar!");
}
}
The below will compile, since main does have a way to directly invoke that method:
public class Foo {
public static void main(String[] args) {
invokeBar();
}
public static void invokeBar() {
System.out.println("Yay, bar!");
}
}
Static means that you do not need to have an instance of a class in order to call that method.
static void main is just the specific function that Java requires, so that it knows where to begin running your code. Every program must contain one, and exactly one, static void main.
I noticed that you seem to NEED to have the 'public static void main(String[] args)' at the beginning of every script.
The reason for this is that when JVM runs your program it needs to be able to run it without creating an instance of your entry class containing main method. Sometimes your class containing main method may have constructors which needs arguments to create an instance of it then how would JVM know what values does it have to pass to create an instance of it on its own, which is why java forces you to make main as static method so that JVM doesnot need to worry about creating an instance of your main class to call the main method which is the entry point to your application.
And we have to make all voids static
This is an incorrect assumption. You need not make your void methods as static. There are 2 ways of calling your methods either through object of the class (these methods are called instance methods) or through the class variable(name) (these methods are called static methods). If you donot want to make your methods static then you need to create an instance of you class ad call your methods.
What does static mean in Java?
static is a modifier in Java . You can either use it for your instance variables or for methods or for inner classes. This keyword makes the resource(instance variables/methods/innerclass) a property of the underlying class and hence is shared across all the instances(objects) of the class.

How does the main method work?

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.

Hello world in Java: Understanding the concept versus in python

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.

Java Array Declaration Bracket Placement

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.

Categories