java relative path vs absolute path on command line - java

Running into an interesting problem
When I run:
$cd /projects/MyProject/
$java -cp . S3Sample
This works fine. However if I run:
$java -cp /projects/MyProject /projects/MyProject/S3Sample
Error: Could not find or load main class .projects.MyProject.S3Sample
Why is that. Did a quick look and can't find the answer. Thanks!

I have this folder structure:
- home
- org
- test
+ Foo.java
+ Foo.class
And the code in Foo.java is a simple hello world application:
//Note the usage of the package statement here.
package org.test;
public class Foo {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
Then, in command line, in order to execute Foo.class, I should provide the complete name of the class (I'm in "/home" folder in cmd):
$ java -cp "org/test;." Foo
Exception in thread "main" java.lang.NoClassDefFoundError: Foo (wrong name: org/test/Foo)
$ java -cp "org/test;." org.test.Foo
Hello world
Now, I edit the class above and remove the package sentence:
//no package specified
public class Foo {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
After recompiling the class and executing the same command lines:
$ java -cp "org/test;." Foo
Hello world
$ java -cp "org/test;." org.test.Foo
Exception in thread "main" java.lang.NoClassDefFoundError: org/test/Foo (wrong name: Foo)
TL;DR
Make sure to always specify the full name of the class. Check if your class belongs to a package. Specifying the path of the class to execute is the same as writing the full name of the class, java program will replace / by ..

You should run
$ java -cp /projects/MyProject S3Sample
The path for class is already CLASSPATH-relative

With java, you specify the fully qualified name of a class containing the main method you want executed. (The launcher will replace / with .). This class needs to be in the classpath. The argument is not a path to a file.

Related

GCJ throws error: "Undefined reference to main" when compiling

I´d wanted to compile a simple Java "Hello World" program like it was repesented on the GeeksforGeeks Hello World Tutorial, by using gcj in Linux Ubuntu. This is the source code:
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello, World");
}
}
But gcj threw two errors:
(.text+0x18): undefined reference to main
collect2: error: ld returned 1 exit status
Original output from the terminal:
gcj -o helloworld HelloWorld.java
/usr/lib/gcc/i686-linux-gnu/4.6/../../../i386-linux-gnu/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: error: ld returned 1 exit status
I´d take attention on the requirement, that the .java file should be named after the class which holds main:
Important Points :
The name of the class defined by the program is HelloWorld, which is same as name of file(HelloWorld.java). This is not a coincidence. In Java, all codes must reside inside a class and there is at most one public class which contain main() method.
By convention, the name of the main class(class which contain main method) should match the name of the file that holds the program.
What am I doing wrong?
You are missing the --main= option, from the documentation, this option is used when linking to specify the name of the class whose main method should be invoked when the resulting executable is run.
gcj -o helloworld --main=HelloWorld HelloWorld.java

Error while compiling a simple Java code

So I typed the very first example of Deitel&Deitel's How to Java book which is
public class Welcome1
{
// main method begins execution of Java application
public static void main( String[] args )
{
System.out.println( "Welcome to Java Programming!" );
} // end method main
} // end class Welcome1
Then I saved the file as test.java and went to its directory in cmd and typed Java test.java and I got the error Error: Could not find or load main class test.java.
What am I doing wrong?
You have two mistakes. Your class must match the file name. So move "test.java" to "Welcome1.java". Then you must compile it before you can run it.
javac -cp . Welcome1.java
Then
java -cp . Welcome1
First you have to compile the class with javac
javac Welcome1.java
Then you can call the class Welcome1
java -cp . Welcome1
The file name needs to be Welcome1.java. Class names and file names need to match.
Edit: And as others have mentioned you have to actually compile your code with the javac command before trying to run it with java.
Your class and Java file name must be the same. Like if you were to rename Welcome1 to test it would compile or rename the file to Welcome1.java it would compile.

Opening class in package from console in Java

So when i try to open a java class that's not in a package from the command prompt it all works fine, but when I try to open a class that's in a package it gives me NoClassDefFoundError.
And when I list the package when I try to open the class (java somepackage/someclass) it says that it can't load or find the main class.
Any help?
What I can infer is, you have two classes:
Test.java:
// no package defined here
class Test{
public static void main(String[] args){
System.out.println("Test");
}
}
so you can compile and run it using:
javac Test.java
java Test
Another class:
Test.java:
package test; // package defined here
class Test{
public static void main(String[] args){
System.out.println("Test");
}
}
And thus doing same thing gives you error.
For this you need to be in the parent directory of 'test' folder in your terminal or cmd and use:
java test.Test
No problem with compiler. You can compile as usual using javac Test.java from inside 'test' folder.
NoClassDefFoundError means that your JVM can't find your class at runtime. This could be because it's not visible (set to private or protected, or just no access modifier).
It could also be missing from your build path
package pkg1;
public class Dataguise{
public static void main(String [] args){
System.out.println("My name is Maninder Singh");
}
}
Suppose this is my code. My package name is pkg1.
1. First you need to create pkg1 dirrectory if not existed.
2. Run "javac Dataguise.java" command
3. It will generate the "Dataguise.class" file and move this file to "pkg1" folder
4. Now run "pkg1.Dataguise" command it will work.
I was having the same issue so sharing my experience.
What I assume is, you are creating a package and a class inside it, for example.
package com.vishwa.hello.commandLineArgs;
public class ComandLineArguments {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < args.length; i++) {
System.out.println("Command line arg is "+args[i]);
}
}
}
When I try to compile and run the above code in command prompt (from the package folder) as
javac ComandLineArguments.java.
java ComandLineArguments 123 456.
You get the below error:
Error: Could not find or load main class ComandLineArguments
Caused by: java.lang.NoClassDefFoundError: com/vishwa/hello/commandLineArgs/ComandLineArguments (wrong name: ComandLineArguments)
There are 2 ways to solve this:
Go to the root path of your project and then run.
java com/vishwa/hello/commandLineArgs/ComandLineArguments 123 456
789.
Command line arg is 123.
Command line arg is 456.
Command line arg is 789.
If you want to run the program from the package directory, you need to specify the class path along with the complete package
reference.
java -cp
/Users/16399/Documents/workspace-spring-tool-suite-4-4.12.1.RELEASE/CoreJava/src/
com/vishwa/ hello/commandLineArgs/ComandLineArguments 123 456 789.
Command line arg is 123. Command line arg is 456. Command line arg is 789.

