main method as final in java - java

I saw this code in one of the certification exams:
public class SimpleClass
{
int num;
final static void main(final String args[])
{
String s1="new";
String s2="String";
String s3="Creation";
System.out.println(s1+s2+s3);
}
}
I know that final methods are ones which are not possible to override. I also know that if the usual signature of the main method is altered, it will be treated as any other ordinary method by the JVM, and not as main().
However, the options given to me were:
1> Code won't compile
2> Code will throw an exception
3> will print newStringCreation.
It's not possible to run this program on eclipse IDE. Can anyone explain what should be the answer and why?
Ok let me put my question like this - When I execute my program, what will happen? Which of the 3 options above should I choose?

final static void main won't run, since main is not public.
public final static void main will work.
At least that's the behavior on my Eclipse IDE.

The Code will compile without any problems but it will throw a run-time exception saying "main method not public". The main method has to be public because it has to be called by JVM which is outside the scope of the package and hence would need the access specifier-public. If you are unable to run it in eclipse, try the archaic method of saving the file in a notepad with filename.java. Go to cmd and reach the file location..If on desktop, use cd desktop! Use the following commands to run the file-
javac filename.java
java filename
You will see the required run-time exception that I mentioned above.

The main method has to be accessible from the outside. Hence, in your case the application will compile but throw an execution at runtime.

You have the main method but since the modifier is final JVM wont be able to run the main method of the program.You wont see any compilation error.
You can run the program in eclipse when you make the modifier change of final to public

Related

Why doesn't obj.start() run when I run my code?

I'm learning java and practicing on sololearn.com and I copied one of the examples to practice typing code. However the code here -
//Create myClass
class Loader extends Thread {
public static void main(String[] args) {
}
public void run(){
System.out.println("Hello Young World");
}
}
public class MyClass {
public static void main(String[] args) {
Loader obj = new Loader();
obj.start();
}
}
isn't printing "Hello Young World" to my console. In fact I had to add a 'main()' method to the Loader class just to run MyClass.java. However in the example their code ran without having to include a main method in Loader. Maybe they have customized their environment to allow for this type coding and IntelliJ just has different rules. Please could someone copy the code on their machines and run it with IntelliJ to see if they run into the same problem?
I've troubleshooted, but the code seems to be solid.
I guess you start the wrong main-method (the main from the Loader class which is empty). As you noted, you donĀ“t have to add a main-method in your Loader class. Please remove the method and start the main-method from MyClass.
If you have several main-methods, you can choose which one should be executed in the run configurations. In your example, it should look like this:
In this case, make sure you select the one you like to execute.
Another way to execute the right main-method, is to select the class which contains the main-method and hit the play button on the left side:
To run the program in my console I had to 'java MyClass' rather than running 'java MyClass.java' which executed the whole file rather than just the class whose main method I wanted to call!
To run the program in IntelliJ I had to make sure that the right Class was being called as pointed out above.

Every java program I try to start shows error

SOLVED, Program was in location with national symbol in it's path.
I just started studying java, but every program i try to start (even example ones from my course) shows an error.
Error: Could not find or load main class "Any class name of program I try start"
C:\Users\Mine\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
edit:
example of code, but happens to any code.
public class Hello {
static void hello(){
System.out.println("Hello, World!");
}
public static void main(String[] args) {
hello();
}
}
This error means that when Netbeans is invoking the JVM, the JVM cannot find the class file for the class Netbeans is telling it to run. When you create a project in Netbeans, the classpath will be configured for you by the IDE, so you shouldn't normally see this error unless you have deleted the auto-generated main class and made a new one from scratch in the wrong place.
So the first thing to do is check what class Netbeans is using as the main class:
Right-click on the project name in the Projects tab and click on "Properties"
Then click on "Run" and check the name of the class in "Main Class":
Note in my example the class is called "tests.Test". This means the class Test in the package "tests". In your question, your class "Hello" doesn't have a package declaration at the top (although you may have chosen not to copy this). If you have no package (and you really should be using packages, even for trivial programs like "Hello, World!", just to get used to doing so, if nothing else), the "Main Class" entry should just be the class name.
So you need to either move your class into the package specified in this parameter, or change this parameter to match the fully qualified name of your main class
Error: Could not find or load main class "Any class name of program I try start"
C:\Users\Mine\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
You are attempting to run a class called Any class name of program I try start, however the name of your class is Hello.
I don't know how Netbeans does things, but I would first try compiling and running the program without netbeans.
javac Hello.java
java Hello
If that works then open up the run settings in netbeans and make sure that it is doing the same thing.
Just make a new main class or just re-type public static void main(String[] args) { } and that's it.

