Tuesday, 7 August 2018

JAVA VIRTUAL MACHINE



When a Java program is compiled it is converted to bytecode, which is then executed by the
Java Interpreter by translating the bytecode into machine instructions. Program in Java
runtime environment, which is used to interpret bytecode, is called Java Virtual Machine.
Any machine for which java interpreter is available can execute this bytecode. That’s why
java is called as Machine Independent and Architecture Neutral. The JVM plays the main
role to making Java portable. Java is Machine Independent and Architecture Neutral



IMPLEMENTING A JAVA PROGRAM



Steps to be followed to implement a Java Program:
Creating the program
Compiling the program
Running the program

Creating the program
We can create a program using any text editor.
Class Sample
{
public static void main(String args[])
{
System.out.println(“ HELLO “);
}
}
We must save this program with the filename Sample.java ensuring that the filename and
classname should be same. This file is called as source file. If a program contains multiple
classes, the filename must be the classname of the class containing the main method.

Compiling the program
C:\> javac Sample.java
The javac compiler creates a file called Sample.class that contains the bytecode version of the
program.

Running the program
C:\> java Sample
Now the interpreter looks for the main method in the program and begins execution from
there.

JAVA TOKENS



Smallest individual units in a program are known as Tokens. The complier recognized them
for building up expressions and statements. Java languages include 5 types of Tokens. They
are:
# Reserved Keywords
# Identifiers
# Literals
# Operators
# Separators

Keywords:
A keyword is a word that has special meaning defined by the Java programming language.
The program shown earlier in Listing 1-1 uses four keywords:public, class, static, and void.
In all, Java has 51 keywords. They’re listed in alphabetical order in Table 1-1. abstract do if
package synchronized boolean double implements private this break else import protected
throw byte extends instanceof public throws case false int return transient catch final
interface short true char finally long static try class float native strictfp void


Identifiers:
An identifier is a word that you make up to refer to a Java programming element by
name. Although you can assign identifiers to many different types of Java elements, they’re
most commonly used for the following elements:
Classes, such as the HelloApp class in Listing 1-1
Methods, such as the main method in Listing 1-1
Variables and fields, which hold data used by your program
Parameters, which pass data values to methods

Comments:
A comment is a bit of text that provides explanations of your code. Comments are completely
ignored by the compiler, so you can place any text you wish in a comment. Using plenty of
comments in your programs is a good idea to explain what your program does and how it
works.
Java has three basic types of comments:
end-of-line comments
traditional comment
Multi comments
JavaDoc comments.

End-of-line comments (single Line comments):
An end-of-line comment begins with the sequence // and ends at the end of the line. You can
place an end-of-line comment at the end of any line.
Everything you type after the // is ignored by the compiler. For example:
total = total * discountPercent; // calculate the discounted total
If you want, you can also place end-of-line comments on separate lines,
like this:
// calculate the discounted total
total = total * discountPercent;
You can place end-of-line comments in the middle of statements that span
two or more lines. For example:
total = (total * discountPercent) // apply the discount first
+ salesTax; // then add the sales tax

Traditional comments (Multi Line comments):
A traditional comment begins with the sequence /* and ends with the sequence */ and can
span multiple lines. For example:
/* HelloApp sample program.
This program demonstrates the basic structure
that all Java programs must follow. */
A traditional comment can begin and end anywhere on a line. If you want, you can even
sandwich a comment between other Java programming elements, like this:
x = (y + /* a strange place for a comment */ 5) / z;
Usually, traditional comments appear on separate lines. One common use for traditional
comments is to place a block of comment lines at the beginning of a class to indicate
information about the class such as what the class does, who wrote it, and so on. However,
that type of comment is usually better coded as a JavaDoc comment, as described in the next
section.
You may be tempted to temporarily comment out a range of lines by placing
/* in front of the first line in the range and */ after the last line in the range.
However, that can get you in trouble if the range of lines you try to comment
out includes a traditional comment. That’s because traditional comments
can’t be nested. For example, the following code won’t compile:
/*
int x, y, z;
y = 10;
z = 5;
x = (y + /* a strange place for a comment */ 5) / z;
*/
Here, I tried to comment out a range of lines that already included a traditional comment.
Unfortunately, the */ sequence near the end of the fifth line is interpreted as the end of the
traditional comment that begins in the first line. Then, when the compiler encounters the */
sequence in line 6, it generates an error message.

Multi Comments (Comments with comments or Nested comments):
Here, comments with in comments, nested comments. It can be represented with
/** Multi comments or Comments with in comments or Nested comments */

JavaDoc comments:
JavaDoc comments are actually a special type of traditional comment that you can use to
automatically create Web-based documentation for your programs. Because you’ll have a
better appreciation of JavaDoc comments when you know more about object-oriented
programming, I devoted a section in Book III, Chapter 8 to creating and using JavaDoc
comments.

