The below code gets compiled successfully, wherein inside some class, I have written two methods with same name & same type signature. Am using Eclipse Oxygen 4.7.0 and I can see error Duplicate method show(int,int) shown in red. But when I compile the code, its getting compiled successfully with correct output. When I run the same code in command prompt using javac its validly not getting compiled.
package oops2;
class A6
{
int i, j;
void show(int i, int j)
{
System.out.println(" i & j : " +i + " " +j);
}
void show(int k, int l)
{
System.out.println("override or not");
}
void show(String s)
{
System.out.println("Entered str is "+s);
}
}
public class OverrideNoInherit
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
A6 a = new A6();
a.show(20, 30);
a.show("this is it");
}
}
Here, I want to mention that when I click on run on Eclipse, I get a pop-up saying
Errors exist in this project, proceed with launch?
Now, didn't this error mean that there are other classes in same project which had errors & thus did not get compile. I don't think this meant that despite there being errors in code, the programs would get compiled. Then what would be difference between warnings & errors?
Eclipse always compiles classes. The body of methods containing errors are replaced by a method that throws a java.lang.Error containing the compile errors of that class. This is actually helpful for test driven development that allows you to start tests on classes that have compile errors. The methods that are compilable can be tested even if some other parts are currently containing errors.
You've got a special case here. The compiler is able to compile the first occurance of the method but later comes across the duplicate method that can't be added to the class. Because the first method is already compiled and when you enforce the starting of the class despite the warning you see the regular method that was successfully compiled in action.
Related
I wrote a Java program whose filename was (intentionally) different from the class I wrote inside the file. The javac command failed as expected on both CMD and WSL. The java command however worked and ran my print statement. I wrote the code intentionally this way so there is no way it was a previously compiled version of the code. The following code was written in a file called "explainJava.java" (notice the filename is different from the class name).
public class explain{
public static void main(String[] args) {
System.out.println("Java is weird");
}
}
I've had to google this myself, but I think I've found an explanation in this article.
According to that source as of Java 11 java is capable of compiling a single source file into memory.
What I conclude from that: When the file is compiled into memory and not written to disk it obviously cannot have a file name. If there is no filename there is no such thing as a wrong filename, therefore the code executes.
Please also note that the restriction of having to name a file like the public class within that file is more of a design decision to make work for the compiler easier/ faster. It is not a physical restriction so to speak. Have a look at the following thread for more details.
If you put this code:
public class explain {
public static void main(String[] args) {
System.out.println("Java is weird");
}
}
into a file named explainJava.java, and then compile it with this:
javac explainJava.java
you will get an error that correctly informs you that your filename ("explainJava") and the class defined inside that file ("explain") do not match:
explainJava.java:1: error: class explain is public, should be declared in a file named explain.java
public class explain{
^
1 error
If you run this command:
$ java explainJava.java
Java is weird
you see expected output, because you're skipping the explicit compilation step (that is, you aren't running javac first) and instead relying on behavior introduced in Java 11 that allows you to compile+run in a single step. Here's an explanation: Does the 'java' command compile Java programs?
So the answer is to either:
rename your file to match the class, so change the filename to "explain.java", or
rename the class to match the file, change public class explain to be public class explainJava
Let's say i have a code like this :
public class Test {
public static void main(String args[])
{
int x = 5;
// Widening Casting
double myNum = x;
System.out.println(x + " " + myNum);
}
}
Now i write the following commands in powershell changing the value of x from 5 to 6 once in my code and saving it, it works perfectly fine. But tutorials online suggest me to use javac for compilation. Why so?
From Java 11 onwards, the java command is able to compile and run a single Java source file with a static void main(String[]) entry point method. (This feature was added as JEP 330.)
The online tutorials are correct for Java 10 and earlier, and they are correct for cases where more than one Java source file needs to be compiled.
My code is:
if (client == null) {
// this can happen e.g. during a graceful shutdown
throw new ImapTaskRunnerRetrievalException("user " + user + " not found (provisioned null)");
}
Which gives the error
Incompatible types.
Required: java.lang.Throwable
Found: me.unroll. ... ImapTaskRunnerRetrievalException
even though when I command click on this thing I get
// IntelliJ API Decompiler stub source generated from a class file
// Implementation of methods is not available
package me.unroll.emailfetcher;
public interface ImapTaskRunnerSource {
// ...
static class ImapTaskRunnerRetrievalException extends java.lang.Exception {
// ...
}
}
Not sure why IntelliJ is so confused. The files live in different Maven/Nexus repos but it clearly found the code, so I'm not sure why it's being contradictory.
I have a similar issue on this method:
logger.error(CloudwatchMarker.RangeCachePoolRejectedTask.get(), "rejected range search on start", exc);
Error:
Cannot resolve method 'org.slf4j.Marker, java.lang.String, Exception)
Even though command clicking through to Logger gives this:
public void error(Marker marker, String msg, Throwable t);
Configure an SDK, e.g., JDK. Not doing this causes really wonky problems.
My DrJava was working fine, but now I keep getting the folowing error whenever I run anything:
Static Error: This class does not have a static void main method accepting String[].
So it will compile OK, but then it shoots out the error . This happens even though everything I test does indeed have a public static void main(String[] args) in it. It seems like a classpath/resources type of error. I appreciate any tips
EDIT: my class
public class Test{
public static void main(String[] args){
System.out.println(" hashmap ");
}
}
There's nothing wrong with the code, so the problem must be with the environment.
Check that you're actually executing that class. Find out where the class that's executed is specified and check it's correct
Check that you're compiling the class. Maybe the code you're looking at has not been compiled and you're trying to execute an old version that was compild before you coded a main()
Check your classpath. Is the compiled class accessible in the classpath of the java command
You don't need to reinstall java, nor is it a java version issue. It may be the way that your are running the program.
To check if it is a problem with your code, do the following:
Make a new folder and put Test.java in it.
Open up Command Line Or Terminal and change to that folder .
Type javac Test.java. Test.class should be in the folder now.
If you want, open up the class with a text editor. This is what I get:
˛∫æ2
<init>()VCodeLineNumberTablemain([Ljava/lang/String;)V
SourceFile Test.java hashmap Testjava/lang/Objectjava/lang/SystemoutLjava/io/PrintStream;java/io/PrintStreamprintln(Ljava/l ang/String;)V! *∑±
% ≤∂±
Back to the command line or terminal, type java Test.
If you get an error, which you shouldn't, I don't know what to say. It should produce the string " hashmap " on to the command line or terminal.
Why re-installing Dr. Java may not work is because you may be using the same working directory, causing same run settings to be used. Dr. Java may be running an external program, one without a main method.
I think that you should install the Eclipse IDE for Java. It is much easier to get around, it looks nicer, and it runs the file or project that you are looking at currently.
Sometimes this problem happens because may be mistake in saving file.you always your file using double quotes and with the .java extension which is main class means that class containing main method.
you should save your file by class name which is public .if there is two classes and both have main method then you should save your file by class name that is public and that class will be run.As like your compiler looking for main method in public static void main(String [] args) that is contract for jvm to run a programme
so it is not able to found that main method that is static and it looking for your Dr class.java
See this Example it have two main methods and practice these kinds of question.I also got this kind of problem in starting.
public class TestFirst
{
public static void main(String [] args){
System.out.println(" TestFirst ");
}
}
class Test{
public static void main(String [] args){
System.out.println(" hashmap ");
}
}
if you save pro-gramme by "TestFirst.java" then o/p will come TestFirst if you do some mistake in main method because we have saved our programme by TestFirst then you will get error like you got.
# 2nd mistake may be this
debian#debian:~/Geany_java$ javac Test1.java
debian#debian:~/Geany_java$ java Test1
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at Test1.main(Test1.java:11)
your classpath has not set properly See above Compiling successfully but running showing same kind of error you got.Which OS is using I can guide you properly.
Check that actually your file have the .java termination nor the .dj
There is nothing wrong with the code.
It is the executing environment which might have problem. Please share the details.
Check if program compiled correctly.
Check time-stamo of .class file.
Check permissions on folder/directory where class-files are getting generated.
Check if DrJAVA has appropriate permission on the directory.
Did you create a file, compiled it with out main?
Check class-path. Might be possible that previous class file is still being found by JDK in classpath.
Try compiling .java file from cmdLine instead of editor.
As others have mentioned, your code is fine. There must be a problem with your environment. I recently experienced a similar issue when investigating and answering this question.
Basically, in that question, the code Void.class instanceof Class resulted in a compiler error because a user-made Class.class existed in the classpath, so one Class (the Java built-in java.lang.Class) didn't match with the given Class (user-made).
Something similar may be at work here. It is possible that there is a user-made String.class in your classpath. Then in your main signature, String[] args would mean an array of your String, when Dr. Java must be looking for a main method taking an array of the Java built-in String, i.e. java.lang.String[]. If you have a custom String class in your classpath (or in your project?), then the Java compiler will choose it over the built-in String. If you were to compile and run your Test class from the command line, then you would get the runtime error: Exception in thread "main" java.lang.NoSuchMethodError: main.
Following #S0urceC0ded's suggestion, you may find this when looking at Test.class in a text editor:
main([LString;)V // A user-made String class
instead of what it's supposed to be:
main([Ljava/lang/String;)V // The built-in java.lang.String class
If so, remove your own String class (at least the .class file, but also the .java file so the .class file isn't re-created) from the classpath, and compile and run your Test class again.
Without a look at your environment, I can't tell for sure that this is the issue. But it can explain it.
If you are using Dr.Java as IDE, then you need to make sure that the main class containing 'public static void main' should be at the very top of your program. Otherwise Dr.Java throws this error during runtime.
I have tried some of the existing solutions but it does not work.
I have two files/classes First.java (in which main is defined) and Second.java where simple functions are defined.
**First.java:**
import java.util.*;
public class First
{
public static void main(String[] args)
{
Second s1 = new Second();
s1.Hello();
}
}
When I debug the above code in eclipse, it gives me error "source not found" on the line Second s1 = new Second();
However, this error occurs, if I click "step into". If I click "step over" on the aforementioned line, the error does not occur; and if click on "step into" in subsequent steps, the error does not occur again, and the execution successfully enters into the second file "Second.java".
So my question is, Is there a way that I can enter the constructor of the "Second.java" without stepping over it?
How to set the source path.
Second.java class:
public class Second
{
int a;
public Second()
{
this.a=100;
}
public void Hello()
{
System.out.println("hello how are you");
}
public int GetResult()
{
return a;
}
}
The problem is when you 'step into' the line when the Second object is created, it is asking the classloader to load the Second class. Since you probably do not have eclipse setup to point to the location of the java sources, eclipse does not know where the java source code is on your machine for all the files the vm uses to load the class, including java.lang.ClassLoader, and eclipse shows you the 'Source not found' page.
You can:
Move the break point from the line Second s1 = new Second(); in First.java to public Second() in Second.java. Then when you debug, you should hit the break point after the Second object has been loaded by the VM and you should be able to debug the constructor as it is being instanciated.
When you 'step into' the break point at the line Second s1 = new Second(); and get the source not found page, immediately 'step return' and then press 'step into' again, which should take you to the constructor of the Second class.
Click on attach source, and browse to the directory of the java source files. They are usually included with the JDK download and are located in a file called src.zip in the installation folder of your VM (for the Sun VM).
Source not found usually means that Eclipse can't find the required files. Is Second.java in your project? The best thing is to make a package such as me.russjr08.projects. That way Eclipse can search through the package (Assuming all of the correct files are there) and find the class / java files you want to use.
IIRC Another solution is to include Second.java in your src folder