Run javac compiled groovy code using java?

I have a simple groovy file as follows:
class test2 {
public static void main(String[] args) {
println("In groovy!!");
}
}
My gradle task is compiling this into a test2 class file
How do I run this file from prompt ?
java test2 (from the location of the test2.class file)
causes a : Error: Could not find or load main class test2.class
I assuming I need to add asm and groovy to the class path. However:
java -cp "groovy-all-2.3.6.jar;asm-all-3.3.1.jar" test2
also doesn't work (files are in correct locations).
I know this may be a bit late for the OP but nevertheless:
Given that your groovy main exists, the error message:
Error: Could not find or load main class YOUR_MAINCLASS_HERE
from the java command while executing a groovy main (of a compiled groovy file which produced classes) means basically that your groovy jar is not in the classpath.
Longer Answer:
Lets see why that is for a simple hello world example. I have a file called main.groovy with the following content:
class Main {
static void main(String[] args){
println('hello world')
}
}
Put this somewhere in your filesystem. Open a command prompt in the same directory and ensure that groovy and java is accessable though the PATH.
In the command prompt, compile the file with groovyc, so just type in:
groovyc main.groovy
This will produce a file called Main.class (with uppercase M because of the class name).
Ok now we have the appropriate test setup. If you now try to run the file just with java command:
java Main
you will get the error message:
Error: Could not find or load main class Main
This is a bit unexpected, because one can think that we just can invoke the main in our Main.class without linking the groovy library, so we would expect an exception like ClassNotFoundException.
In contrast, try again with groovy in your classpath. I will refer to the directory of your groovy installation as GROOVY_HOME. To run the hello world Main class finally, we can type in:
java -cp ".:/$GROOVY_HOME/lib/*" Main
which produces the expected output on unix-like systems (on windows you need to replace the colon with a semicolon and the variable access would be like %GROOVY_HOME%).
The reason is quite simple: Groovy produces for groovy main methods not the same signature as required by the java specification. Therefore, you can only invoke a groovy main with groovy on the CLASSPATH - what makes totally sense!
You can check this for yourself. Try now the command:
javap Main.class
This will give you a quick analysis of the bytecode and the present interfaces of the class "Main.class". All along you will see something similar to this output:
Compiled from "main.groovy"
public class Main implements groovy.lang.GroovyObject {
public static transient boolean __$stMC;
public Main();
public static void main(java.lang.String...);
protected groovy.lang.MetaClass $getStaticMetaClass();
public groovy.lang.MetaClass getMetaClass();
public void setMetaClass(groovy.lang.MetaClass);
public java.lang.Object invokeMethod(java.lang.String, java.lang.Object);
public java.lang.Object getProperty(java.lang.String);
public void setProperty(java.lang.String, java.lang.Object);
}
Of interest is line 5:
public static void main(java.lang.String...);
This seems quite similar to a normal java main, but with one difference: groovyc used an java.lang.String ellipsis (as stated by the three dots) and not and java.lang.String[].
So this could be the reason. I'm not so sure, because normally java will give you an appropriate error output if it can find the class but not the method signature. For example, try:
java java.lang.Integer
which has clearly not a main method. Java sees that correctly:
Error: Main method not found in class java.lang.Integer, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
I'm also not sure, what groovy does during class loading for understanding this kind of main signature (or lets says this kind of bytecode), but if you compare that with a normal java hello world javap output, you get
public class JMain {
public JMain();
public static void main(java.lang.String[]);
}
which has a different and the normal java main signature.
Maybe someone from the pivotal groovy team can clarify.
I hope this will give you a hint.
The test2.class needs to be on your CLASSPATH. For example, if it is at /Users/you/classes/test2.class then /Users/you/classes/ needs to be on your CLASSPATH.
Since you are building with Gradle, you could also just let Gradle sort all of that out for you using JavaExec. See http://www.gradle.org/docs/current/dsl/org.gradle.api.tasks.JavaExec.html for more info. A simple example in your build.gradle might be something like this:
task myTask(type: JavaExec, dependsOn: 'classes') {
main = 'test2'
classpath = sourceSets.main.runtimeClasspath
}
I hope that helps.