JAVA PROGRAM STRUCTURE



Java program may contain many classes of which only one class defines a main method.
Documentation Section
The documentation section comprises a set of comment lines giving the name of the program,
and other details.
Package Statement
This statement declares a package name and informs the compiler that the classes defined
here belong to this package
Import Statement
This is similar to #include statement in c/c++
Ex: import java.io.*;
This statement instructs the interpreter to load the methods contained in the package java.io.
Interface Statement
This is an optional section and is used only when we wish to implement the multiple
inheritance feature in the program.
Class Definition
A java program may contain multiple class definitions, which contains business logic
methods.
Main Method Class
Since every Java program requires a main method as its starting point, this class is the
essential part of a java program.

SIMPLE JAVA PROGRAM

Class Example
{
public static void main(String args[])
{
System.out.println(“Welcome to Java”);
}
}

Save this file as Example.java same as class name
Class Example
It defines a class named Example using a keyword class. After that, class definition is
specified within curly braces.

public static void main(String args[])
This is the point from where the program will start the execution. The public keyword
is used to control the access of various class members. If member is public it can be accessed
outside the class. So we have to declare main( ) as public because it has to be invoked by the
code outside the class when program is executed. Static keyword allows the main( ) method
to be executed without creating an object of that class, and void means main( ) method does
not return any value.

String args[]
String is a predefined class and it takes any type of variable. [ ] represents free array.
args represents reference variable of string type.
System.out.println(“Welcome to Java”);
System is a class from java.lang package that contains all I/O related reference variables. Out
is a variable of system class. println( ) function is used to display this line.
Running the program
First set the path
location
C:\ set path=c:\jdk 1.3\bin;%path%
Compile the program
C:\> javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode version of
the program.
Run the Program
C:\> java Example
Output: Welcome to java

JAVA ENVIRONMENT


JAVA ENVIRONMENT
It is a product from sun micro systems which is a collection of ‘n’ number of tools and
utilities which are used together to develop dynamic applications using java. The
development tools are part of the system known as Java Development Kit (JDK) and the
classes and methods are part of the Java Standard Library (JSL), also known as the
Application Programming Interface (API).

Tools of Java Development Kit (JDK)

1. Javac (Java Compiler) :
Usage: javac <filename.java>
It stands for Java Compiler which takes the source code and translates into byte code.
2. Java (Java Interpreter) :
Usage: java <filename>
It stands for Java Interpreter that interprets the byte code and produces the output.

3. applet viewer (for viewing Java applets) :
Usage: applet viewer <filename.java>
It is used to run applet based programs that provides graphical interface

4. Javap (Java help) :
Usage: javap <fully qualified class name>
It stands for Java Disassembler which will explore all methods and properties of the given
class.

5. Jdb (Java Debugger) :
Usage: jdb <class file>
It stands for Java Debugger. It makes the class file to execute line by line interruption.

6. Java doc (Java Documentation) :
Usage: javadoc <filename.java>
It is used to create HTML files for every class and method used in the program.

Application Programming Interface (API)
The Java Standard Library includes hundreds of classes and methods grouped into several
functional packages. Most commonly used packages are:

Language Support Package:
A collection of classes and methods required for implementing basic features of java.

Utilities Package:
A collection of classes to provide utility functions such as date and time functions.

I/O Package:
A Collection of classes required for Input/Output manipulations

Networking Package:
A collection of classes for communicating with other computers via network.
AWT Package:
The Abstract Window Tool Kit package contains classes that implements platform
independent graphical user interface.

Applet Package:
This includes a set of classes that allows us to create Java applets.

JAVA AND WORLD WIDE WEB


JAVA AND WORLD WIDE WEB
World Wide Web (WWW) is an open-ended information retrieval system designed to be used
in the Internet's distributed environment. This system contains what are known as Web pages
that provide both information and controls.
Java was meant to be used in distributed environments such as Internet. Since, both the Web
and Java share the same philosophy, Java could be easily incorporated into the Web system.
Before Java, the World Wide Web was limited to the display of still images and texts.
However, the incorporation of Java into Web pages has made it capable of supporting
animation, graphics, games and a ,vide range of special effects. With the support of Java, the
Web has become more interactive and dynamic. On the other hand, with the support of Web,
we can run a Java program on someone else's computer across the Internet.

WEB BROWSERS
Internet is a vast sea of information represented in many formats and stored on many
computers. A large portion of the Internet is organized as the World Wide Web, which uses
hypertext. Web browsers are used to navigate through the information found on the net. They
allow us to retrieve the information spread across the Internet and display it using the
hypertext markup language (HTML). Examples of Web browsers: Hot Java, Netscape
Navigator, and Internet Explorer.

JAVA AND INTERNET



