Saturday, 31 May 2014

Components in JVM Architecture






 NOTE: 
=>         Runtime data areas shared among all threads   

=>   Thread specific Runtime data areas


 
Classloader:
Classloader is a subsystem of JVM that is used to load class files.

Class(Method) Area:
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.

Heap:
It is the runtime data area in which objects are allocated.

Java Stack:
Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

Program Counter Register:
PC (program counter) registers. It contains the address of the Java virtual machine instruction currently being executed.

Native Method Stack:
It contains all the native methods used in the application.

Execution Engine:
It contains:
1) A virtual processor
2) Interpreter
Read bytecode stream then execute the instructions.


3) Just-In-Time (JIT) compiler
It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term compiler refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
 

Java SE 7 new features

    
> Java Virtual Support for dynamic languages.
> Java HotSpot Virtual Machine Performance Enhancements.
> Changes in Java Programming Languages:
    > Strings in Switch statement.
    > Try with Automatic resource Management.
    > Enhanced Type Inference for Generic Instance Creation.
    > Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods.
    > Binary literals.
    > Underscores in Numeric Literals.
    > Multiple Exception Catching  and  Exceptions Rethrowing  with Improved Type Checking.
> Concurrency Utilities.
> Two new packages, java.nio.file and java.nio.file.attribute , are added to improve platform independence and add support for metadata and symbolic links.
> XRender-Based Rendering Pipeline for Java2D.
> Security enhancement : Elliptic Curve Cryptography (ECC), CertPath Algorithm Disabling etc...
> Swing Enhancements : JLayer Class, Nimbus Look & Feel, ease in mixing Heavyweight and Lightweight components, Shaped and Translucent Windows, HSL Color Selection in JColorChooser Class.

> Networking Enhancements : Enhanced support for new network protocol like SCTP and Sockets Direct Protocol , addition of URLClassLoader.close method.

> XML Enhancements : inclusion of JAXP, also support JAXB, JAX-WS.

> Internationalization Enhancements : supports Unicode 6.0.0 , Support for ISO 4217 Currency Codes, Locale Class Supports BCP47 and UTR35, Unicode 6.0 Support in Regular Expressions API etc.

> Enhancement of Rich Internet Applications (RIA) : Requesting and Customizing Applet Decoration in Dragg able Applets, Embedding JNLP File in Applet Tag, Deploying without Codebase, Handling Applet Initialization Status with Event Handlers.

************************************************

Strings in Switch statement

Using JDK 7, you can pass string as expression in switch statement. The switch statement compares the passed string with each case label and execute the case block which have matched string. The comparison of string in switch statement is case sensitive.

The example code for the above is given below :

public class StringsInSwitch
{
public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg)
{
String typeOfDay;

switch (dayOfWeekArg)
{
case "Monday":
typeOfDay = "Start of work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
}
System.out.println(typeOfDay);
return typeOfDay;
}
public static void main(String args[]) {
new StringsInSwitch().getTypeOfDayWithSwitchStatement("Friday");
}
}