Getting NoSuchMethodError at runtime

I have looked through many answers to similar questions. But couldn't narrow down to a solution.
Following is the code: (Simplifying names for readability)
First class:
package p1;
public class C1 {
public static void test() {
System.out.println("Boom!");
}
}
Second class:
package p2;
import p1;
public class C2 {
public static void main(String[] params) {
C1.test();
}
}
Clean-Build doesn't give any error. (No compilation error)
But at runtime I'm getting following error:
Exception in thread "main" java.lang.NoSuchMethodError: C1.test()V
at C2.main(C2.java:6)
Java Result: 1
P.S. I'm using Netbeans.
This means that you are running your class C2 with an old version of class C1 in the classpath (a version that did not yet have the test() method).
Make sure you don't have old versions of C1.class somewhere. Remove all your *.class files and recompile everything, and then try to run it again.
Addition: As Kevin Bowersox noted in a comment, your main method must look like this:
public static void main(String[] args)
It must take a String[] as an argument.
It will properly compile and run only if main function will have String tab as args.
But also check versions of class C1 and C2, try rebuild your project to recompile that classes.
public static void main(String args[]) {
C1.test();
}
i think you should import it as
import p1.*;
Than you will get access to all classes and member functions in it.
Netbeans sometimes likes to get stuck after some changes and clean build doesn't work then.
Try editing each file that has been recently modified and saving it again (e.g. put a whitespace in a random place). After that, clean and build the project again.
If my memory refreshes and as Jesper pointed out, I also encountered that same issue NoSuchMethodFoundException under that same scenario (having still old class references that have not been cleaned).
I just copied your code snippets with 2 different packages directly in to my netbean, compiled and runned C2. It did print the BOOM! message.
In my case using :
public static void main(String args[]){
}
does not make a difference when I compiled and runned the code.
public static void main(String params[]){
}
It makes sense since the main class should have the correct method signature of main.
Here args or params, should not make a huge difference, I believe; as what we have inside the method is simply a reference for the inner body of the method that it uses.
Still definitely it is good practice to follow the standard signature for main.
I would recommend to clean the project and copy the contents from scratch in a new project and build it again, sometimes netbeans can go crazy.

Is Java not installed correctly? Exception in thread "main" java.lang.NoSuchMethodError

Recently when I write any code and compile it, then try to run it I get this exception:
Exception in thread "main" java.lang.NoSuchMethodError
At first I thought there is something wrong in my code, but I couldn't find anything wrong with it. When trying to run a HelloWorld example that had worked before, if works, but if I copy the exact same code into a file HelloWorld2 I get this exception again.
The code is identical but when I used javap to decompile both class files I found a difference. In HelloWorld (the original file)
"public static void main(java.lang.String[])";
and in HelloWorld2 (the new one)
"public static void main(String[])";
without java.lang..
I recompiled the old HelloWorld with javac and now when I try to run it it doesn't work and I get the same exception. None of my old code now works if I recompile it.
I've searched everywhere but can't find a solution to this problem - any idea what is going on here?
You may get this if you have your own class called String (without a package) in your classpath. It sounds like that's what happened. Here's a way to try to reproduce this - compile it and run it, and see if it looks the same:
class String {}
public class Test {
public static void main(String[] args) {
}
}
Once you've got the compiled String.class file in your file system in an awkward place, that will be used by default even if you only compile the Test class above...
Basically, see if you can find a file called String.class somewhere.

Categories

Resources