Importing Classes from another package - java

Hello so I'm trying to Import a class from another project I made but I cant get it to work..
this is my code:
import program.GUI;
public class name {
//code
}
I get the following error
Opens the new class wizard to create the type.
package: program
public class GUI {
}
I have created a prog02>src>program>GUI.java
How can I solve it.

I think I see the problem here...
I don't know if your running java from cmd, but my explanation is going to assume you are. Outside of using IDEs like Netbeans and Eclipse that pretty much streamline the build process of java code, it's good to know how it works.
Ok, here goes:
1) Compile your java source code files into bytecode (.class files) by invoking JAVAC
javac [optional flags] [path to file intended for compilation]
This creates the bytecode that the JVM will need in order to execute.
2) Invoke the Java interpreter (JVM) to run your bytecode.
java [optional flags] [name of class file w/o .class extension]
If everything goes right this command will create a JVM process with main.java being the main entry to the program that creates the initial thread that runs your program.
Here what you should write to get you program to compile with you package dependencies.
cd to base dir that contains program with main method (src)
javac -cp . program/ (check by going to dir to see if a GUI.class file
was generated)
javac -cp . Main
java -cp . Main
That should do it. Otherwise from and IDE standpoint you either don't have file in the right directory or you are not using the right syntax for specifying your package and import.

The package declaration on the GUI class is not right. It should be:
package program;
public class GUI {
}
You may also find this useful: Java Code Conventions

Related

'Code Runner' extension shows "Could not find or load main class" when running Java programs inside a package/folder. (VScode)

When I try to run my Java program through "Code Runner" extension while it is inside a package/folder, it shows error "Could not find or load main class".
But if I run same program through marked "Run | Debug" , the programs runs successfully. it also runs succesfully on code runner if the class is outside the folder.
Here are pictures to visualize my problem more clearly.
This one is run through code runner when the classes are inside the folder
It doesn't work here
This one is run through code runner when the classes are outside the folder
It works here
This one is run through the run button over the main function, it runs the program through the terminal.
It works here
the white and black lines are drawn to hide some personal information.
Is something wrong with 'Code Runner' extension? Btw, 'Code Runner' runs Python, C, C++ without any problem. even if they are inside a folder in these languages, it works perfectly fine.
As a test, I created the following directory structure:
Test
├── Test1.java
└── Test2
└──Test2.java
As you described, the compilation runs normally in the first-level directory, but an error occurs in the second-level directory.
It's not entirely a matter of Code Runner extensions, there are also language specifications for the Java language itself.
As a test, you can run the program directly from the command line using the javac and java commands.
We can see that in the secondary directory, the compilation is successful, but the operation fails.
Use the run button on the code block to run successfully. We observed the command line code and found that it is not running the code in the secondary directory, and it specifies the classpath path.
Looking back, we return to the first level directory on the command line, run the java command again, and the operation is successful.
So we see that the command executed by the code runner is to simply run the javac and java commands directly in the current directory, so the operation fails.
Also as you said, languages like python don't have this problem. Because they don't have this language specification.
The problem arises from the java packages which are a means to organize sources,
actual a very useful feature considering easily dealing with hundreds of sources.
Java uses a folder tree = package hierarchy.
(Package names (directories) by convention are in small letters.)
C:\Users\Me\JavaProject> javac foo/bar/Hello.java
C:\Users\Me\JavaProject>
foo\
baz\
World.java
package foo.baz;
public class World {
public static final WORLD = "World";
}
bar\
Hello.java
package foo.bar;
import foo.baz.World;
public class Hello {
public static void main(String[] args) {
System.out.println("Hello " + World.WORLD + "!");
}
}
Hello.class
C:\Users\Me\JavaProject> java foo/bar/Hello
Hello World!
The consequence of having packages means that you must compile and execute in the root directory. When packing the .class files in a .jar file (a zip format) it becomes easier, the directories are inside the jar file.
An IDE will help with all this.
A build infrastructure could be maven (or gradle). A maven project provides a conventional directory layout, and so on.

Could not find or load main class - for any program