******************************
The try-with-resource Statement
The try-with-resource statement contains declaration of one or more resources. As you know, prior to Java SE 7, resource object must be closed explicitly, when the resource use or work is finished. After the release of Java SE 7, the try-with-resource statement handles it implicitly means it automatically closed the resource when it has no longer use to the class. But for this, you need to declare resources using try-with-resource statement.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class J7TryWithResource
{
static String readFirstLineFromFile(String path) throws IOException
{
try (BufferedReader br = new BufferedReader(new FileReader(path)))
{
System.out.println(br.readLine());
return br.readLine();
}
}

public static void main(String args[])
{
try {
readFirstLineFromFile("C://J7Try.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}

*******************************
Underscores in Numeric Literals:-
In Java SE 7,  You can place any number of underscore( _ ) between digits of numeric literals. This added feature improves the readability of the code. For example : Using underscore you can separate groups of digits in numeric literals . For Example credit card number can be write as follows :

long creditCardNumber = 1234_5678_9012_3456L;
You can place underscore between digits. But for placing underscore you need to be careful. You can't place underscore in the following places :
> You can't place it at the beginning or at the end of a number.
> Adjacent to a decimal point in a floating point literal.
> Before to an F or L suffix.
> In positions where a string of digits is expected.

Some of the valid example with different type of data type is given below:

long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi = 3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;

Some of the invalid examples are given below :
float pi1 = 3_.1415F;
float pi2 = 3._1415F;
long socialSecurityNumber1= 999_99_9999_L;
int x3 = 52_;
int x5 = 0_x52;
int x6 = 0x_52;
int x8 = 0x52_;
int x11 = 052_;

*********************************
Multiple Exception Catching
In this section, you will learn about new catch method added in Java SE 7 which eliminate duplicate code.

Take a look at the following code :
    catch (IOException ex) {
    logger.log(ex);
    throw ex;
    catch (SQLException ex) {
    logger.log(ex);
    throw ex;
    }
Prior to Java SE 7, you can't create common catch method to remove duplicate code. But in Java SE 7, you can create common catch method to remove duplicate code as follows :

public class J7MultipleExceptionCatching
{
public static void main (String args[])
{
int array[]={20,10,30};
int num1=15,num2=0;
int res=0;

try
{
res = num1/num2;
System.out.println("The result is" +res);

for(int ct =2;ct >=0; ct--)
{
System.out.println("The value of array are" +array[ct]);
}

}

catch (ArrayIndexOutOfBoundsException|ArithmeticException e)
{
System.out.println("Error....some exception occur");
}
}
}

*************************
Exceptions Rethrowing  with Improved Type Checking
Take a a look at the following code having improved type checking of Java SE 7 :

Two classes FirstException and SecondException is given below :
    static class FirstException extends Exception { }
    static class SecondException extends Exception { }
The third class, containing improved type checking, which have the following method :

public void rethrowException(String exceptionName) throws FirstException, SecondException
{
try {
if (exceptionName.equals("First")) {
throw new FirstException();
} else {
throw new SecondException();
}
}
catch (Exception e) {
throw e;
}
}
The above code will only execute using Java SE 7 , If you will try to execute it through prior version than Java 7, you will get the error " unreported exception Exception; must be caught or declared to be thrown " .

The reason behind this is the type of the catch parameter e is Exception, which is a supertype, not a subtype, of FirstException and SecondException.  Throws must be like this : "throws Exception" to compile the above code prior to Java 7.

But now(in Java SE 7), you can throw an exception that is a supertype of the throws type. Here Exception is the super type of the FirstException and SecondException.

The complete Code is given below :

import java.io.*;

public class J7RethrowingException
{
public void rethrowException(String exceptionName) throws FirstException, SecondException
{
try {
if (exceptionName.equals("First")) {
System.out.println("FirstException is thrown");
throw new FirstException();

} else {
System.out.println("SecondException is thrown");
throw new SecondException();
}
}
catch (Exception e) {
throw e;
}
}
public static void main(String args[])throws FirstException, SecondException{
new J7RethrowingException().rethrowException("First");
}
}

********************************

Java DataTypes

Working With Variables:
A variable represents a memory location which holds data (values).

Declaring a Variable:
Syn:-
   [access-spe] [modifier] datatype variablename;

   [access-spe] [modifier] datatype variablename=value, variablename[=value,]...;

        DataTypes
Integers:
byte       8bits     -128  to  127
short     16bits   -32,768  to  32,767
int         32bits   -2,147,483,648  to  2,147,483,647
long      64bits   -9,223,372,036,854,775,808   to   9,223,372,036,854,775,807

Reals:
float     32bits     1.4* (10**-45) to 3.4* (10**+38)
                          (7 digits after decimal point)
double  64bits     4.9* (10**-324) to 1.8* (10**+308) 
                          (15 digits)

Characters:
char    16bits    1char only

Booleans:
boolean    1bit    true or false

Strings:
String


f-s              datatype
%d             byte    short     int      long  
%f             float    double
%c            char
%s  %S    String
%b  %B   boolean
%h           hex-dec
%o           oct-dec




Priority (Precedence) Of Operators:
     > 1st, the contents inside the braces: (),  [] and . will be executed.
     > Next unary -,  ++,  --,  ~,  !
     > Next *,  /  and %
     > + and - will execute next
     > Bitwise operators >>,  <<,  >>>
     > Relational operators >,  >=,  <,  <=
     > Relational operators ==,  !=
     > Bitwise operators &,  ^,  |
     > Logical operators &&,  ||
     > Ternary ope ?:
     > Assignment   =,   ope=

Features of java

Peculiarities of Java:

Platform Independent: The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language. Not even a single language is idle to this feature but java is more closer to this feature. The programs written on one platform can run on any platform provided the platform must have the JVM.


Simple: There are various features that makes the java as a simple language. Programs are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the java programs that can crash the system but we can not say about the other programming languages. Java provides the bug free system due to the strong memory management. It also has the automatic memory allocation and deallocation system.

Object Oriented: To be an Object Oriented language, any language must follow at least the four characteristics.

 Inheritance :   It is the process of creating the new classes and using the behavior of the existing classes by extending them just to      reuse  the existing code and adding the additional features as needed.
Encapsulation:  It is the mechanism of combining the information and providing the abstraction.

Polymorphism: As the name suggest one name multiple form, Polymorphism is the way of providing the different functionality by the functions  having the same name based on the signatures of the methods.
Dynamic binding:   Sometimes we don't have the knowledge of objects about their specific types while writing our code. It is the way     of providing the maximum functionality to a program about the specific type at runtime. 

 As the languages like Objective C, C++ fulfills the above four characteristics yet they  are not fully object oriented languages because they are structured as well as object oriented languages. But in case of java,  it is a fully Object Oriented language because object is at the outer most level of data structure in java. No stand alone methods, constants, and variables are there in java. Everything in java is object even the primitive data types can also be converted into object by using the wrapper class.

Distributed: The widely used protocols like HTTP and FTP are developed in java. Internet programmers can call functions on these protocols and can get access the files from any remote machine on the internet rather than writing codes on their local system.

Interpreted: We all know that Java is an interpreted language as well. With an interpreted language such as Java, programs run directly from the source code.
 The interpreter program reads the source code and translates it on the fly into computations. Thus, Java as an interpreted language depends on an interpreter program.
 The versatility of being platform independent makes Java to outshine from other languages. The source code to be written and distributed is platform independent. 
 Another advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with Java.

Robust: Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust.

Secure: Java does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box. Security manager determines the accessibility options of a class like reading and writing a file to the local disk. Java uses the public key encryption system to allow the java applications to transmit over the internet in the secure encrypted form. The bytecode Verifier checks the classes after loading.

Architecture- Neutral: The term architectural neutral seems to be weird, but yes Java is an architectural neutral language as well. The growing popularity of networks makes developers think distributed. In the world of network it is essential that the applications must be able to migrate easily to different computer systems. Not only to computer systems but to a wide variety of hardware architecture and Operating system architectures as well.  The Java compiler does this by generating byte code instructions, to be easily interpreted on any machine and to be easily translated into native machine code on the fly. The compiler generates an architecture-neutral object file format to enable a Java application to execute anywhere on the network and then the compiled code is executed on many processors, given the presence of the Java runtime system. Hence Java was designed to support applications on network. This feature of Java has thrived the programming language.

Portable: The feature Write-once-run-anywhere  makes the java language portable provided that the system must have interpreter for the JVM. Java also have the standard data size irrespective of operating system or the processor. These features makes the java as a portable language.

Performance: Java uses native code usage, and lightweight process called  threads. In the beginning interpretation of bytecode resulted the performance slow but the advance version of JVM uses the adaptive and just in time compilation technique that improves the performance. 

Multithreaded: As we all know several features of Java like Secure, Robust, Portable, dynamic etc; you will be more delighted to know another feature of Java which is Multithreaded.
 Java is also a Multithreaded programming language. Multithreading means a single program having different threads executing independently at the same time. Multiple threads execute instructions according to the program code in a process or a program. Multithreading works the similar way as multiple processes run on one computer. 
 Multithreading programming is a very interesting concept in Java. In multithreaded programs not even a single thread disturbs the execution of other thread. Threads are obtained from the pool of available ready to run threads and they run on the system CPUs. This is how Multithreading works in Java which you will soon come to know in details in later chapters.

Dynamic: While executing the java program the user can get the required files dynamically from a local drive or from a computer thousands of miles away from the user just by connecting with the Internet.

Setting up the path for windows 2000/XP:

Assuming you have installed Java in c:\Program Files\java\jdk directory:

> Right-click on 'My Computer' and select 'Properties'.

> Click on the 'Environment variables' button under the 'Advanced' tab.

> Now alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Introduction to Core Java



JAVA

History of Java
Let's see some points that describe the history of java.
Ø James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
Ø Originally designed for small, embedded systems in electronic appliances like set-top boxes.
Ø Initially called Oak and was developed as a part of the Green project.
Ø In 1995, Oak was renamed as "Java". Java is just a name not an acronym.
Ø Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995.

Java Version History
There are many java versions that have been released.
Ø JDK Alpha and Beta (1995)
Ø JDK 1.0 (23rd Jan, 1996)
Ø JDK 1.1 (19th Feb, 1997)
Ø J2SE 1.2 (8th Dec, 1998)
Ø J2SE 1.3 (8th May, 2000)
Ø J2SE 1.4 (6th Feb, 2002)
Ø J2SE 5.0 (30th Sep, 2004)
Ø Java SE 6.0 (11th Dec, 2006)
Ø Java SE 7.0 (28th July, 2011)

Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently used.

Some of them are as follows:
1.  Desktop Applications such as acrobat reader, media player, antivirus etc…
2.  Web Applications such as irctc.co.in, javapoint.com etc…
3.  Enterprise Applications such as banking applications.
4.  Mobile
5.  Embedded System
6.  Smart Card
7.  Robotics
8.  Games etc...

Types of Java Applications
There are mainly 4 types of applications that can be created using java:

1) Standalone Application
It is also known as desktop application or window-based application. An application that we need to install on every machine such as media player, antivirus etc… AWT and Swing are used in java for creating standalone applications.

2) Web Application
An application that runs on the server side and creates dynamic page, is called web application. Currently, servlet, jsp, struts, jsf etc… technologies are used for creating web applications in java.

3) Enterprise Application
An application that is distributed in nature, such as banking applications etc… It has the advantage of high level security, load balancing and clustering. In java, EJB is used for creating enterprise applications.

4) Mobile Application
 These Applications are created for mobile devices. Currently Android and Java ME are used for creating mobile applications.

Java can be divided into 3 modules.
They are:
Ø JSE (Java Standard Edition)
Ø JEE (Java Enterprise Edition)
Ø JME (Java Micro/Mobile Edition)

JSE
Ø Java is a high level programming language.
Ø Java is a pure OOP language.
Ø Java can be used to develop all kind of software applications so it is called as programming suite.
Ø It is installable software as JDK software.
Ø Latest version is 7.0 or 1.7 (Dolphin)
Ø This module is given to develop stand-alone applications, desktop applications, and two-tier applications…
Ø The application that is specific to one computer and contains main() method is called as stand-alone application.
Ø The stand-alone application that contains GUIness is called as Desktop application.
Ø The application that contains two layers communicating with each other is called as two-tier application.
Note: layer represents logical partition in the application having logics.




There is given many features of java. They are also called java buzzwords.

Simple
Java is simple in the sense that:
Syntax is based on C & C++ (so easier for programmers to learn it after C, C++).
Removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection in java.

Object-oriented
Object-oriented means we organize our software as a combination of different types of objects that incorporates both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules.
Basic concepts of OOPs are:
        Object
        Class
        Inheritance
        Polymorphism
        Abstraction
        Encapsulation

Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet.

Robust
Robust simply means strong. Java uses strong memory management. There is lack of pointers that avoids security problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java. All these points make java robust.

Secured
Java is secured because:
        No explicit pointer
        Programs run inside virtual machine sandbox.
With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
Some security can also be provided by application developer through SSL, JAAS, cryptography etc.




Platform Independent
A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides software-based platform.
The Java platform differs from most other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms.
It has two components:
        Runtime Environment
        API (Application Programming Interface)

Architecture-neutral
Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence Java runtime system.

High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a compiled language (like c, c++ ...)

Interpreted
Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light weight process.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it shares the same memory. Threads are important for multi-media, Web applications etc.


Difference between JDK, JRE and JVM

JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java byte code can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

The JVM performs four main tasks:
Ø Loads code
Ø Verifies code
Ø Executes code
Ø Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is used to provide runtime environment. It is the implementation of JVM.  It physically exists. It contains set of libraries + other files that JVM uses at runtime.

JDK
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.



API (Application Programming Interface)
Ø It is the base for the programmer to develop certain software technology based applications.
Ø Every software technology used built-in API's. Using these API’s the programmers can develop user defined API’s and software applications.
Ø In "c" language API is set of functions which come in the form of header files.
Ø In "c++" language API is set of functions, classes which come in the form of header files.
Ø In "Java" language API is set of classes, interfaces, enums, annotations which come in the form of packages.
The three types of API in java:
ü Built-in api’s
ü User define api’s
ü Third part api’s

Ø Generally the java related api’s came as in the form of jar files (java style zip file).
Ø rt.jar file represents all the built-in (Official core java) api’s of jdk software.
What happens at compile time?
At compile time, java file is compiled by Java Compiler and converts the java code into bytecode.



What happens at runtime?
At runtime, following steps are performed:


 




Can you save a java source file by other name than the class name?
Yes, like the figure given below illustrates:

 
To compile: javac Demo.java
To execute: java Simple

Can you have multiple classes in a java source file?
Yes, like the figure given below illustrates:
 
In java, there are two types of data types:
Ø primitive data types
Ø non- primitive data types (reference)

 




Data Type

Default Value

Default size

boolean

false

1 bit

char

'\u0000'

2 byte

byte

0

1 byte

short

0

2 byte

int

0

4 byte

long

0L

8 byte

float

0.0f

4 byte

Double

0.0d

8 byte


Why char uses 2 byte in java and what is \u0000?
Because java uses Unicode system rather than ASCII code system. \u0000 is the lowest range of Unicode system.

Unicode System
Unicode is a universal international standard character encoding that is capable of representing most of the world's written languages.


Why java uses Unicode System?
Before Unicode, there were many language standards:
ü ASCII for the United States.
ü ISO 8859-1 for Western European Language.
ü KOI-8 for Russian.
ü GB18030 and BIG-5 for Chinese, and so on.

This caused two problems:
1.  A particular code value corresponds to different letters in the various language standards.
2.  The encodings for languages with large character sets have variable length. Some common characters are encoded as single bytes, other require two or more byte.
To solve these problems, a new language standard was developed i.e. Unicode System. In Unicode, character holds 2 byte, so java also uses 2 bytes for character.
Lowest value: \u0000
Highest value: \uFFFF