I have been reading many answers about the different between the compile time and the runtime in Java. But I am still not clear. Some answers said: the compile time is the period when you, the developer, are compiling your program or code. My question is when do I compile my program or code? For example: I open my IDE, eclipse or netbeans, write code in different classes and click on Run button and my application opens. Can someone explain me when did I compile my program/code in this sample process? or when was I in the compile time stage in this sample process?
When you write any java class,extension of file must be .java. Let take simple java class to print Hello World :
public class Simple {
public static void main(String[] args) {
System.out.println("Hello World !!");
}
}
So save this file as Simple.java.
Now open the cmd,lets say file saved in d:\test directory
d:\test>javac Simple.java // When you run this the .java is converted into byte code and it is saved in .class file.
d:\test>java Simple // JVM will execute the byte code file i.e. Simple.class
Note : All this process is done by IDE internally
Do this. Open notepad. Type in :
class Sampl{
public static void main(String []args){
System.out.println("hi from run time");
}
}
Save it as Sampl.java
Save it in a new folder without spaces - say c:\j\academic or ~/j/academic if on linux
Now open a command promot, figure out path to your JDK and type in
cd c:\j\academic
dir
Should see just Sampl.java
javac Sampl.java
dir
Should see 2 files :
Sampl.java and Sampl.class
That's you byte code
Now you can move or even delete Sampl.java and can still run Sampl.class from command line using
java -cp . Sampl
So you notepad and .java time was coding time. On command prompt was compile and run time
javac is the java compiler
java.exe is the runtime app that loads and runs our classes
[When runing jboss or other app container we run java with the jboss main class, and its calsses load and run ours]
These search results should help too google java tutorial command propmpt
There is a very important thing you may not have fully understood yet, namely that the text you type - which in this case makes a Java program - is not on the form of the instructions that the CPU is executing millions of every second - which for Java is Java Byte Code, and which needs to be present for the JVM to execute your program.
The transformation of the Java source code you wrote into the corresponding Java Byte Code, is done by a so-called Java compiler. There is nothing magical about a compiler as it is just a program which can read in text and generate the corresponding byte codes, and it is a standard assignment for computer science students to write one (but usually for smaller languages than Java).
If you write your programs in a standard text editor (not an IDE) and save to disk, you need to manually invoke the Java compiler by running javac on your Java sources. One of the advantages of IDE's is that they usually do the compilation automatically - either immediately when you save your file or when you want to run your program - but it makes it a bit more magical what goes on.
(Note: This transparent compilation step in an IDE becomes very useful when debugging in i.e. Eclipse, as it allows for updating the code being executed without having to restart the debug session from scratch.)
Related
I have started learning algorithm in java, but there are lot of things getting in my way unlike python or ruby. I wanted to well structure my source code for future references, here is my directory structure.
~/workspace/algorithms/
|---searching/BinarySearch.java
|---sorting/InsertionSort.java
The InsertionSort.java file consists of this package:
package algorithms.sorting;
class InsertionSort {...}
I am able to compile my java source but I am having trouble running the program. I may also need to import code from any package inside algorithms to any package.
How to compile and run programs keeping my package structure intact from vim or command line? what should be my current directory while running commands?
PS: I am a vim user and don't want to abandon it just for the sake of Java.
Your classpath should point to ~/workspace. Then on the command line enter:
> java algorithms.sorting.InsertionSort
This will call the main() method of your InsertionSort class.
I just started Java today and I am getting a NoClassDefFoundError when I run my code:
class Example {
public static final String greeting = "Hi there";
public static void main(String[] args) {
System.out.format("%s", Example.greeting);
}
}
Above is the contents of my example.java code. This code compiles fine in the Eclipse execution, but when I try to run example.java by itself, it fails. Eclipse also created some .class file when I ran this program, but that doesn't make much sense as to why it would fail if I ran the .java by itself in a different directory as all the information of the class Example is found in the .java file itself.
Does Java need the .class file to compile and run despite having the class itself defined in the program and why? I also built the .java file through terminal and it worked fine
Compilation and execution of a Java program is two step process:
During compilation phase Java compiler compiles the source code and generates bytecode. This intermediate bytecode is saved in form of a .class file.
In second phase, Java virtual machine (JVM) also called Java interpreter takes the .class as input and generates output by executing the bytecode.
So yes .class file is essential for execution of the code. .java file is text that you write, but not what the machine can interpret.
Here is the flow diagram of what happens:
To look at it in more depth:
When your Java project builds, it translates the source code (contained in *.java source files) to Java bytecode (most often contained in *.class files). This takes your high-level code one step closer to machine code, but not quite there yet. This bytecode is a collection of compact instructions; easier for a machine to interpret, but less readable.
When you run a Java application on your computer, cellphone, or any other Java-enabled platform, you essentially pass this Java bytecode to the Java Virtual Machine. The interpreter in the Java Virtual Machine usually starts compiling the entire bytecode at runtime, following the principles of so-called just-in-time compilation. This makes for the typical, albeit often slight delay when opening a Java application, but generally enhances the program performance compared to interpreted compilation.
Does Java need the .class file to compile and run despite having the class itself defined in the program and why
The compiled output of a java file (class) is .class file. It contains the bytecode of the program which is run by the JVM. So .class files are required to run the program.
I also built the .java file through terminal and it worked fine
Even through the terminal, when you compile the .java file (class). It creates the .class for each class declared in the .java file. Then you execute the class which contains the main method. The main method is the entry point for the JVM.
For example:
File name: example.java
Compile code: javac example.java
Output is .class file: Example.class. Because name of the class is Example.
Run the program: java Example
Error in your code. Looks like this has been updated in the question.
System.out.format("%s", Student.greeting);
Name of the class is Example not Student. it should be:
System.out.format("%s", Example.greeting);
So I have a java project with multiple java files.
I know that is almost straight forward to start a java application using batch file. But that is for a pretty simple java program with a single class.
However I am wondering if it is possible to do that with in a scale of a project that you usually create using eclipse. A large project with multiple packages, classes and multiple java files.
My try was to write a script and apply on the main class as following
set path = C:\Program Files\Java\jdk1.7.0_25\bin
javac -classpath twitter/twitter4j-stream-3.0.5.jar;twitter4j-core-3.0.5.jar" sourcepath="lib/twitter4j-core-4.0.1.jar;lib/twitter4j-core-4.0.1.jar;lib/twitter4j-stream-4.0.1.jar;svm_light_lib Program.java
java Program
However when I start the .bat file it automatically closes.
Any Ideas ?
Thanks in advance
First, never overwrite the environment variable path, not even
temporarily. Append your folder instead: set "path=%path%;%mypath%" or set "path=%mypath%;%path%".
(There exists a particular path command but I'm not sure about right syntax: path=%path%;%mypath% with = assignment or path %path%;%mypath% without it).
Use full path to a program if you know it, e.g. "%mypath%\javac".
For better readability, values for -classpath and -sourcepath options are stored to the environment variables mycpth and mysrcp, respectively. Note and use proper " quotation and no spacing around = to avoid any leading and trailing spaces in all set commands.
pause to see all the javac output. Displays the message Press any key to continue . . .
Next code should be (syntax) error-free. However, success depends (among others) on classpath and sourcepath entries visibility as well...
set "mypath=C:\Program Files\Java\jdk1.7.0_25\bin"
set "path=%path%;%mypath%"
set "mycpth=twitter/twitter4j-stream-3.0.5.jar;twitter4j-core-3.0.5.jar"
set "mysrcp=lib/twitter4j-core-4.0.1.jar;lib/twitter4j-core-4.0.1.jar;lib/twitter4j-stream-4.0.1.jar;svm_light_lib"
"%mypath%\javac" -classpath "%mycpth%" -sourcepath "%mysrcp%" Program.java
pause
java Program
However I am wondering if it is possible to do that with in a scale of a project that you usually create using eclipse. A large project with multiple packages, classes and multiple java files.
Of course it is possible!
In this case, I suspect the problem is that you java command doesn't have a "-cp" argument. The java command is probably failing because it can't find twitter classes ... at runtime.
Remember to include "." on the classpath ... or else java won't find the file that you just compiled.
#JB Nizet's suggestion is also very important advice for finding out what is actually happening.
I know this question has been asked loads of times before, but I'm a rookie programmer and despite trying many of the solutions on this site I still can't fix this issue. I'll be really thankful if you can take the time to figure out what I've done wrong.
Operating system: Windows 8
Java version: 1.8.0 update 25
The command prompt I'm using is the one that comes with Windows. (I'm presuming there are other types so I'm just making it clearer.) The code's a really basic one.
package com.thefinshark.intro;
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome.");
}
}
So, first I changed the directory to C:\javawork, where Welcome.java is saved. I set the path to C:\Program Files\Java\jdk1.8.0_25\bin, then compiled the code. The compilation seemed fine, I found the Welcome.class file in the C:\javawork as well. The execution, however, kept returning "Could not find or load main class Welcome". I've tried C:\javawork>java Welcome and C:\javawork>java com.thefinshark.intro.Welcome, and loads of other variations. I've also changed the classpath to C:\ and C:\javawork but it still dosen't work. Someone answering a similar question suggested adding dt.jar and tools.jar to the classpath but no dice.
It'll be great if someone could help, and I'll be happy to help pass on the information to the others who have problems like this as well. (As I'm typing this I'm looking at a whole long list of similar questions.)
The directory structure must match the package name of your source file. So, if your class is in the package com.thefinshark.intro, then your source file must be in a directory com\thefinshark\intro.
So, for example, you should save your source file as C:\javawork\com\thefinshark\intro\Welcome.java, and then compile and run it from the directory C:\javawork:
C:\javawork> javac com\thefinshark\intro\Welcome.java
C:\javawork> java com.thefinshark.intro.Welcome
Note: The javac command expects a filename of the source file you are compiling (com\thefinshark\intro\Welcome.java), and the java command expects a fully-qualified class name (com.thefinshark.intro.Welcome).
See Lesson: Packages for more details on how to work with packages.
I'm using Eclipse and I've written a Java application using SWT. When Eclipse compiles my program, it renames my main file into 4 different files like this:
MainFile.class
MainFile$1.class
MainFile$2.class
MainFile$3.class
When I go to run this program from command line, I get
Could not find the main class: MainFile.class. Program will exit.
I really don't understand why this is happening.
The $ classes are for anonymous inner classes and perfectly normal.
Could we see the command line you ran? You probably need to write java MainFile instead of java MainFile.class.