Blog is under construction. Blog is under construction.

Me on Flickr

Monday, 30 July 2012

Difference between JRE, JVM and JDK?


Difference between JRE, JVM and JDK:

JRE, JVM and JDK are three terms you often heard in conjunction with Java programming language and most people either confuse between them or think they all are same. In this java article we will what is Java Run-time (JRE), what is Java virtual Machine (JVM) and what is Java development Kit (JDK) along withJust in Time compiler or JIT. Once you know what JRE, JVM or JDK means you can differentiate them easily by yourself

JRE JVM and JDK in Java Programming language

Java Runtime Environment (JRE)

Java is everywhere in browser, in mobile, in TV or in set-top boxes and if you are into Java programming language than you know that Java code which is bundled in JAR (Java archive) file require Java virtual machine JVM to execute it. Now JVM is an executable or program like any other program and you can install that into your machine. You have seen browser often suggesting download JRE to run a Java Applet downloaded from Internet. Various version of JRE are available in java.oracle.com and most of the user who just want to execute Java program inside browser or standalone downloads JRE. All browsers including Internet Explorer, Firefox and Chrome can work with JRE.

Java Virtual Machine (JVM)

When you download JRE and install on your machine you got all the code required to create JVM. Java Virtual Machine is get created when you run a java program using java command e.g. java HelloWorld. JVM is responsible for converting byte code into machine specific code and that's why you have different JVM for Windows, Linux or Solaris but one JAR can run on all this operating system. Java Virtual machine is at heart of Java programming language and provide several feature to Java programmer including Memory Management and Garbage Collection, Security and other system level services. Java Virtual Machine can be customized e.g we can specify starting memory or maximum memory of heap size located inside JVM at the time of JVM creation. If we supplied invalid argument to java command it may refuse to create Java Virtual Machine by saying "failed to create Java virtual machine: invalid argument". In short Java Virtual Machine or JVM is the one who provides Platform independence to Java.

Java Development Kit (JDK)

JDK is also loosely referred as JRE but its lot more than JRE and it provides all the tools and executable require to compile debug and execute Java Program. Just like JRE, JDK is also platform specific and you need to use separate installer for installing JDK on Linux and Windows. Current Version of JDK is 1.7 which is also referred as Java7 and it contains javac (java compiler) based on programming rules of Java7 and Java which can execute java7 code with new features like String in Switch, fork-join framework or Automatic Resource Management. When you install JDK, installation folder is often referred as JAVA_HOME. All binaries are located inside JAVA_HOME/bin which includes javac, java and other binaries and they must be in your system PATH in order to compile and execute Java programs. For details on Path see how to set PATH for Java in Windows and UNIX.

Difference between JRE, JDK and JVM

In short here are few differences between JRE, JDK and JVM:

1)  JRE and JDK come as installer while JVM are bundled with them.
2)  JRE only contain environment to execute java program but doesn’t contain other tool for compiling java program.
3)  JVM comes along with both JDK and JRE and created when you execute Java program by giving “java” command.

Just in Time Compiler (JIT)

Initially Java has been accused of poor performance because it’s both compiles and interpret instruction. Since compilation or Java file to class file is independent of execution of Java program do not confuse. Here compilation word is used for byte code to machine instruction translation. JIT are advanced part of Java Virtual machine which optimize byte code to machine instruction conversion part by compiling similar byte codes at same time and thus reducing overall execution time. JIT is part of Java Virtual Machine and also performs several other optimizations such as in-lining function.

That’s all on JRE, JDK and Java Virtual machine and difference between them. Though they look similar they are different and having a clear idea of JVM, JIT or JDK helps in java programming.


How the Java Virtual Machine (JVM) Works?

How the Java Virtual Machine (JVM) Works?


The Java virtual machine is called "virtual" because it is an abstract computer defined by a specification. To run a Java program, you need a concrete implementation of the abstract specification. This chapter describes primarily the abstract specification of the Java virtual machine. To illustrate the abstract definition of certain features, however, this chapter also discusses various ways in which those features could be implemented.


What is a Java Virtual Machine?
To understand the Java virtual machine you must first be aware that you may be talking about any of three different things when you say "Java virtual machine." You may be speaking of:
  • the abstract specification,
  • a concrete implementation, or
  • a runtime instance.
The abstract specification is a concept, described in detail in the book: The Java Virtual Machine Specification, by Tim Lindholm and Frank Yellin. Concrete implementations, which exist on many platforms and come from many vendors, are either all software or a combination of hardware and software. A runtime instance hosts a single running Java application.
Each Java application runs inside a runtime instance of some concrete implementation of the abstract specification of the Java virtual machine. In this book, the term "Java virtual machine" is used in all three of these senses. Where the intended sense is not clear from the context, one of the terms "specification," "implementation," or "instance" is added to the term "Java virtual machine".



