Users Online

· Guests Online: 24

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

#00001 Java Introduction

1.1.            Introduction

JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It was developed by James Gosling and Patrick Naughton. It is a simple programming language.  Writing, compiling and debugging a program is easy in java.  It helps to create modular programs and reusable code.

Java terminology

Before we start learning Java, lets get familiar with common java terms.

Java Virtual Machine (JVM)

This is generally referred as JVM. Before, we discuss about JVM lets see the phases of program execution. Phases are as follows: we write the program, then we compile the program and at last we run the program.
1) Writing of the program is of course done by java programmer like you and me.
2) Compilation of program is done by javac compiler, javac is the primary java compiler included in java development kit (JDK). It takes java program as input and generates java bytecode as output.
3) In third phase, JVM executes the bytecode generated by compiler. This is called program run phase. 

So, now that we understood that the primary function of JVM is to execute the bytecode produced by compiler. Each operating system has different JVM, however the output they produce after execution of bytecode is same across all operating systems. That is why we call java as platform independent language.

bytecode
As discussed above, javac compiler of JDK compiles the java source code into bytecode so that it can be executed by JVM. The bytecode is saved in a .class file by compiler.

Java Development Kit(JDK)

While explaining JVM and bytecode, I have used the term JDK. Let’s discuss about it. As the name suggests this is complete java development kit that includes JRE (Java Runtime Environment), compilers and various tools like JavaDoc, Java debugger etc.
In order to create, compile and run Java program you would need JDK installed on your computer. 

Java Runtime Environment(JRE)

JRE is a part of JDK which means that JDK includes JRE. When you have JRE installed on your system, you can run a java program however you won’t be able to compile it. JRE includes JVM, browser plugins and applets support. When you only need to run a java program on your computer, you would only need JRE.

These are the basic java terms that confuses beginners in java. For complete java glossary refer this link:


https://docs.oracle.com/javase/tutorial/information/glossary.html

 

 

1.2.            Main Features of JAVA

Java is a platform independent language

Compiler (javac) converts source code (.java file) to the byte code (.class file). As mentioned above, JVM executes the bytecode produced by compiler. This byte code can run on any platform such as Windows, Linux, Mac OS etc. Which means a program that is compiled on windows can run on Linux and vice-versa. Each operating system has different JVM, however the output they produce after execution of bytecode is same across all operating systems. That is why we call java as platform independent language.

Java is an Object Oriented language

Object oriented programming is a way of organizing programs as collection of objects, each of which represents an instance of a class.

4 main concepts of Object Oriented programming are:

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

Simple

Java is considered as one of simple language because it does not have complex features like Operator overloading, Multiple inheritance, pointers and Explicit memory allocation.

Robust Language

Robust means reliable. Java programming language is developed in a way that puts a lot of emphasis on early checking for possible errors, that’s why java compiler is able to detect errors that are not easy to detect in other programming languages. The main features of java that makes it robust are garbage collection, Exception Handling and memory allocation.

Secure

