Running Java Program from Folder Mac with Terminal - java

So I'm used to creating a single Java file and putting it into the desktop and running it from the terminal on mac (cd Desktop/, javac HelloWorld.java, java HelloWorld). Now I have a program that has multiple classes. My question is how to run a program from a folder. I have around 5 .java files in my folder and I need to run the one with the main class.

Writing multiple classes in single file or writing them in different .java files changes nothing. Finally, you have no. of .class files equal to no. of classes you have defined in your .java files.
The JVM checks for the public static void main(String[] args) in your class file to run the program(BTW you can also overload it but the above one is what is called first). You can also write main() method in every class. I believe that's why you use class name to run the program like java HelloWorld.

You should just use the name of the entry point class instead of HelloWorld, other classes will be compiled and used automatically.
The entry point class is the one that contains method
public static void main(String[] args)

Related

how to run jar files depend on jar files

my program consist of
"javax.mail.jar"
and a simple myProgram.java (Contain Main class) ("package:com.test.myprogram")
and anotherProgram.java (contain Main class) ("package:com.test.myprogram")
I have converted it to "myprogram.jar" file
how do I run "myProgram.java" in shell? using "myprogram.jar"
If your application is in (say) "myprogram.jar" and it depends on "javax.mail.jar", then you would run it like this:
$ java -cp myprogram.jar:javax.mail.jar com.test.myprogram.Main
(On Windows, you need to use ; instead of : as the classpath separator.)
However, it doesn't make a lot of sense to have "myProgram.java" and "anotherProgram.java" BOTH declare a Main class ... by which I assume you mean a class called Main. The problem is that since both versions of the Main class are in the same package, compiling one source file will overwrite the Main class produced when you compile the other source file.
java -classpath yourjarfilename.jar yourpackagename.classname

When should I set class path?

public class a {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
For the above code, I can run it by javac a.java, and then java a.
But if I add a package for it:
package hello;
public class a {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
I need add the classpath -cp in order to run it: java -cp ../ hello.a
Why I do not need to set the classpath in the first situation? When do I need to add -cp?
To answer your question
When should I set my classpath
Always, as you work on more complex projects you will find that your classpath will almost always need to be set. This will either be done manually like you have done with -cp command or by your IDE.
To answer your second question
Why I do not need to set the classpath in the first situation
I first need to explain a little bit about classpaths. In short classpath exist to tell the VM where to look for your files. In the first situation since you didnt have a package the default location was used to find your class so no classpath was needed. However when you complicated things and added a package at this point a classpath is needed
The classpath is where java (the program) looks for classes. The default contains a bunch of system-wide things (for the JDK), and then also the current directory: ..
Without the package line, your class was in the "default package," which is basically no package. This means its full name is a (more or less), and java will look for it in a file called $CP_ELEM/a.class for each element CP_ELEM in the classpath. In the default case, that amounts to ./a.class, which is fine because that file exists.
With the package line, your class is in the hello package, and its full name is hello.a. That means that java will look for it in $CP_ELEM/hello/a.class, which amounts to ./hello/a.class -- which doesn't exist. But if the directory you're in happens to be called "hello", then java -cp .. hello.a, which amounts to looking in ../hello/a.class, will work.
Classpath is like telling the system where to find my classes:
If you don't have a classpath the java will try to load the class
from the default directory (Probably where you're running the command at).
Now let's say you put your compiled classes in folder "bin" and sources in "src" folder
To tell the system to load the classes from "bin" folder you have to give him the following parameter:
-cp bin;
Also i see you don't understand the packaging system in java so here's fast explain:
Packaging is like you the directory of your class for example:
If you set the class's package to package a; and your classpath directory is set to "bin"
You have to create folder called "a" in "bin" folder, and then move the compiled class there, do the same for the source file, but in "src" folder
Just saying you could use eclipse which is located at : http://www.eclipse.org
If this didn't help you, Then take a look at this: https://www3.ntu.edu.sg/home/ehchua/programming/java/J9c_PackageClasspath.html

Running Java builds with packages defined from Eclipse

I am fairly new to Java and wrote simple a program to strip unwanted contents from a CSV export.
The top of the program looks like this:
package csv;
import java.io.*;
import java.util.*;
public class csvstrip {
public static void main(String[] args) throws Exception {
Eclipse automatically builds the csvstrip.class in a folder {workspace}\bin\csv. However, whatever I type into command line (running it using the java command), I get the following:
Error: Could not find or load main class csvstrip
If I remove the package declaration from the code, Eclipse asks if you wish to move the csvstrip class to the default package and builds the the class a level up in the folder {workspace}\bin. Now, on entering
java csvstrip
the program functions fine. Before removing the package csv declaration, I tried:
java csv.csvstrip
java csvstrip
from both the bin and bin\csv folder but nothing seemed to run. What piece of information am I missing here? If you define a package for your code, from where in command line are you supposed to run the java command and how should your program be referenced?
I presume that you are trying to run the class file from top level or default package folder.
java will obviously throw you 'Class Not Found' error, because you are looking in the wrong directory.
trying running.
java .\csv\csvstrip
in the assumption that you are in the present working directory which contains csv folder within which you have csvstrip or try giving the complete path.
In your configuration you should be able to start your class standing in the bin folder and typing
java csv.csvstrip
...or...
java csv/csvstrip
should also work just fine
If you are on a windows machine please double check the case of your class file and of your package folder. Windows is case insensitive java classloader isn't.

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.

running a java program in a unix terminal

I have a java program with multiple class files and they are all stored in the same folder called lab7. I coded the project in NetBeans so used "package lab7" in all the files. My main application java file is called lab7.java. Now, when i try to run this on the terminal i get "Exception in main thread: NoClassDefFoundError". I do the following inside the folder lab7.
javac *.java
java lab7
I don't know why get this error. It should be some basic class path error. Thanks for the help.
Normally class names should start with a capital letter. So you should rename your main class to Main. If it's inside the lab7 package, run this:
java lab7.Main
This should be run in the directory that contains the lab7 directory. So if you're in the lab7 directory itself, go up one level first.
Use
java lab7.lab7
You do have a lab7.java file with a public static void main(String[]) method, right?

Categories