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.
Related
What makes public static void main(String args[]) {} be the convention to test code instead of simply static {}?
class Test {
public static void main(String args[]) {
System.out.println("testing");
}
}
It seemingly has the same capabilities, you can instantiate owner class, use its methods, another classes, even send output as well:
class Test {
static {
System.out.println("testing");
}
}
Is there a standard reason to not use the small static {} to run your average test? Can I take it just as my choice/preference safely?
In other words, I'd like to find a case where you put a code in one that you couldn't (or shouldn't) put in another, that it wouldn't run or give unexpected result, etc.
I'd say the most prominent reason not to use static {} for such things is that you have little control over when it runs. static {} blocks run "when the class is initialized", which means at least four (watch out for the Spanish inquisition) detrimental things for this purpose:
It does not necessarily happen just because the class is loaded.
It does, on the other hand, happen just because you want an instance of the class or reference a static field from some other class, which is the main reason why you don't really want to put code with wide-ranging side-effects in static {} blocks.
It is also not guaranteed to not happen for such simple reasons as the Jar file being on your classpath. JVMs are free to run static {} blocks whenever they feel like it, as long as it is before any static references from the class from other code is made. "Before" could mean "at VM startup".
No VM implementation has any invocation arguments to run such code for you on request.
The purpose of static {} blocks is to initialize static class data (in possibly quite complex ways, of course), and from the preceding points you may be able to see why it's not particularly useful for anything else.
In java every application requires a main method which will be the entry point of the application. The main method required has the signature as follows:
public static void main(String[] args)
The difference between this method and the other one you suggested (besides the fact that your application needs a main method with this signature as an entry point) is that this is a method and takes the "String[] args" parameter. This parameter is where your arguments would go when running a program from the console.
Every java application can be run from the console and therefore it makes sense for every application to have a standard entry point method which will be able to take any special arguments.
Your static {} block is not necessarily a method or a function that can be called and therefore it can not be used as a entry point into your application. It takes no parameters and you have no control over when its code block will be run.
I do not want to change the public static void ... String[] args part of the signature, but is it possible to "rename" this function (eg. just for fun)?
So the entry point for execution would be a function with another name.
Rename it to, like, boot (what would better reflect, if not being historical, the actual use for it in my particular case).
related
I'm interested in doing something different, but these questions are still interesting:
public static void main(String arg[ ] ) in java is it fixed?
Why the name main for function main()
No. The Java Language Specification says:
A Java virtual machine starts execution by invoking the method main of some specified class, passing it a single argument, which is an array of strings.
The JVM Specification says the same thing:
The Java virtual machine then links the initial class, initializes it, and invokes the public class method void main(String[]).
Simple Answer No, Reason, Specification is like that, JVM will only look for main and not any custom name as the starting point. It has to be called main with the exact signature public static void main(String[] args)
Logically also it makes sense how will JVM know that instead of main method, it has to look for boot or something else unless java command had an option to pass the start method.
But that is asking just too much for no good reason.
Secondly since its standardized it helps the developer community too, whoever looks at the code know how to run a given Java Standalone program, or say if you have got a project, your first point will always be look for the main method, and from there you move on.
At start JVM is looking from method public static void main with array of Strings as argument. So only thing you can do is rename argument args. If you want method like boot nobody stops you from doing something like this (personally I don't recommend that "pattern")
static void boot(String[] arguments){
//your logic
}
public static void main(String[] args) {
boot(args);
}
No. You can not do that according to Java Language Specification. But if you want, as Java is a open source project, so download the complete source code of Java language and change it accordingly ( I mean change the source code of JVM itself). This is the only way you can do that.
So now you can understand, why I said it is impossible.
Your application starts running from public static void main(String[] args). It's like the point where JVM looks at to start the proceedings. If you change it, JVM will feel free to not start your application.
If you want to want to have boot() as the starting point of your application - call it in main().
Simple answer is NO . When you start executing program it looks for public static void main(String[] args) which takes String array argument.From this entry point main thread get started.
Yes,We can change the name of the main method if we can change the configurations of the JVM and let it look for a method with another name instead of main method.
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.
I'm rather confused by the concept of making a class with methods, and having a main method with methods underneath.
What exactly are the differences here? How it one way better than the other way? What situations call for a method under the main rather than a class?
It would help me to understand a project - a basic Craps game which will contain a Shooter class, Die class, and a Craps class (which apparently contains the main).
You do not have "main" methods. All methods are a class method, the only difference is that 'static' methods (v.g., main) do not need that you instantiate a new object (via the 'new' statement) to use them.
In other words:
public class MyClass {
public static void myStaticMethod() {
}
public void myInstanceMethod() {
}
}
You can do
MyClass.myStaticMethod()
but in order to use myInstanceMethod you must create an object
(new MyClass).myInstanceMethod;
Usually you do the last thing as
MyClass myObject = new MyClass();
myObject.myInstanceMethod();
Note that you can also do
myObject.myStaticMethod();
but it is exactly the same than doing
myClass.myStaticMethod();
and the first way is considered poor style and usually causes a compiler warning.
#Miranda because with only static methods you lose all of the Object Oriented part, and you just end using Java as you would use plain C.
In the object, you have both the state and the methods. In the class you store both the object state and the methods. For instance, typically you can create a "Card" class, create a card "new Card('K', "Leaf")" and have methods to manipulate it ("uncoverCard()").
Once you have the reference to the object that you want, you use its methods and you know that you are only affecting this object, and that you are using the right version of the method (because you are using the method defined for this very class).
Switching to OO programming from procedural programming may seem difficult at the beginning. Keep trying, looking at tutorial code and asking for advice when needed and you'll soon get to understand it.
Basically it's a matter of separation. You create classes for reusability. If everything was in the main class then your code would not be maintainable. The main class is used as a starting point for your application. If you did everything in the main class you wouldn't be able to take advantage of all that object oriented programming affords you. You'll learn more about it as you get into the course. But basically each of the classes you will create will have single responsibility. Even the main class, whose responsibility is to run the program.
Good luck with your class by the way. Maybe it will give you an advantage in the casinos.
The entrance-point for a Java-Application is it's main-method:
public static void main(String[] args){
// Do stuff here
}
This method differs from others in the way that it's:
The entrance-point of your application, so it will be the first
called method and basic initialization things should be done here.
It's a static-method which makes it accessible without creating an
instance of the class holding it.
This static-thing is best illustrated as follows:
public class Test{
public int addOne(int number){
return number++;
}
public static int drawOne(int number){
return number--;
}
}
// Create our Int:
int value = 12;
// This will work because the method
// is a static one:
System.out.println( Test.drawOne(value) ); // Outputs 11
// This won't work because it's a non-
// static method:
System.out.println( Test.addOne(value) ); // Error
// But this will work:
Test ourTest = new Test();
System.out.println( ourTest.addOne(value) ); // Outputs 13
An Application written in Java will normally only have one main-Method, which declares the point where the Application first starts off.
If you want to do stuff with variables, objects, etc you'll want to create your own methods/classes but they won't be main-Methods.
First of all, method can't have another method inside it. Every method has to be part of a Class. The difference between a main method (actually the main method which you are talking about) and any other method is that execution of the program starts at the main method.
A method represents a functionality or a set of instructions that have been grouped together. And a class is a set of methods and variables that define an entity (like Shooter, Die).
So you'll have a Die class which will contain methods that will only contain die specific methods, a Shooter class with methods specific to Shooter and a Craps class, from where the game will begin, that utilizes the methods of the Die and Shooter classes to complete the game.
I'm sure some of the other guys here will be able to explain this much better than I can, but I'll give it a shot.
So, as you know, your main method is the sort of entry point to your program. It is the first thing executed. You can add other methods in the same class, but these methods are static methods as you can't instantiate a class that has your main in it (at least I don't think you can; I've never actually tried).
The purpose of making a class and defining methods is so that you can create objects out of that class. For instance, in your case, you create a Die class. You can then create Die objects from that class. Think of a class as a sort of model or mold that you create objects out of. Once you create these objects they each have their own data members (variables defined in the class). Lets say in your Die class you defined two variables, die1 and die2, each Die object you create will have a die1 and die2 variable, but each Die object can hold different values for these variables.
Now, lets say you create a method in the die class that modifies these variables (a setter method) and lets call it public void setDie1(int value) then you can modify the value of the die1 variable by calling that method on the Die object with something like myDieObject.setDie1(3).
To put this altogether, if you just put methods in the same class as your main method then you wouldn't be able to have multiple objects created from the same class.
This can be a tricky concept to figure out at first, but it will all clear up quickly as you learn more. I hope this helps!
The main method
This is the only method REQUIRED to run a Java application. The method MUST have a very specific signature public static void main(String[] args). The reason why it needs this specific signature is because the Java Virtual Machine (JVM) needs to find it in order to execute your program. The JVM is that Java runtime "thingy" you install on your computer to run programs. More correctly, the Java Runtime Environment (JRE) contains the JVM. The String[] args is 0 or more arguments the method accepts from the command prompt when executing a program. Simple programs often don't require any arguments being passed from the command prompt.
What might confuse beginner Java programmers, is that it seems that many projects out there have main methods in every .java file. This is not required. This is done so that each class could be run in isolation from its dependencies. In a project (application) only one class is required to have a main method.
Other methods
Methods other than the main method are optional. If you want, you could place 100% of your program logic inside of main. But, you can understand the problem with that. If you do that, your code will only be able to do a very specific sequence of steps. Back in the days prior to modular programming, this was the way it was done. So, if you needed to write a program that did something slightly different, you needed to write a new program. It is not very efficient, but it still works. Fast forward a few years after "modular programming" became a thing and now you have to write programs that have to react to events. For example, a user hovers the mouse over a button. The problem with events is that events are unpredictable. Not only you don't know WHEN events will occur, but also you cannot predict the ORDER in which they will occur. Therefore, having all the logic inside a single function (i.e. main) won't work and compiling a "different" sequence of steps inside main might not work also because you cannot predict the WHEN and HOW.
Methods allow you to encapsulate very small units of execution in a prescribed order. The assumptions is that, whenever a situation calls for it, the same sequence of steps must be executed. So, you modularize your code and extract those small sequences you know will always execute in that order and put it in some "method" so that you could call that sequence of steps when I needed.
Example
Simple program with no command-line arguments
public class MyProgram {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
When you execute the compiled unit from the command prompt, you will type java MyProgram and in the console you will see "Hello World!"
public class MyProgram {
public static void main(String[] args) {
System.out.println("Hello " + args[0]);
}
}
However, in the above program, if you don't provide an argument, it will throw an exception when executing. But, if you pass at least one argument, it will display the very first argument and ignore the rest. For example, java MyProgram Hector Fontanez will display "Hello Hector"
On both examples, the JVM called the main method for execution.
public class MyProgram {
public static void main(String[] args) {
showGreeting("Hello " + args[0]);
}
public static void showGreeting(String greeting) {
System.out.println(greeting);
}
}
In this last example, I created a function called showGreeting. Contrary to the main method, I as a programmer decided when and where to call this function, not the JVM. In the function, I extracted functionality I thought the method needs to execute in order to "show a greeting". I know my example has only one line. But you get the idea. As my program grows, I can call showGreeting from other parts of the program as many times I think, as a programmer, is necessary for my application to do the job it is required. Not only that, from the main method, the argument being passed will not necessarily the same as the argument that could be passed from another part of the program.
Lastly, you need to understand what are static and non-static methods, and also understand what public, protected, private, and default (no keyword) access modifiers do.
New Java programmers often encounter messages like the following when they attempt to run a Java program. (Different Java tools, IDEs and so on give a variety of diagnostics for this problem.)
Error: Main method not found in class MyClass, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Error: Main method not found in the file, please define the main method as:
public static void main(String[] args)
Error: Main method is not static in class MyClass, please define the main method as:
public static void main(String[] args)
Error: Main method must return a value of type void in class MyClass, please
define the main method as:
public static void main(String[] args)
java.lang.NoSuchMethodError: main
Exception in thread "main"
What does this mean, what can cause it, and what should one do to fix it?
When you use the java command to run a Java application from the command line, e.g.,
java some.AppName arg1 arg2 ...
the command loads the class that you nominated and then looks for the entry point method called main. More specifically, it is looking for a method that is declared as follows:
package some;
public class AppName {
...
public static void main(final String[] args) {
// body of main method follows
...
}
}
The specific requirements for the entry point method are:
The method must be in the nominated class.
The name of the method must be "main" with exactly that capitalization1.
The method must be public.
The method must be static 2.
The method's return type must be void.
The method must have exactly one argument and argument's type must be String[] 3.
(The argument may be declared using varargs syntax; e.g. String... args. See this question for more information. The String[] argument is used to pass the arguments from the command line, and is required even if your application takes no command-line arguments.)
If anyone of the above requirements is not satisfied, the java command will fail with some variant of the message:
Error: Main method not found in class MyClass, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Or, if you are running an extremely old version of Java:
java.lang.NoSuchMethodError: main
Exception in thread "main"
If you encounter this error, check that you have a main method and that it satisfies all of the six requirements listed above.
1 - One really obscure variation of this is when one or more of the characters in "main" is NOT a LATIN-1 character … but a Unicode character that looks like the corresponding LATIN-1 character when displayed.
2 - Here is an explanation of why the method is required to be static.
3 - String must be the standard java.lang.String class and not to a custom class named String that is hiding the standard class.
The problem is that you do not have a public void main(String[] args) method in the class you attempt to invoke.
It
must be static
must have exactly one String array argument (which may be named anything)
must be spelled m-a-i-n in lowercase.
Note, that you HAVE actually specified an existing class (otherwise the error would have been different), but that class lacks the main method.
Other answers are doing a good job of summarizing the requirements of main. I want to gather references to where those requirements are documented.
The most authoritative source is the VM spec (second edition cited). As main is not a language feature, it is not considered in the Java Language Specification.
2.17.1 Execution - Virtual Machine Start-up
5.2 Virtual Machine Start-up
Another good resource is the documentation for the application launcher itself:
java - the Java application launcher
If you are running the correct class and the main is properly defined, also check if you have a class called String defined in the same package. This definition of String class will be considered and since it doesn't confirm to main(java.lang.String[] args), you will get the same exception.
It's not a compile time error since compiler just assumes you are defining a custom main method.
Suggestion is to never hide library java classes in your package.
The name of the exception suggests that the program tried to call a method that doesn't exist. In this context, it sounds like the program does not have a main method, though it would help if you posted the code that caused the error and the context in which the code was run.
This might have happened if the user tried to run a .class file or a .jar file that has no main method - in Java, the main method is the entry point to begin executing the program.
Normally the compiler is supposed to prevent this from happening so if this does happen, it's usually because the name of the method being called is getting determined ar run-time, rather than compile-time.
To fix this problem, a new programmer must either add the midding method (assuming still that it's main that's missing) or change the method call to the name of a method that does exist.
Read more about the main method here: http://csis.pace.edu/~bergin/KarelJava2ed/ch2/javamain.html
Generally, it means the program you are trying to run does not have a "main" method. If you are going to execute a Java program, the class being executed must have a main method:
For example, in the file Foo.java
public class Foo {
public static void main(final String args[]) {
System.out.println("hello");
}
}
This program should compile and run no problem - if main was called something else, or was not static, it would generate the error you experienced.
Every executable program, regardless of language, needs an entry point, to tell the interpreter, operating system or machine where to start execution. In Java's case, this is the static method main, which is passed the parameter args[] containing the command line arguments. This method is equivalent to int main(int argc, char** argv) in C language.
I feel the above answers miss a scenario where this error occurs even when your code has a main(). When you are using JNI that uses Reflection to invoke a method. During runtime if the method is not found, you will get a
java.lang.NoSuchMethodError: No virtual method
If you are using VSCode:
Choose: Clean Workspace
Choose: Restart and delete
Keep coding :-)
For those who encountered this problem in Kotlin Project.
You can try deleting .idea folder and running the project again - for me it solved the issue. (better close IntelliJ first)
Seems like sometimes IntelliJ gets all confused about the main method signature and expecting the java signature instead of the Kotlin one.
Few min back i was facing " main method not defined".Now its resolved.I tried all above thing but nothing was working.There was not compilation error in my java file.
I followed below things
simply did maven update in all dependent project (alt+F5).
Now problem solved.Getting required result.