We don’t have pointers and we cannot access out of bound arrays (you get ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why several security flaws like stack corruption or buffer overflow is impossible to exploit in Java.

Java is distributed

Using java programming language we can create distributed applications. RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for creating distributed applications in java. In simple words: The java programs can be distributed on more than one systems that are connected to each other using internet connection. Objects on one JVM (java virtual machine) can execute procedures on a remote JVM.

Multithreading

Java supports multithreading. Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU.

Portable

As discussed above, java code that is written on one machine can run on another machine. The platform independent byte code can be carried to any platform for execution that makes java code portable.

 

 

1.3.         Java Virtual Machine (JVM), Difference JDK, JRE & JVM – Core Java

Java is a high level programming language. A program written in high level language cannot be run on any machine directly. First, it needs to be translated into that particular machine language. The javac compiler does this thing, it takes java program (.java file containing source code) and translates it into machine code (referred as byte code or .class file).

Java Virtual Machine (JVM) is a virtual machine that resides in the real machine (your computer) and the machine language for JVM is byte code. This makes it easier for compiler as it has to generate byte code for JVM rather than different machine code for each type of machine. JVM executes the byte code generated by compiler and produce output. JVM is the one that makes java platform independent.

So, now we understood that the primary function of JVM is to execute the byte code produced by compiler. Each operating system has different JVM, however the output they produce after execution of byte code is same across all operating systems. Which means that the byte code generated on Windows can be run on Mac OS and vice versa. That is why we call java as platform independent language. The same thing can be seen in the diagram below:

 

So to summarise everything: The Java Virtual machine (JVM) is the virtual machine that runs on actual machine (your computer) and executes Java byte code. The JVM doesn’t understand Java source code, that’s why we need to have javac compiler that compiles *.java files to obtain *.class files that contain the byte codes understood by the JVM. JVM makes java portable (write once, run anywhere). Each operating system has different JVM, however the output they produce after execution of byte code is same across all operating systems.

JVM Architecture



 

Lets see how JVM works:


Class Loader: The class loader reads the .class file and save the byte code in the method area.

Method Area: There is only one method area in a JVM which is shared among all the classes. This holds the class level information of each .class file.

Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a Class object for each .class file.

Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing temporary variables.

PC Registers: This keeps the track of which instruction has been executed and which one is going to be executed. Since instructions are executed by threads, each thread has a separate PC register.

Native Method stack: A native method can access the runtime data areas of the virtual machine.

Native Method interface: It enables java code to call or be called by native applications. Native applications are programs that are specific to the hardware and OS of a system.

Garbage collection: A class instance is explicitly created by the java code and after use it is automatically destroyed by garbage collection for memory management.

JVM Vs JRE Vs JDK

JRE: JRE is the environment within which the java virtual machine runs. JRE contains Java virtual Machine(JVM), class libraries, and other files excluding development tools such as compiler and debugger.
Which means you can run the code in JRE but you can’t develop and compile the code in JRE.

JVM: As we discussed above, JVM runs the program by using class, libraries and files provided by JRE.



JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as compiler, debugger etc.

 

 

 

1.4.         How to Compile and Run your First Java Program

In this tutorial, we will see how to write, compile and run a java program. I will also cover java syntax, code conventions and several ways to run a java program.

Simple Java Program:

public class FirstJavaProgram {
  public static void main(String[] args){
    System.out.println("This is my first program in java");
  }//End of main
}//End of FirstJavaProgram Class

 

Output: 

This is my first program in java

How to compile and run the above program

Prerequisite: You need to have java installed on your system. You can get the java from here.

Step 1: Open a text editor, like Notepad on windows and TextEdit on Mac. Copy the above program and paste it in the text editor.

You can also use IDE like Eclipse to run the java program but we will cover that part later in the coming tutorials. For the sake of simplicity, I will only use text editor and command prompt (or terminal) for this tutorial

Step 2: Save the file as FirstJavaProgram.java. You may be wondering why we have named the file as FirstJavaProgram, the thing is that we should always name the file same as the public classname. In our program, the public class name is FirstJavaProgram, that’s why our file name should be FirstJavaProgram.java.

Step 3: In this step, we will compile the program. For this, open command prompt (cmd) on Windows, if you are Mac OS then open Terminal.
To compile the program, type the following command and hit enter.

javac FirstJavaProgram.java

 

You may get this error when you try to compile the program: “javac’ is not recognized as an internal or external command, operable program or batch file“. This error occurs when the java path is not set in your system

If you get this error then you first need to set the path before compilation.

Set Path in Windows:

Open command prompt (cmd), go to the place where you have installed java on your system and locate the bin directory, copy the complete path and write it in the command like this.

set path=C:\Program Files\Java\jdk1.8.0_121\bin

 

Note: Your jdk version may be different. Since I have java version 1.8.0_121 installed on my system, I mentioned the same while setting up the path.

Set Path in Mac OS X

Open Terminal, type the following command and hit return.

export JAVA_HOME=/Library/Java/Home

 

Type the following command on terminal to confirm the path.

echo $JAVA_HOME

 

That’s it.

The steps above are for setting up the path temporary which means when you close the command prompt or terminal, the path settings will be lost and you will have to set the path again next time you use it. I will share the permanent path setup guide in the coming tutorial.

Step 4: After compilation the .java file gets translated into the .class file(byte code). Now we can run the program. To run the program, type the following command and hit enter:

java FirstJavaProgram

 

Note that you should not append the .java extension to the file name while running the program.

 

Java Class File

 

A Java class file is a file containing Java bytecode and having .class extension that can be executed by JVM. A Java class file is created by a Java compiler from .java files as a result of successful compilation. As we know that a single Java programming language source file (or we can say .java file) may contain one class or more than one class. So if a .java file has more than one class then each class will compile into a separate class files.


For Example: Save this below code as Test.java on your system.

 

// Compiling this Java program would

// result in multiple class files.

 

class Sample

{

 

}

 

// Class Declaration

class Student

{

 

}

// Class Declaration

class Test

{

       public static void main(String[] args)   

       {

           System.out.println("Class File Structure");

       }

Copy Code

 

For Compiling:

javac Test.java



After compilation there will be 3 class files in corresponding folder named as:

  • Sample.class
  • Student.class
  • Test.class

 

A single class file structure contains attributes that describe a class file.
Representation of Class File Structure

 

ClassFile

{

     magic_number;

     minor_version;

     major_version;

     constant_pool_count;

     constant_pool[];

     access_flags;

     this_class;

     super_class;

     interfaces_count;

     interfaces[];

     fields_count;

     fields[];

     methods_count;

     methods[];

     attributes_count;

     attributes[];

}

Elements of class file are as follows:

  1. magic_number: The first 4 bytes of class file are termed as magic_number. This is a predefined value which the JVM use to identify whether the .class file is generated by valid compiler or not. The predefined value will be in hexadecimal form i.e. 0xCAFEBABE.
    Now let’s see what happen when JVM will not find valid magic number. Suppose we have a .java file named as Sample.java as follows and follow step by step process on your system.

// class Declaration

class Sample

{

   public static void main(String[] args)

   {

       System.out.println("Magic Number");          

   }

}

Step 1: Compile using javac Sample.java


Step 2: Now open the Sample.class file. It will looks like following.



 

Step 3: Now erase at least single symbol from this Sample.class file from starting of file and save it.


Step 4: Now try to run this using java Sample command and see the magic i.e. you will get run time exception (See the highlighted text in below image):

 

 

Note: This can vary depending on how much you remove the .class file data.

  1. minor_version & major_version: These both together represents .class file version. JVM will use these versions to identify which version of the compiler generates the current .class file. We denotes the version of class file as M.m where M stands for major_version and m stands for minor_version

 

Note: Lower version compiler generated .class file can be executed by high version JVM but higher version compiler generated .class file cannot be executed by lower version JVM. If we will try to execute we will get run time exception.

 

This demonstration is for Windows OS as follows:

 

Step 1: Open a command prompt window and try to check java compiler version and JVM version using following commands respectively (Highlighted text in image are the commands)


Output for 1.8 version will be:



 

Step 2: Now check with another version which may be higher or lower than already installed.thisDownload link.
And install this to your PC or laptops and note the installation address.
Step 3: Open a second command prompt window and set the path of bin folder of installed jdk installed during 2nd step. And check for Java compiler version ad JVM version.

 


Step 4: Now on 1st command prompt compile the any valid .java file. For example: See above Sample.java file. Compile it as:


 


Step 5: Now on 2nd command prompt window try to run the above compiled code class file and see what happen. There is a run time exception which I have highlighted in below image.

 

 

Note: Internally jdk 1.5 version means 49.0 and 1.6 means 50.0 and 1.7 means 51.0 etc. class file version where the digits before the decimal point represent the major_version and digits after decimal point represents the minor_version.

  1. constant_pool_count: It represents the number of the constants present in the constant pool (When a Java file is compiled, all references to variables and methods are stored in the class’s constant pool as a symbolic reference).
  2. constant_pool[]: It represents the information about constants present in constant pool file.
  3. access_flags: It provide the information about the modifiers which are declared to the class file.
  4. this_class: It represents fully qualified name of the class file.
  5. super_class: It represents fully qualified name of the immediate super class of current class. Consider above Sample.java file. When we will compile it, then we can say this_class will be Sample class and super_class will be Object class.
  6. interface_count: It returns the number of interfaces implemented by current class file.
  7. interface[]: It returns interfaces information implemented by current class file.
  8. fields_count: It represents the number of fields (static variable) present in current class file.
  9. fields[]: It represent fields (static variable) information present in current class file.

10.  method_count: It represents number of methods present in current class file.

11.  method[]: It returns information about all methods present in current class file.

12.  attributes_count: It returns the number of attributes (instance variables) present in current class file.

13.  attributes[]: It provides information about all attributes present in current class file.

 

Closer look to the First Java Program

Now that we have understood how to run a java program, let have a closer look at the program we have written above.

public class FirstJavaProgram {

 

This is the first line of our java program. Every java application must have at least one class definition that consists of class keyword followed by class name. When I say keyword, it means that it should not be changed, we should use it as it is. However the class name can be anything.

I have made the class public by using public access modifier, I will cover access modifier in a separate post, all you need to know now that a java file can have any number of classes but it can have only one public class and the file name should be same as public class name.

public static void main(String[] args)  {

 

This is our next line in the program, lets break it down to understand it:
public: This makes the main method public that means that we can call the method from outside the class.

static: We do not need to create object for static methods to run. They can run itself.

void: It does not return anything.

main: It is the method name. This is the entry point method from which the JVM can run your program.

(String[] args): Used for command line arguments that are passed as strings. We will cover that in a separate post.

System.out.println("This is my first program in java");

 

This method prints the contents inside the double quotes into the console and inserts a newline after.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.65 seconds
10,255,250 unique visits