How to compile and run a Java class (Hello World example) - java

I am new to Java. I wrote a simple program that prints "Hello World". My program compiled but did not run but gave me this exception:
Exception in thread main java.lang.NoClassDefFoundError:Hello wrong name : main hello
My program is like so:
package main;
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
My program is in: \main\Hello.java
I searched so much and compiled in different ways but i don't understand what the problem is. Can anyone help me?

You should have the Hello.java under main directory as per the package definition.
So do the following.
d:>mkdir main
d:>move Hello.java main
d:>javac main\Hello.java
d:>java main.Hello
Which would print Hello World. This is because javac will output the .class file next to .java file by default.
If you don't want this behaviour or if you don't want to move the .java file, then you can also mention where the output classes needs to go.
d:>javac -d . Hello.java
This would create the Hello.class automatically under main directory as per the package definition in relevance to the current directory. Hence,
d:>java main.Hello
Which would also print Hello World
You can learn more about how to compile java source code here

Related

How to access other files in any editor?

For example I have Main.java and test.java. test has public static int bro = 5; so i try to print test.bro from Main but the class test is not found. An IDE like Eclipse takes care of this for me but how do I do this with an editor? Sorry noob question. I'm in cmd in the directory of deez files and i type javac Main.java, den java Main. Thanks.
file Main.java:
public class Main {
public static void main(String[] args) {
System.out.println(test.bro);
}
}
file test.java:
public class test {
public static int bro = 5;
}
So suppose you have two source files: Main.java and test.java then you need to compile them first.
You can do it via command javac Main.java test.java. That command will produce 2 files in your current directory: Main.class and test.class. Which contain compiled java code.
Now you need to run your main class with classpath which contains both of your classes. So you need to run command java -cp . Main. Where . represents directory with your compiled classes.

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

Trying to understand how to create a jar file that opens terminal and takes in a argument

I finished creating a program but I was told that my program
must be a Java application that takes as a command line argument the name of the file."
I understand I can use the jar command in terminal but I don't undestand how you open the terminal and take a file name as a argument. I was wondering if someone could explain what code is required to do this.
Thanks alot.
I tried creating a basic jar file in terminal with the line "jar cvf findOptimalTransport.jar ." but the jar file does not open, I think its because the current implementation takes the users input with a scannar in the code and prints via the terminal. However, this wont work because a terminal window is not opened with this command.
It doesn't have to be a jar file. Command line arguments can be entered from the command line, when you run your application.
Let me give you an example, about how this works. Let's say you have the below simple Java application:
public class MyApplication{
public static void main(String[] arguments){
System.out.println("Hello World!");
}
}
That public static void main() is a method; and more specifically the main method of your application which is what is executed when compiled and ran.
To compile and then run it, you type in the command line/terminal:
javac MyApplication.java //this will compile it
java MyApplication //this will run the main method of MyApplication
But what is that parameter in the main method? What is String[] arguments ?
When you run your program, whatever you type after the application name is an argument, of type String and it is stored in the String array String[] arguments (or most commonly String[] args).
What this means, is that, if you execute your application like this:
java MyApplication some_file.txt // Run application with one arg.
You can access that argument like so:
public class MyApplication{
public static void main(String[] arguments){
System.out.println("Hello World!");
System.out.println("You entered: " + arguments[0]);
}
}
Output:
Hello World!
You entered: some_file.txt
Note: To run a jar file, you need to navigate to the folder that the jar file is in and from the command line you can run it by typing:
java -jar <jarname>.jar

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.

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