I'm having a problem where the java command - no matter what I'm trying to run, says that it Could not find or load main class.
Everything is fine when compiling with javac, .class files are created. So when I run:
javac HelloWorld.java
on
public class HelloWorld{
public static void main(String[] args){
System.out.println("Hello World");
}
}
everything compiles fine, a HelloWorld.class file is created along side the HelloWorld.java file. However when I then go to run:
java HelloWorld
1) the most telling sign is that when I press Tab to autofill HelloWorld nothing comes up.
2) when I do run it, I get the Error: Could not find or load main class HelloWorld despite it being in the same directory, not being part of a package, compiling fine with a .class file, the program having a main class.
For reference running Fedora 23 64bit, openjdk version "1.8.0_111".
Just a small reminder for the newbies in Java:
When compiling, you type:
javac MyClass.java
Now, you've got two files:
MyClass.class MyClass.java
Now, whereas you typed the .java extension when compiling, you must NOT type the extension .class when running the program. You should just type:
java MyClass
If you type java MyClass.class then you'll get:
Error: Could not find or load main class
Try using java -cp . HelloWorld
Some good reading: http://www.sergiy.ca/how-to-compile-and-launch-java-code-from-command-line/
You need to specify classpath parameter while running your example:
java -cp . HelloWorld
java -cp HelloWorld
works. I use windows 10, and was checking out the very course. I first had to add it to path, and spent time wasted on it. Be sure, however, to NOT include the .class part of the name. Java is not my first language, but Java is portable and is a suitable language for everyone.
The same happened to me while compiling a piece of code (that was initially writen for an IDE with several files) throug terminal. The problem was mentioning the package with the same name of the main class (package HelloWorld). I fixed it and now it works. Not sure if that's your case
May be you have removed your JDK From System.
You can change it using following steps
1> Select Project
2> Right Click On Project
3> Click On Properties
4> Go to Java Build Path
5> Click On Libraries Option
6> Select JRE System Library
7> Click On Edit
8> Change Your Library Accordingly

Running a simple Java Program in Command Prompt error

I am trying to run my Example2.class program in windows 7 64-bit command prompt. I used command prompt already to compile the program, but when type: "java Example2" it gives me an error saying could not find or load main class example2. How do I set the right path to my file so that it can find it? Thanks
You need to give it the full package name, and (unless you change the class path) you need to be in the right directory. If the full package name is
com.something.Example2
then you'd expect the compiler to produce a file like this:
com/something/Example2.class
If you make sure you're in the directory immediately above com (i.e., you can see com when you do a directory listing), then you can run it with
java com.something.Example2
Note that it's case sensitive.
If you used the default package (i.e., the full class name really just is Example2) then you need to be in the directory containing Example2.class, and then you run
java Example2
But using the default package is discouraged.
The biggest thing you could do to help yourself out is to use an IDE (Eclipse or NetBeans are the most commonly used ones). As soon as you start to write anything at all large or complex, compiling and running from the command line without an IDE will cause you to claw your own eyes out.
When you write a class you can save the file as : MyClass.java and then execute this commands in this directory:
javac MyClass.java
which will compile the class and then create automatically the file: MyClass.class (If compilation ended without errors)
and then to run this SPECIFIC class execute the command:
java Myclass

Cannot run simple HelloWorld class [duplicate]

