Create Object of class in same package - java

I created a class HT17
package useFul;
class HT17
{
void show()
{
System.out.println("Hello World!");
}
}
And i tried accessing it from another class from same package
package useFul;
class HT18
{
public static void main(String[] args)
{
HT17 h =new HT17();
h.show();
}
}
But i am getting error: Cannot find symbol HT17
Yes, They are in same directory i.e useFul
A solution would be helpful!

At first create a folder named useFul and copy the classes there, then cmd to compile and run. cmd command:
javac useFul/HT18.java
java useFul/HT18

Most likely you are using javac <file name> this will create the class file in the same folder even though you have a package defined.
So you've to use javac -d . option this will create proper folder structure for the classes. Try the following.
$ javac HT17.java -d .
$ javac HT18.java -d .
$ java useFul.HT18
The -d is used to mention where to create the compiled classes with proper folder structure using package. in the example . is used, means use the current directory.

Related

Execution of Java class file

When I try to execute a java file within a package, the integrated terminal can't find the class file. How should I configure vscode or the command to automatically add the packages on the command like java package.File or search the class file automatically? I'm using Code Runner extension with this command: "java": "cd $dir && javac -d \"$workspaceRoot/java/bin/\" $fileName && cd \"$workspaceRoot/java/bin/\" && java $fileNameWithoutExt. This works when the java file isn't in a package.
You need to have java run as <package>.ClassName. For example, if your class looks like this:
package com.something;
class Something {
public static void main(String[] args) {
System.out.println("Hello World");
}
};
And you run javac with the following:
javac -d . Something.java
Then, you need to make sure that java knows which package you want to run:
java com.something.Something;
In other words, you need to explicitly tell java what package your main class is in.
Basically, you need to create another variable inside of vscode that allows you to add the package to the beginning of the command:
"java": "cd $dir && javac -d \"$workspaceRoot/java/bin/\" $fileName && cd \"$workspaceRoot/java/bin/\" && java $filePackage.$fileNameWithoutExt
Unfortunately, it doesn't look like https://github.com/formulahendry/vscode-code-runner has a java package variable already defined, so it's something you'd have to either create by downloading the source of the package and hacking it, or requesting a variable from the package author at https://github.com/formulahendry/vscode-code-runner/issues
Update:
It looks like this is already an issue in the CodeRunner package: https://github.com/formulahendry/vscode-code-runner/issues/118. You might want to watch this issue for updates and upgrade your extension when it is fixed.
As a temporary workaround, I think just not specifying a package for your main class will work. All other classes are going to be using import anyway, so it doesn't matter for those, but keep your main class in the top-level package and VSCode Code Runner should work as expected.

Javah tool error: could not find class file for HelloWorld

