command line error when trying to use java package - java

I'm learning java packages in school and I'm able to create and use my package on netbeans perfectly but cannot do it from the lubuntu command line. I get an error: could not find or load main class. Here is the code but I know this is not the problem since it works perfectly in netbeans
package animals;
public class MammalInt implements Animal
{
public void eat()
{
System.out.println("Mammal eats");
}
public void travel()
{
System.out.println("Mammal travels");
}
public static void main(String args[])
{
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
package animals;
interface Animal
{
public void eat();
public void travel();
}
I first compile Animal.java and put the Animal.class file into a directory
animals. I then compile MammalInt.java. If I do not put the Animal.class file in a animals directory it will not compile MammalInt.java . After I have both class files into the animals directory I do java animals/MammalInt and get the error: cannot find or load main class. I also have doe java MammalInt and get the same error. This is really frustrating. Please help.

When compiling (a set of files) you need to use the path.So use /
javac animals/*.java
When running the Java class, you need to specify the Java name of the class.
In your case this is done as follows:
java animals.MammalInt
This says you want the class MammalInt in the package animal. Depending on your installation you also need to add your current directory to your classpath (this is where java looks for .class files), resulting in:
java -cp . animals.MammalInt
Note that you run all commands from the root of your source code tree. This means the directory that contains the directories for your packages. So if you have the following direcotries:
project/
project/animals/
project/animals/Animal.java
Then run the commands from the project/ directories.

Related

How to add directory to class path in ubuntu?

Suppose i have a directory "Animal" (without quotes) and i have java classes in it.How to add that directory to class path in Linux ? I mean suppose i want to use class files in "Animal" directory from some other folder , then i need to add "Animal" to class path .How to do it ?
Also suppose Animal directory has several sub directories and each of the sub directories also have directory having java class files .Then how to add each of them to java package ?
edit : Suppose i have two folders in Ubuntu say Downloads and Documents .Now in Downloads i created a folder called "animal" having a class named Dog.java . Now in Documents folder i created main method in which i try to make an instance of "Dog" class .I want to do it by importing the package "animal" in Download folder. How to do it ?We know that if we want to use some pre-built package in java then we import that package to use classes inside that package .Similarly suppose i want to import my own package , what i need to do ? When i write import and compile then it says package "animal" does not exist .So what i do so that it doesn't gives compilation error .Can some one elaborate by giving an answer .
I did lot of work before asking this question and when i was unsuccessful i finally asked this question .
To work this out in detail, with some code- the folder structure is:
~ (user folder)
~/Documents
~/Documents/useanimal
~/Documents/useanimal/UseDog.java
~/Downloads
~/Downloads/animal
~/Downloads/animal/Dog.java
The code for the two classes is below. To compile:
cd ~/Downloads
javac animal/Dog.java
cd ~/Documents
javac -cp ~/Downloads useanimal/UseDog.java
To run:
cd ~
java -cp Documents:Downloads useanimal.UseDog
and it will output
UseDog:main
Dog created
Code:
animal/Dog.java
package animal;
public class Dog {
public Dog() {
System.out.println("Dog created");
}
}
useanimal/UseDog.java
package useanimal;
import animal.Dog;
public class UseDog {
public static void main(String[] args) {
System.out.println("UseDog:main");
Dog dog = new Dog();
}
}

Trouble running java app from cmd

I have two files, app.java and test.java
They both reside in the same package, and they compile just fine with "javac app.java test.java"
Two class files are then created.
However, when I go to run them with the command "java app" because app has the main method, I get "Error: Could not find or load main class app"
app.java:
package working_directory;
public class app {
public app() {
}
public static void main(String [] args) {
test testing = new test();
System.out.println(testing.calculate(60));
}
}
This Is the test.java
package working_directory;
public class test {
public test() {
}
public int calculate(int x) {
return (int) x * x * x;
}
}
Make sure to choose the right path for compilation and running code:
D:\
+--Folder(start cmd here)
+---working_directory
+----app.java
+----test.java
How to compile
D:\Folder\>javac working_directory\*.java
How to run
D:\Folder\>java working_directory.app
To use the java command, you must specify the fully qualified name of the class you want run. This means that you need to specify the package name as well.
You should run this:
java working_directory.app
Since working_directory is the package name.
You must provide a classpath, when running it from command line:
(for windows)
java -classpath . app
You have a package name declared in other words that's a folder. Your project should look like this then
C:\YourProject
C:\YourProject\working_directory
C:\YourProject\working_directory\app.java
Your Project starts at root level so it's C:\YourProject there you have to use the command line and type java working_directory.app

How to compile and run a java class with a package

I have a class called MyClass in the file MyClass.java file (code mentioned below)
package myclass;
class MyClass {
public int add (int a, int b){
return a+b;
}
public static void main(String args[]) {
MyClass obj = new MyClass();
System.out.println(oobj.add(2, 3));
}
}
I am compiling the class with
javac MyClass.java
But I am trying to run the class using
java MyClass
or
java myclass.MyClass
I am getting the Error
Error: Could not find or load main class MyClass
But, I am able to run this program if I omit out the package name.
where am I going wrong?
Make sure that you are inside the parent directory of the package folder (the folder in which your compiled class file is), and execute the following command:
java myclass.MyClass
Below is an example file structure:
bin
-> myclass
-> MyClass.class
In the example structure above, you would have to execute the command from the "bin" directory.
Also, define the class as public and recompile the java source file.
I ran into this too. It's very frustrating for someone from other languages. The key here is, the java file has to be in the right directory depending on the package declaration.
if the java file Test1.java starts with
package com.xyz.tests;
Then the java file Test1.java needs to be in directory com/xyz/tests
You can compile and run as
javac com/xyz/tests/Test1.java
java com/xyz/tests/Test1
Good luck.
You Need To Compile The Class using :
javac -d ./myclass
I get my example to run by
java <package>.<class>
From parent directory of package

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.

Compiling From Command Line Wth Circular Dependencies

Imagine that I have two classes (shown below). Now imagine that I am compiling them using javac.exe from the command line. They won't compile because class A needs class B's methods to exist and vice versa. Is there any trick to getting them to compile from the command line? (Eclipse can compile this no problems!)
I should add they are both currently in two separate .java files.
public class A {
public void doAWork() { /* A work goes here. */}
public void doBWork() { new B().doBWork(); }
}
public class B {
public void doBWork() { /* B work goes here. */}
public void doAWork() { new A().doAWork(); }
}
It looks like your issue is elsewhere.
I can perfectly compile the code in Java 1.5, 1.6 and 1.7 with the following command:
javac A.java B.java
Even providing a single file name works perfectly, since B.java is in the same directory:
javac A.java
Are you sure the two files are placed in appropriate directories?

Categories

Resources