The Architecture of the Java Virtual Machine



1.            The first component of JVM architecture is "class loader" used to load the .class files.
2.            Class Loader object loads user defined .class files from the given userdefined package or from current package by default where as ' boot strap class loader' loads .class files from Java API at runtime.
3.            The loaded .class files is forwarded to 'execution engine'.
4.            'Execution Engine' translates .class files byte code to platform native code and it calls the native functions using native callable statements.
5.            Execution engine contains 2 components. (i) JVM (Interpreter) (ii) JIT(Just In Time)Compiler
6.            JDK contains JVM by default where as web browsers contain JIT. JIT compiles all components at a time. It improves performance. JIT is needed to display downloaded applet file at client browser.
7.            The code which is written in other languages is known as native code(.dll, .cab) to Java. Native code is processed by native translator of JVM.
8.            JVM allocates memory for Java Datatypes at runtime not at compilation time. JVM needs memory to allocate. JVM needs 2MB to 64MB initial memory to execute an application.
9.            Memory is divided into five data areas like Stack Area, Heap Area, Method Area, Register Area and Stackpool Area.

For more information on JVM: 

Watch Video about JVM:



How to write a simple Java Program?



Java HelloWorld Program



In this page, you will learn how to write a Java program
hello world java program :- Java code to print "Hello World".
Open Notepad and type as below:

Java source code

public class HelloWorld
{
   public static void main(String args[])
   {
      System.out.println("Hello World");
   }
}

Save this file as HelloWorld.java
To compile: javac HelloWorld.java

To execute: java HelloWorld


Output:
Hello World

What happens at Compile Time?



To commence with Java programming, we must know the significance of Java Compiler. When we write any program in a text editor like Notepad, we use Java compiler to compile it. A Java Compiler javac is a computer program or set of programs which translates java source code into java byte code. 
The output from a Java compiler comes in the form of Java class files (with .class extension). The java source code contained in files end with the .java extension. The file name must be the same as the class name, as classname.java. When the javac compiles the source file defined in a .java files, it generates bytecode for the java source file and saves in a class file with a .class extension.
Following figure shows the working of the Java compiler:



Once the byte code is generated it can be run on any platform using Java Interpreter (JVM). It interprets byte code (.class file) and converts into machine specific binary code. Then JVM runs the binary code on the host machine.

At Compile Time, Java file is compiled by Java Compiler (it does not interact with OS) and converts the Java code into Byte code (Which is nothing but .class file)
.

What happens at Run time?

At Run time, following steps are performed



Classloader:  is the Sub system of JVM that is used to load class files.
Bytecode Verifier: Checks the code fragments for illegal code
Interpreter:  read bytecode stream then execute the instructions

How to Set Path and Classpath for Java on Unix, Linux and Windows?


How to Set Path and Classpath for Java on Unix, Linux and Windows?



PATH is one of fundamental Environment variable on shell or DOS but it’s commonly associated with Java mainly because if we try to run a java program which doesn't include Java executable in PATH then we say PATH is not set for Java and we need to set path for Java. I have also seen developer getting confused over path and classpath in java. Though both path and classpath provides run-time settings for any java environment which is required to compile and execute Java program they are completely different to each other.
Classpath is usually used to find out classes and mostly associated with lib part while PATH is used to find the executable or command to be executed. In order to compile and run java program from command line your PATH environment variable must have "javac" and "java" on it. In this Java PATH tutorial we will see what is PATH for Java, How to Set Path for Java and how to troubleshoot PATH related issues.
What is Path in Java
First of all PATH is not specific to java it’s a shell concept and also available in Windows and DOS. It’s represented by Environment variable called "PATH" and that's why it’s known as path. Whenever you type a command in shell in UNIX or Linux or in command prompt in windows machine, command will be looked on PATH and if shell is not able to find the command in PATH it says "not recognized" or wrong command. Now for compiling and running we use two java commands "javac" and "java" and these commands doesn't come by default with windows or Unix instead they comes when you install JDK in your machine. Now to successfully compile and run a java program in either windows or Linux you must have these two commands or executable in your PATH environment variable and that is called Setting Path for Java.

Setting Path for Java in Unix/Linux and Windows
How to check if "java" or "javac" is in PATH
Javac and Java command resides under /bin directory or your Java installation directory. In my machine its "C:\Program Files\Java\jdk1.6.0_26\bin"

If you have this bin directory in path it means java and javac will be in path and Path is set to run Java Program. There are two ways you verify whether java is in path or not.
1) Simple and easy way
Open a command prompt window by pressing start -->run-->cmd and then typing "java" or "javac" in command prompt as shown in below example
C:\Documents and Settings>java
Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)