Java is strongly associated with the Internet because of the fact that the first application
program written in Java was HotJava, a Web browser to runapplets on Internet. Internet users
can use Java to create applet programs and run them locally using a "Java-enabled browser"
such as HotJava.
Internet users can also set up their Web sites containing Java applets that could be used by
other remote users of Internet. The ability of Java applets to hitch a ride on the Information
Superhighway has made Java a unique programming language for the Internet. In fact, due to
this, Java is popularly known as Internet language.

HOW JAVA DIFFERS FROM C AND C++



Java and C
Java is a lot like C but the major difference between Java and C is that Java is an objectoriented
language and has mechanism to define classes and objects. In an effort to build a
simple and safe language, the Java team did not include some of the C features in Java.
Java does not include the C unique statement keywords goto, sizeof, and typedef.
Java does not contain the data types struct, union and enum.
Java does not define the type modifiers keywords auto, extern, register, signed, and unsigned.
Java does not support an explicit pointer type.
Java does not have a preprocessor and therefore we cannot use # define, # include, and # ifdef
statements.
Java does not support any mechanism for defining variable arguments to functions.
Java requires that the functions with no arguments must be declared with empty parenthesis
and not with the void keyword as done in C.

Java and C++
Java is a true object-oriented language while C++ is basically C with object-oriented
extension. C++ has maintained backward compatibility with C. It is therefore possible to
write an old style C program and run it successfully under C++. Java appears to be similar to
C++ when we consider only the "extension" part of C+ +. However, some object-oriented
features of C++ make the C++ code extremely difficult to follow and maintain.
Java does not support operator overloading.
Java does not have template classes as in C++.
Java does not support multiple inheritance of classes. This is accomplished using a new
feature called "interface".
Java does not support global variables. Every variable and method is declared within a class
and forms part of that class.
Java does not use pointers.
Java has replaced the destructor function with a finalize( ) function.
There are no header files in Java.

JAVA FEATURES



Compiled and Interpreted
Java combines both these approaches thus making java a two-stage system. First, Java
compiler translates source code into what is known as bytecode instructions. Bytecode are not
machine instructions and therefore, in the second stage, Java Interpreter generates machine
code that can be directly executed by the machine that is running the Java Program.

Platform-Independent and Portable
Java is compiled to an intermediate form called Java Byte-Code or simply byte code. A Java
program never really executes immediately after compilation on the host machine. Rather,
this special program called the Java Interpreter or Java Virtual Machine reads the bytecode,
translates into the corresponding host machine instructions and then executes the machine
instruction. A java program can run on any computer system for which a JVM and some
library routines are installed. Because of Platform Independence Java programs can be
portable from a mini computer up to a super computer irrespective of H/W requirements and
OS Base.

Object-Oriented
Java is one of the Pure Object Oriented Programming Language where every construction of
the program should be written under the implementation of class which is the basic part of
OOPS.

Robust and Secure
Robustness is measured with the help of 2 concepts 1) Memory Management 2) Exception
Handling

In traditional applications, the programmer is responsible for both allocations and
de allocation of memory. In Java, Memory allocation is controlled by JVM where object
creation is done by the user de allocation is taken by Garbage Collector
In C,C++ error handling is done manually even before running the program. If any run-time
error comes the program is in inconsistent state which leads to memory leak. Java supports
pure exception handling which guards the program from abnormal situations.
Java is intended to work in networked and distributed environments by providing security.
Security becomes an important issue for a language that is used for programming on Internet.
Java Systems not only verify all memory access but also ensures that no viruses are communicated with an applet. The absence of pointers in Java ensures that programs cannot
gain access to memory locations without proper authorization.

Distributed
Java is designed as a distributed language for creating applications on networks. It has the
ability to share both data and programs. Java applications can open and access remote objects
on Internet as easily as they can do in a local system. This enables multiple programmers at
multiple remote locations to collaborate and work together on a single project.

Familiar, Simple and Small
By using Java different range of applications can be developed by keeping the common
structure which is understood by JVM. Java uses many constructs of C and C++ and
therefore, Java code looks like a C++ code.

Multithreaded and Interactive
Multithreaded means handling multiple tasks simultaneously. It is one of the important
features of Java that provides multi-tasking where 2 parts of a program can be runnable
concurrently by sharing the common block of resources. This feature greatly improves the
interactive performance of graphical applications.

High performance
Java performance is impressive for an interpreted language, mainly due to the use of
intermediate bytecode. Java architecture is also designed to reduce overheads during runtime.

Dynamic and Extensible
Java is capable of dynamically linking in new class libraries, methods and objects. In Java
classes that were unknown to a program when it was compiled can still be loaded into it at
runtime. Java programs support functions written in other languages such as C and C++.

Java Weaknesses:
Java is that it doesn’t directly support true decimal data.
Ex:
Double x = 5.02;
Double y = 0.01;
Double z = X + Y;
System.out.println(z);
Output:
5.029999999999999
But result is “5.03”