I am trying to create a header file using javah tool from the command line and an external tool configuration on eclipse on windows 7 OS but it's not working.
My code is:
package mypackage;
public class HelloWorld {
private static String HelloWorld;
private native void print();
static {
System.loadLibrary(HelloWorld);
}
public static void main(String[] args)
{
new HelloWorld().print();
}
}
I have followed different ways and even read the documentation of javah tool from Oracle, but they didn't help to overcome this problem.
My class file (HelloWorld.class) and java file (HelloWorld.java) both are in C:\..\eclipse-workspace\Distribution System Process\src\mypackage
But whenever I run javah tool, it gives me an error:
could not find class file for HelloWorld or mypackage.HelloWorld
I tried by providing classpath as well, but am not getting any header file.
Note: I have two classes in my package. The Frame1.java is the main class, which is the Gui, and the other class is used for JNI and called HelloWorld.java. I am not sure if the classes matter, but I am currently working on HelloWorld.java to create a header file:
What is causing this failure? :(
javah tool requres access to compiled code. You have to provide place, where your compiled class is.
Take a look here for a very simple sample code:
http://jnicookbook.owsiak.org/recipe-No-001/
As you can see, sources are compiled and stored inside some other place (here it is called target)
${JAVA_HOME}/bin/javac -d target java/recipeNo001/HelloWorld.java
${JAVA_HOME}/bin/javah -jni -d c -cp target recipeNo001.HelloWorld
Then, you have to tell javah where to find these files (compiled Java classes). It is done by -cp argument.
Argument -d, on the other hand, will tell javah where to store C headers.

How to access another class in another package?

I have 2 classes, each is on different folders
Main class src/mainclass/Main.java
Display class src/swingclass/Display.java
Main Class:
package src.mainclass;
import src.swingclass.Display;
public class Main{
public static void main(String[] args){
Display sM = new Display();
}
}
Display Class:
package src.swingclass;
public class Display{
public Display(){
System.out.println("Display class");
}
}
i run it on cmd and it is stated
error: package src.swingclass does not exist
and also, Main class could not see Display class.
overall, i have 3 errors.
I know that using IDE will make this easier, but i want to learn this on cmd. I followed the tutorials on net, but it still has errors.
I believe you should get rid of the src part of the package, i.e.
package swingclass;
...
and import it like:
import swingclass.Display;
Remove all occurrences of "src." in all files
Change to the src directory
Type: javac mainclass/Main. java
Type: javac swingclass/Display.java
Type: java mainclass.Main
Go to the src folder level (go inside src folder) in your command prompt, and use the commands
javac -classpath . src/mainclass/Main.java
to compile (this will implicitly compile the Display class as well, since it is required by Main class) and
java -classpath . src/mainclass/Main
to run the Main class.
. indicates the current directory (in your case, src folder) relative to which the other paths (to source/class files) are then specified.
javac -d bin -sourcepath src <path to main class from src directory, in your case it will be one folder up from src/mainclass/Main.java>
java -cp bin src.mainclass.Main (set class path to bin root where class files are, scr is where your package starts)
Using the -classpath flag should help you solve your problem.
javac -d "theClassPathNameYouWant" "src/swingclass/Display.java"
javac -d "theClassPathNameYouWant" "src/swingclass/Main.java"
java -classpath "theClassPathNameYouWant" swingclass.Main

Run from command line, Wrong Name error

I want to run a Java project from the command line which I start using a batch file, but I get the wrong name error.
The directory setup:
srcMVC
bin (folder with .class files)
src (folder with .java files)
Batch file
Batch file:
set path=C:\Program Files\Java\jdk1.7.0_09\bin
javac src\model\*.java -d bin -cp src
javac src\controller\*.java -d bin -cp src
javac src\view\*.java -d bin -cp src
javac src\main\*.java -d bin -cp src
PAUSE
java bin\main.Main
PAUSE
Compiling works, but I get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: bin\main/Main (wrong name: main/Main)
Any suggestions?
package main;
// omitted imports
public class Main {
// omitted variables
public static void main(String[] args) {
// omitted implementation
}
}
The following statement resolved my error:
java -cp bin; main.Main
NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time.
For example if we have a method call from a class or accessing any static member of a Class and that class is not available during run-time then JVM will throw NoClassDefFoundError.
By default Java CLASSPATH points to current directory denoted by "." and it will look for any class only in current directory.
So, You need to add other paths to CLASSPATH at run time. Read more Setting the classpath
java -cp bin main.Main
where Main.class contains public static void main(String []arg)
you are wrongly exicuting java bin\main.main
main() is your main method but you should supply java interpreter the Class Name which implements main()
So if your class name is Test and file name is Test.java which has main() method
java Test
if your Test.java/Test class in is package my.test e.g - package com.my.test;
than, java com.my.test.Test
hope you got it !!
java bin/main.Main is wrong, you must specify -cp here:
java main.Main -cp bin
Here the first argument is the class name which should be found in the classpaths, rather than the class file location. And -cp just adds the logical path to classpaths. You should make the root of your project searchable in the classpath.
and for those javac commands, you have already specified the correct path, so you don't need -cp src. The difference here is the javac command uses logical path for .java files, while using java command you could only specify the path in -cp attribute.
You could also execute java main.Main without -cp if you enter the directory bin:
cd bin
java main.Main
Since the current path will be automatically be searched by java as a classpath.
Assuming you have a class called Main you have to run it with this command:
java bin\Main
It will call your main method.
Java run time (in your case the java.exe command), takes the class file name that containst the main() method as input. I guess you should be invoking it as "java bin\main" assuming there is a main.class which has a public static void main (String[]) method defined.
Note: General practice is to capitalize the first literal of any class name.

I have managed to compile java-program but I cannot execute it

I have just installed JDK on Windows Vista. After that I set proper values for the 4 environment variables: classpath, include, lib, path. After that I was able to compile my HelloWorld-program (I got a *.class file). But when I try to execute the compiled program (I type java HelloWorldApp) it does not work. The Java write a lot of stuff and in the end it is written that it "could not find the main class: HelloWorldApp". Can anybody, pleas, help me with this problem?
Just for clarity; you are saying that you have a class in the default package, that is you have not included a package specifier in the Java file, and your class is called HelloWorldApp. When you compiled this, you got a classfile HelloWorldApp.class in the current directory.
Assuming the above to be true then try:
java -cp . HelloWorldApp
For example, the following works on a unix box:
$ echo 'class HelloWorldApp { public static void main(String []argv) { System.out.println("Hello World!"); } }' > HelloWorldApp.java
$ javac HelloWorldApp.java
$ java -cp . HelloWorldApp
Hello World!
Of course, you should indent your code a little nicer than just shoving the whole thing onto one line ;-)
Edit: To answer the comment:
Normally, the default classpath is the runtime libraries and the current directory. However, if you have the CLASSPATH variable set, then this will override the default, and you need to explicitly set the classpath back to its "default value". To verify if the CLASSPATH environment variable is set, you can do (again assuming unix):
set | grep CLASSPATH
If it is set, that is why you need to manually include . on your classpath.
create a file called HelloWorld.java;
paste the code posted below inside HelloWorld.java:
compile it by executing the command: javac HelloWorld.java in the same folder as HelloWorld.java is in;
execute the code by doing: java -cp . HelloWorld in the same folder as HelloWorld.java is in.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("HelloWorld works!");
}
}
How the classpath works, can be read here: http://en.wikipedia.org/wiki/Classpath_%28Java%29
Have you included . and .. in your path? Just for clarification . represents your current directory and .. represents your parent directory. You are telling that the java has to search the current directory and the parent directory to find the class. Add the same to your classpath too.
What happens if you use:
java -cp {path to directory with HelloWorldApp in it} HelloWorldApp
That path should be contained within your CLASSPATH environment variable. Is that exported to your command shell ? Do you need to start a new command shell to get the most recent version of CLASSPATH ?
Post your code. I believe the problem is that your main class is not defined properly. I did this the other day.
public static void main(String[] args){
//code
}
The class path concept and the logical difference between Java source code and compiled byte code is notoriously hard to get right.
I would strongly recommend you familiarize yourself with the Sun Java Tutorial. The relevant section is
http://java.sun.com/docs/books/tutorial/getStarted/cupojava/win32.html

Categories