where options include:
    -client       to select the "client" VM
    -server       to select the "server" VM
    -hotspot      is a synonym for the "client" VM [deprecated]



If it displays lot of output means Java is in your path and similarly you can check for "javac”, on the other hand if java is not in your system's path you will get below output in UNIX
stock_trader$ javac
javac: not found
and in windows
C:\Documents and Settings>javac
'javac' is not recognized as an internal or external command,
operable program or batch file.
If java or javac is not in your path then you can add them into path by adding "bin" directory or your JDK installation directory into environment variable "PATH". Both windows and UNIX use same name.
How to set PATH for Java in windows
I say pretty easy just add bin directory of your JDK installation directory into PATH environment variable. You can do this either from command prompt or by using windows advanced environment editor
1) Setting Java PATH using command prompt in windows

Use "set" command to set value of PATH environment variable as shown in below example:

C:\Documents and Settings>set PATH=%PATH%;
C:\Program Files\Java\jdk1.6.0_26\bin

%PATH% is actually representing current path and we are appending java bin directory into PATH. Note that every path in windows is comma (;) separated while in UNIX it would be colon (:) separated

2) Setting Java PATH using windows environment variable editor
Use short cut "window key + pause/break" --> Advanced --> Environment Variables -->PATH
Just append the path of java installation directory here and you are done. Open a command prompt and type java or javac and you can see the output.
How to set Java PATH in UNIX or Linux
Setting PATH for java in UNIX is similar to the way we did for it on windows using command prompt. In UNIX just open any shell and execute below command
set PATH=${PATH}:/home/opt/jdk1.6.0_26/bin
Remember here each element in PATH is colon separated.

CLASSPATH in Java
I have experience in finance and insurance domain and Java is heavily used in this domain for writing sophisticated Equity, Fixed income trading applications. Most of these investment banks have written test for Java and I always fine at least one question related to CLASSPATH in Java on those interview. Java CLASSPATH is one of the most important concepts in java but I must say mostly overlooked. This should be the first thing you should learn while writing java programs because without understanding of Classpath in Java you can't understand how java locates your class files.

So let’s start with basic and then we will see some example and improvisation of Classpath in Java. In Fact CLASSPATH is an environment variable which is used by Java Virtual Machine to locate user defined classes. 

Setting Java Classpath in Windows
For setting Java Classpath in Windows (any version either Windows XP or Windows 2000) you need to specify value of environment variable CLASSPATH, name of this variable is not case sensitive and it doesn’t matter if name of your environment variable is Classpath, CLASSPATH or classpath in Java.

Here is Step by Step guide for setting Java Classpath in Windows:


  1. Go to Environment variable window in Windows by pressing "Windows + Pause “-->Advanced -->Environment variable " or you can go from right click on my computer than choosing properties and then Advanced and then Environment variable this will open Environment variable window in windows.
  2. Now specify your environment variable CLASSPATH and put the value of your JAVA_HOME\lib and also include current directory by including (dot or period sign).
  3. Now to check the value of Java classpath in windows type "echo %CLASSPATH" in your DOS command prompt and it will show you the value of directory which are included in CLASSPATH
Setting Java Classpath in UNIX or Linux
To set Classpath for Java In Linux you can simply export CLASSPATH="your classpath" from either your .bash_profile or .bashrc script which will run whenever you login into your Linux or Unix Machine.
Now to check value of Java CLASSPATH in Linux type "echo ${CLASSPATH}. 
I hope this example for setting classpath in Java will enable to set classpath by yourself let me know if you face any problem while setting up classpath in Java

Overriding Classpath in Java
You can override value of Java classpath defined by environment variable CLASSPATH by providing option "-cp" or "-classpath" while running your program and this is the best way to have different classpath for different application in Java. General way to define classpath is in the startup script of any program. e.g.
CLASSPATH=/home/tester/classes
java -cp $CLASSPATH Test

By default Java CLASSPATH points to current directory denoted by "." and it will look for any class only in current directory.

Different example of using Classpath in Java
In case you have multiple directories defined in CLASSPATH variable, java will look for a class starting from first directory and only look second directory in case it did not find the specified class in first directory. This is extremely useful feature of Classpath in java to understand and it’s very useful for patch release kind of stuff. Let’s see  java -classpath example

I have my CLASSPATH=/home/tester/first:/home/tester/second
Now I have "Test" class of different version in both first and second directory so when I give a command
"java Test" What will happen ? Which Test class would be picked?
Since JVM search directory in the order they have listed in CLASSPATH variable it will first go to the "first" directory and if it finds "Test" over there it will not go to "/home/tester/second" directory.
Now if you delete Test class from /home/tester/first directory it will go to /home/tester/second directory and will pick "Test" class from there.

