Java package - class not found, same directory - java

I have two Java classes "giveMyOb" and "dataConn" declared in the same directory. Both are public classes. "giveMyOb" has a static method "getMine()". Inside dataConn, I called the static method as
giveMyOb.getMine();
When I try to compile dataConn.java, the following error is returned.
"Cannot find symbol
symbol: variable giveMyOb
location : class dataConn
giveMyOb.getMine(); "
It used to work earlier. But is not working now. Why is that?
Additional Information: JDK 1.6. Windows 7. 64 bit.
Update(30 days after the question): When compiled from Eclipse, the classes are referenced and it works. But the same won't work when compiling from command line. I was unable to figure out the reason and nothing logical comes to my mind!

javac -classpath . *.java
ought to create both .class files at the same time. It's more complicated by packages. I'm assuming you have none.
Learn the Sun Java coding conventions. You aren't following them with those class names. They should start with a capital letter.

Try this:
giveMyOb.java
public class giveMyOb {
public static String getMine() {
return "Yay, it works!";
}
}
dataConn.java
public class dataConn {
public static void main(String[] args) {
System.out.println(giveMyOb.getMine());
}
}
Then compile it all:
javac *.java
and run the main class:
java -cp . dataConn
// output: Yay, it works!
Note that Java's coding conventions recommend class names start with a capital.
If "it" still doesn't work, try removing the .class files manually then recompile again.

Related

Java program runs yet compilation fails

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

Java file not compiling

Currently trying to work with objects in Java. Everything goes fine until I hit compile. Have been reading a couple of other questions regarding the same problem, or the same given error, and at this point I am not sure wether I am forgetting something or that I need to change my classpath.
Main Class file:
package TesterClass;
public class Tester {
public static void main(String[] args){
TesterClass firstTest = new TesterClass();
firstTest.stringPrinter();
}
}
The file that is supposed to be functioning as a package file:
package TesterClass;
public class TesterClass{
private String workingSegment;
public TesterClass(){
workingSegment = "Working";
}
public void stringPrinter(){
System.out.println(workingSegment);
}
}
The 2 files are in the same directory and I am trying to manually compile them with
"javac Tester.java". The error I get is about the fact that its having issues with the package. All help is welcome!
EDIT: Forgot to post the actual compiler error.
Tester.java:9: cannot find symbol
symbol : class TesterClass
location: class TesterClass.Tester
TesterClass firstTest;
^
Tester.java:11: cannot find symbol
symbol : class TesterClass
location: class TesterClass.Tester
firstTest = new TesterClass();
^
2 errors
Move to the top of the source tree and compile both class...
So, assuming you source files are in \Java\TesterClass, you need to start in \Java
javac TesterClass\Tester.java TesterClass\TesterClass.java
You may also want to have a quick read of Code Conventions for the Java Programming Language as packages names are suppose to be in lower case :P
Updated
I just tried...
javac TesterClass\Tester.java
And it worked fine.
Are you sure that the Tester.java and TesterClass.java are in the TesterClass directory?
Updated with running example
So, basically, I dropped you .java files into the directory \compile under the TesterClass (\compile\TesterClass) directory and compiled them using...
\compile>javac TesterClass\Tester.java
Then I run them...
\compile>java TesterClass.Tester
Working
You need to go to the top of the directory hierarchy and first compile your TesterClass and then compile your Tester. Since you have not compiled your TesterClass yet, Tester is unable to find it.
The error clearly states that its not able to find the symbol TesterClass, and the reason being TesterClass hasn't been compiled yet.
I suggest you use an IDE which does the compilation automatically for you. If you stick to manual compilation, you need to compile all the classes in the proper order.
Try changing the package name so it does not match the class name. Right now they are the same. Make it package TesterClassPackage, then import TesterClass into the file with the main() method. Even though they are in the same package sometimes you need to literally import files even though they are in the same package.
javac TesterClass\TesterClass.java TesterClass\Tester.java
will do it

Getting "class does not have a static void main method accepting String[]" error even though main signature is correct

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.

Different behaviour of netbeans and console

I have written a code in java. In which I have created a package called xml-creator.
Package xml_creator has 3 classes say XML_Control, XML_Creator, and XML_implement.
When I run my project on netbeans (NetBeans 7.0) it works fine. But if I try to compile code on console, I get various errors like
When I compiled XML_Creator.java, I get following errors.
XML_Creator.java:371: cannot find symbol
symbol : variable XML_implement
location: class xml_creator.XML_Creator
typeAttr.setValue(XML_implement.table_col[i][2]);
^
XML_Creator.java:375: cannot find symbol
symbol : variable XML_implement
location: class xml_creator.XML_Creator
for(int j=0;j<XML_implement.kTab;j++)
^
XML_Creator and XML_implemenr both are in same package but non of them extend each other.
I am sorry I cant show code on this site as it is too large and aginst the company's policies.
I dont understand why it is showing me errors?
Sample code
XML_Control.java
package xml_creator;
public class XML_Control
{
public static void main(String as[])
{
XML_Creator xml = new XML_Creator();
}
}
XML_Creator.java
package xml-creator;
public class XML_Creator
{
XML_implement ixml = new XML_implement();
public XML_Creator()
{
System.out.println(""+ixml.a);
}
}
XML_implement.java
package xml_creator;
public class XML_implement
{
public int a;
public XML_implement()
{
a = 10;
}
}
So when I compile XML_Creator.java, console gives error.
It sounds like you're compiling within the directory containing the .java file, and only telling the compiler about one of the source files. That's the problem - to try to find a source or class file, the compiler is using the package name, and expecting the packages to be laid out in the conventional fashion. Compile from the root of the source tree - which I certainly hope you're using - like this:
javac xml_creator/*.java
You may also want to specify an output directory - which again will be the root of the directory hierarchy for packages:
javac -d bin xml_creator/*.java
If you're building regularly from the command-line (and not just for throwaway code) you should look into using a build system such as Ant.

Why can't I compile my java file on cygwin, when it needs classes from a jar?

I'm trying to compile my class along with a provided .jar file which contains classes that my class will use.
This is what I've been trying:
javac -classpath .:WordSearch.jar WordSearchSolver.java
And this is the response:
WordSearchSolver.java:16: cannot find symbol
symbol : class PuzzleWord
location: class WordSearchSolver
public ArrayList<PuzzleWord> findwords()
^
WordSearchSolver.java:18: cannot find symbol
symbol : class PuzzleWord
location: class WordSearchSolver
return new ArrayList<PuzzleWord>();
^
2 errors
This is my class:
import java.util.ArrayList;
public class WordSearchSolver
{
public WordSearchSolver(int size, char[][] puzzleboard, ArrayList<String> words)
{
}
public ArrayList<PuzzleWord> findwords()
{
return new ArrayList<PuzzleWord>();
}
}
WordSearch.jar contains:
PuzzleUI.class
PuzzleWord$Directions.class
PuzzleWord.class
Natural.class
(WordSearchSolver.java and Wordsearch.jar are in the same directory)
Am I missing something?
Although you're on Cygwin, I'm guessing that your path separator should be a semicolon, since the Java compiler/JVM will be running in a Windows environment.
javac -cp .\;WordSearch.jar ...
Note that the semicolon must be escaped to prevent interpretation by the Cygwin shell (thanks to bkail below)
You aren't importing any of the classes from your WordSearch.jar in your WordSearchSolver class. You need import statements at the top of this class including their package.
It ended up being a combination of semicolons and quotation marks.
javac -classpath ".;WordSearch.jar" WordSearchSolver.java
Thanks everyone for pointing me in the right direction!

Categories