This question already has answers here:
Cannot run simple compiled java program?
(4 answers)
Closed 8 years ago.
I'm trying to compile simple Java HelloWorld source on Windows. I compile it the following way:
javac HelloWorld.java
But then when I run it like this
java HelloWorld.class
I get an error
Could not find or load main class HelloWorld.class
But the file is there, any hints?
Run it like this:
java HelloWorld
Do not put .class suffix after the class name.
java -cp . HelloWorld
The . is needed in order to tell Java to include the current directory in the classpath.
HelloWorld is the name of the class to run (must not add the .class suffix).
This is rather a basic step towards Java development and it's important!
say you have a Java file named: Main.java , open it by your favorite editor:
public class Main
{
public static void main(String[]args)
{
System.out.println("Rugal");
}
}
Now just exit your editor and use javac to compile:
javac Main.java
which will generate a Main.class file.
Then you can use java to launch a JVM to execute this main method in class Main.
java Main
notice that as your class name is Main thus you need to execute the Main class.
here you need not to include .class suffix after the class name.
If you have package name in this class, just use:
java your.package.name.Main to execute.
Yes, is that easy? start your journey in Java!
javac HelloWorld.java is ok But then
use
java HelloWorld
`
To run java program
java HelloWorld
(w/o .class extension)
[NOTE]
Tutorials for beginners http://www.javabeginner.com/
Compiling your java file using javac HelloWorld.java is fine but when your try run it do like this. java HelloWorld.
**
NOTE : Use only class name while running your compiled code.

Package name is different than the folder structure but still Java code compiles

I am using Notepad++ to write my Java code and Command Prompt to compile and run it.
Following is my sample Java code,
package abraKadabra;
public class SuperClass{
protected int anInstance;
public static void main(String [] abc){
System.out.println("Hello");
}
}
However, this file is in the following folder structure :
"usingprotected\superPkg" (usingProtected is a folder somewhere in the hierarchy in C:)
So, my package name here should be something like usingProtected.superPkg instead of abraKadabra as I wrote it.
But, when I compile this Java code from command prompt, it compiles fine with no error or warnings. Why is it so? Shouldn't the package name adhere to the folder structure?
And if it should, how would it adhere?
For e.g. if my package name is usingProtected.superPkg, will the compiler check in the reverse order. The present working directory should be superPkg, then the parent directory should be usingProtected and its done. Is it how it checks the folder structure with package name?
The Java language specification doesn't force files to be in a certain directory. It optionally allows the compiler to require that public classes are in files with the same name of the class, but I don't think there's anything similar for packages. Section 7.2.1 talks about possible storage options in a file system, but it doesn't say anything about enforcing source code structure, as far as I can see.
However, it's best practice - and a pretty much universally accepted convention - to reflect the package structure in the source directory structure... and javac will use this to try to find source files which aren't explicitly specified to be compiled.
Note that if you're compiling from the command line, by default each class will appear in the same location as the corresponding source file, but if you use the "-d" option (e.g. "-d bin") the compiler will build an appropriate output directory structure for you, rooted in the specified directory.
After experimenting a bit, I got the way how to use package name and run Java class files from command prompt.
Suppose following is my Java source file:-
package mySample;
public abstract class Sample{
public static void main(String... a){
System.out.println("Hello ambiguity");
}
}
This file is in directory "D:\Code N Code\CommandLine".
Now, when compile the source code (by going to the above directory from cmd) using following command:-
javac -d . Sample.java
This automatically creates "mySample" folder in my current directory. So, my class file Sample.class is present in directory "D:\Code N Code\CommandLine\mySample". Compiler created this new folder "mySample" from the package name that I gave in my source code.
So if I had given my package name to be "package com.mySample", compiler would create two directories and place my class file in "D:\Code N Code\CommandLine\com\mySample".
Now, I am still in the present working directory i.e. in "D:\Code N Code\CommandLine". And to run my class file, I give the following command:
java mySample.Sample
So, I give the complete hierarchy of package and then the class name. The Java Interpreter will search the current directory for "mySample" directory and in that for "Sample.class". It gets it right and runs it successfully. :)
Now, when I asked that why it compiles my wrong package source code, it would compile the code successfully though, but it gives NoClassDefFoundError when I run my class file. So above method can be used to use package names from command line.
If you're compiling a single class, javac doesn't need to look elsewhere for it. It'll just compile the file as is and put the resulting .class into the same folder. However, you generally won't be able to use the class til you put it into an "abraKadabra" directory in one of the directories in the class path.
If your class uses another class in the package, though, you might have problems compiling it where it is, for the same reason (javac wants to find the class and make sure it has the methods and such that your class uses).
Java compiler does not check the directory structure when it compiles source files. As you mentioned, suppose you have a source file that starts with the directive
package abraKadabra;
You can compile the file even if it is not contained in a subdirectory .../abraKadabra . The source file will compile without errors if it doesn’t depend on other packages. However, the resulting program will not run (unless also including package name in execution). The virtual machine won’t find the resulting classes when you try to run the program.

Categories