I have used this feature of Java Classpath to test my patch releases, we used to have a folder called "patch" listed as first element in Java CLASSPATH and any point of time we want to put any debug statement or want to test any bug we just modify Java source file , compile it and generate class file and put that inside patch folder instead of releasing whole new jar and this comes very handy if you are working in a large project where you don't have development environment setup in Windows and your project only runs on Unix server.
Its also worth noting that when you use the -jar command line  option to run your program as an executable JAR, then the CLASSPATH environment variable will be ignored, and also the -cp and -classpath switches will be ignored. 

In this case you can set your Java classpath in the META-INF/MANIFEST.MF file by using the Class-Path attribute.
Now a common question if I have my CLASSPATH variable pointing to current directory "." and I have class called "Test" inside package "testing" and with below directory structure C:\project\testing\Test.class in my computer.
What will happen if I run command "java Test" from directory "C:\project\testing\" will it run?
No it will not run it will give you Exception in thread "main" java.lang.NoClassDefFoundError: Test
Since name of the class is not Test, instead it’s testing. Test even though your classpath is set to current directory.

Now what will happen if I give command “java testing.Test “from” C:\project\testing\, it will again not run and give error?

Exception in thread "main" java.lang.NoClassDefFoundError: testing/Test
Why because now it looking for class called Test which is in package testing, starting from current directory "." but don't find it since there is no directory called "testing after this path "C:\project\testing\".

To run it successfully you need to go back to directory "C:\project" and now run 
C:\project>java testing.Test 
It will run successfully.

Errors related to Classpath in Java

If you are working in Java you must have faced some errors and exception related to classpath in java, two most common issues related to java classpath is ClassNotFoundException and NoClassDefFoundError. I have seen that most of java developer tries to solve this error by trial and error; they just don’t look beyond the hood and try to understand what the reason for these java classpath related errors is. They often misunderstood that these two errors are same also. 

Here is the reason of these java classpath errors: 

ClassNotFoundException is an Exception and will be thrown when Java program dynamically tries to load a particular Class at Runtime and don’t find that on Java classpath. Two keyword here “dynamically” and “runtime”. Classic example of these errors is when you try to load JDBC driver by using Class.forname(“driver name”). So this error essentially comes when Java try to load a class using forName() or by loadClass() method of ClassLoader. Key thing to note is that presence of that class on Java classpath is not checked on compile time. So even if those classes are not present on Java classpath your program will compile successfully and only fail when you try to run.

On the other hand NoClassDefFoundError is an Error and more critical than ClassNotFoundException which is an exception and recoverable. NoClassDefFoundError comes when a particular class was present in Java Classpath during compile time but not available during run-time. Classic example of this error is using log4j.jar for logging purpose and forgot to include log4j.jar on classpath in java during run-time. Keyword here is “class present at compile time but not available on run-time”. This is normally occurring due to any method invocation on a particular class which is part of library and not available on classpath in Java.












                                                                                                                                                                                                               



Friday, 13 July 2012

Installing JDK on Windows


Installing JDK on Windows


If you want to write and run a program the you will need a development kit. This compiles your source code and run the app. In Java, the tool is called Java Development KIT (JDK). This KIT contains the tools for compiling, running, packaging and etc.

What should know before get into details: Difference between JRE and JDK?
If you want to write and run a program then you will need a development kit. This compiles your source code and run the application. In Java, the tool is called Java Development KIT (JDK). This JDK contains the tools for compiling, running, packaging and etc.
JRE is the Java Runtime Environment. This contain the tool for running the Java application (not for developing). A user, other than a developer, who is going to run a Java program can use JRE. No need to get JDK as the user is not going to develop a program.

Where to download JDK?


SUN has a long list of versions of JDK that they have released so far. you can select the java version and the operating system on which you plan to use ( e.g.: JDK 1.5, Windows 32bit) .
Download it to your local machine. If you cannot find the one you want in the listing then look for the previous releases and download it. Once you download, execute the exe file with default option, it will install everything you.

Once it is installed, open the command prompt (Start ->Run->Type 'cmd' and press 'OK') and type java. You will get a list of options for command 'java' and that indicates that you installed JDK successfully. If you do not see the options listed, then that means the Java path is not in the system environment and you need to set it.

How to set system environment variable

·         Let's assume it is installed in the folder "C:/tools/jdk1.5"
·         Right click on the My Computer icon on your desktop and select properties
·         Click the Advanced Tab
·         Click the Environment Variables button
·         Under System Variable, select "Path" and click "edit"
·         Append ;C:/tools/jdk1.5/bin at the end of the value of "Path"
·         Click OK
·         Click Apply Change
Now open the command prompt again (Start ->Run->Type 'cmd' and press 'OK') and type java. You will get a list of options for command 'java'.

Video for installing JDK


 
Related Posts Plugin for WordPress, Blogger...