'Exception in thread "main" java.lang.NoClassDefFoundError' when running java program from command line

What am I doing wrong here:
class Helo {
// main: generate some simple output
public static void main (String[] args) {
System.out.println ("Hello, world."); // print one line
System.out.println ("How are you?"); // print another
}
}
When I go into terminal I do:
cd ~
javac Atempt2.java (//that's the file name)
java Atempt2
and then it gives me this error message:
Exception in thread "main" java.lang.NoClassDefFoundError: Atempt2
So all in all this is what I do and what happens:
david-allenders-macbook-pro:~ davidallender$ cd ~
david-allenders-macbook-pro:~ davidallender$ javac Atempt2.java
david-allenders-macbook-pro:~ davidallender$ java Atempt2
Exception in thread "main" java.lang.NoClassDefFoundError: Atempt2
david-allenders-macbook-pro:~ davidallender$
I am very new at this so please explain things in a very simple manner.
Thanks.
Its been awhile since I've done any java work but I'm pretty sure your class name needs to match your file name.
javac uses the class name to generate the output not the filename.
So it will generate a Helo.class classfile.
java will take a class name and call the main function in the corresponding class file, here Hello.class.
The ClassNotFoundError is thrown because javac never generated an Atemp2 classfile as there is no Atemp2 class in your source file.
Rename your Atempt2.java to Hello.java to get going, then:
javac Helo.java
java Helo
See here for more discussion and the reasoning.
change:
class Helo
to
class Atempt2
in your source file.
A .java file that declares a class must have the file name match the declared class name.
The filename must match the name of the public class defined in the file. In this case, you would either have to name the file "Helo.java" or renamed the class to Atempt2.
This is the very basic to start with java programming.Any program you write the name of the file must match with the public class of the program.
Here in your program public class of the file is Helo so your file name must be Helo.java.Here the compiler is able to compile but JVM will search for Helo.class file to run. As there is no Helo.class file you are getting runtime Exception Exception in thread "main" java.lang.NoClassDefFoundError: Atempt2
to complement josefx's answer.
The argument to the compiler (javac) is the name of the file or files to compile (as you did).
On the other side, the virtual machine (java) gets the name of the class whose main method is to be executed.
One option would be
javac Atempt2.java // the file name
java Helo // the class name
Normally it is a good idea to have the file named the same way as the class. For public class this is a must (checked by compiler).

Java Command Line Trouble with Reading a Class from a Jar Archive

I am trying to run a java based tool using a command line syntax as the following: java -cp archive.jar archiveFolder.theMainClassName.Although the class I am searching for, a main class, "theMainClassName" is in the archive.jar and in the archiveFolder given at input, I keep getting the error that my class is not seen. Does anybody have any ideas concerning this problem? Thank you in advance
Here's a concrete example of what does work, so you can compare your own situation.
Take this code and put it anywhere, in a file called MainClass.java. (I've assumed a directory called src later. Normally you'd arrange the source to match the package, of course.)
package archiveFolder;
public class MainClass
{
public static void main(String[] args)
{
System.out.println("I'm MainClass");
}
}
Then run each of these commands:
# Compile the source
javac -d . src/MainClass.java
# Build the jar file
jar cf archive.jar archiveFolder
# Remove the unpackaged binary, to prove it's not being used
rm -rf archiveFolder # Or rmdir /s /q archiveFolder on Windows
# Execute the class
java -cp archive.jar achiveFolder.MainClass
The result:
I'm MainClass
How are you building your jar file? Is the code in the appropriate package?
Does theMainClassName class have the following package line at the top:
package archiveFolder
You need the class file to be in the same directory structure as the declared package. So if you had something like:
org/jc/tests/TestClass.class
its source file would have to look like this:
package org.jc.tests;
public class TestClass {
public static void main(String[] args) {
System.out.printf("This is a test class!\n");
}
}
Then you could use the following to create the jar file and run it from the command line (assuming the current directory is at the top level, just above org):
$ jar -cf testJar.jar org/jc/tests/*.class
$ java -cp testJar.jar org.jc.tests.TestClass
Perhaps with java -jar archive.jar?
Of course, it supposes the manifest points to the right class...
You should give the exact message you got, it might shed more light.
EDIT: See Working with Manifest Files: The Basics for information on setting the application entry point (Main class) in your jar manifest file.
Usually this happens when a dependent class (static member) is not found - like this, using log4j:
public class MyClass {
private static Logger log = Logger.getLogger("com.example");
}
The reason is that the initialization of such a static member can be understood as part of the class loading - errors causing the class not to be available (loadable), resulting in the error you described.
Static constructors are another possible reason:
public class MyClass {
static {
// <b>any</b> error caused here will cause the class to
// not be loaded. Demonstrating with stupid typecast.
Object o = new String();
Integer i = (Integer) o;
}
}
I think others have covered some common stuff here. I'd jar tf the jar and make sure the class is listed. I'd also double-check that the class is public and the method is "public static void main(String[] arg)".

Categories

Resources