JAVA

JAVA

JAVA is a general purpose , object oriented programming language developed by Sun Microsystems of USA in 1991. Originally called oak by Jamesh Goslins ( one of the inventors of the languge. Java was designed for the development of software for computer electronic devices like TV, VCRs, tosters and many other electronic devices.

Java features

  1. Compiled and interpreted: Usually a computer language is compiled or interpreted. Java combines both these approaches and thus making java a two state system. First java compiler translates the 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. Hence we can say java is both compiled and interpreted.
  2. Platform independent and portable
  3. The most significant contribution of java over other languages is its portability. Java programs can be easily moved from one computer to another anywhere , anytime. Changes and upgrades in operating system, processors and other system resources will not force any change in java programs.

Java ensures portability in two ways. First java compiler generates the byte code instructions that can be implemented on any machine. Secondly the size of the primitive data types are machine independent.

  1. Object Oriented

Java is a true object oriented language. Almost everything in java is an object. All program code and data reside with object and classes. Java comes with an extensive sets of classes , arranged in packages that we can use in our programs by inheritance.

  1. Robust and Secure Java is a robust language. It provides many safeguards to ensure reliable code. It has strict compile time and run time checking for data types. It is designed as a garbage collected language relieving the programmers virtually all memory management problems. Java also incorporates the concept of exception handling which captures series errors and eliminates any risk of system crashing.

Security becomes one of the most important issue for a programming language that is used over internet. Threat of viruses and abuse of resources are everywhere. Java systems not only verify all memory access but also ensure 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.

  1. 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 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.
  2. Simple , Small and familiar : Java is a small and simple language. Many features of c  and c plus plus that are either redundant or sources of unreliable code are not part of java. For example java does not use pointers , pre-processor header files , goto statement and many others. It also eliminates operator overloading and multiple inheritance.
  3. Multithreaded and interactive : Multithreaded means handling multiple tasks simultaneously . Java supports multithreaded programs. This means that we need not to wait for the application to finish one task before beginning another.
  4. High performance : Java performance is impressive for an interpreted language,mainly due to the use of intermediate bytecode. Java architecture is designed to reduce overheads during run time . The incorporation of multithreading enhances the overall execution speeds of java program.
  5. Dynamic and Extensible : Java is a dynamic language.It is capable of dynamically linking in new class libraries, methods and objects. Java can also determine the type class through a query , making it possible to either dynamically link or abort the file depending on the response.

Java programs support functions written in other languages such as c / c ++. These functions are known as native methods.  

  1. Ease of Development : JAVA 2 Standard Edition ( J2SE) supports features such as Generics, Enhanced For Loop, Autoboxing or unboxing , static import and Annotation.These features reduce the work of a programmer by shifting the responsibility of creating the reusable code to the compiler. The resulting source code is free from bug as the errors made by the compiler are comparatively less than those made by the programmers.
  2. Scalability and performance : J2SE 5.0 assures a significant increase in scalability and performance by improving the start up time and reducing the amount of memory used in j2 runtime environment.

Java and C

Java is a lot like C but the major difference between java and C is that Java is an Object Oriented Language and has mechanisms to define classes and objects where as Language C is procedure Oriented. Java Team did not include some of the features of C in Java to make it simple and safe :

  1. Java does not include C keywords like sizeoff and typedef
  2. Java does not contain data type like struct and union
  3. Java does not have a pre processor and therefore we cannot use #define, #include and #ifdef statement.
  4. Java does not support explicit pointer type.
  5. Java does not define the type modifiers keywords like auto, extern, register, singed and unsigned.
  6. Java adds labelled break and continue statement
  7. Java adds new operators such as instanceof and >>
  8. Java requires that functions with no arguments must be declared with empty parenthesis and not with the void keyword as done in C.
  9. Java adds many features required for object oriented programming.

Java and c Plus Plus

Java is a true object oriented language while C ++ is basically C with object oriented extension. That is what the increment operator indicates. C ++ has maintained the drawback compatibility with C . Listed below are some major C Plus Plus features that were intentionally omitted from Java

  1. Java does not support operator overloading.
  2. Java does not have template classes as that of in C Plus Plus.
  3. Java does not support multiple inheritance in classes. This is accomplished using a new feature called interface.
  4. Java does not support gobal variables. Every variable amd method is declaed within a class and forms part of that class.
  5. Java does not use pointers.
  6. Java has replaced destructor function with a finalize function.
  7. There are no header files in java.

C Plus Plus is a super set of C while Java is neither subset nor super set of C / C ++. 

Java environment

Java Environment includes a large number of development tools and hundreds of classes and methods . The development tools are part of the system known as JDK ( Java Development Kit ) and classes and methods are part of Java Standard Library ( JSL ) , also known as the Application Programming Interface ( API ) .

Java Development Kit ( JDK )

The Java Development Kit comes with a collection of tools used for developing and running Java Programs. They include :

  1. Appletviewer ( for viewing java applets) : Enables us to run java applets ( without actually using a Java-compatible browser )
  2. Javac ( java compiler) : which translates java source codes to byte code files that the interpreter can understand.
  3. Java( Java Interpreter) : which runs applets and applications by reading and interpreting bytecode files.
  4. Javap ( Java diassembler) which enables us to convert byte code files into a program description.
  5. Javah( for C header files ) : Produces header files for use with native methods.
  6. Javadoc ( for creating HTML documents ) creates Html format documentation from java source code files.
  7. Jdb( java debugger ) : which helps us to find errors in our programs.

Application Programming Interface ( API )

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

  1. Language Support Package : A collection or classes and methods required for implementing basic features of java.
  2. Uitlity Package : A collection of classes to provide utility functions like date and time functions.
  3. Networking Package : A collection of classes for communicating with other computers via internet.
  4. Input / Output Package : A collection of classes used for input/output manipulations.
  5. AWT Package : The Abstract Window Tool Kit package contains classes that implements platform independent graphical user interface.
  6. Applet Package : This includes a set of classes that allows us to create Java applets.

Java is a general purpose , object oriented programing language. We can develop to types of java programs :

  1. Stand Alone Applications.
  2.  Web applets

Stand Alone applications are programs written in Java to carry out certain tasks on a stand alone local computer. Java can be used to develop programs for all kinds of application, which earlier were developed using languages like c and c Plus plus.

HotJava itself us a Java application program. Executing a stand alone java programs involves two steps :

  1. Compiling source code intobyte code using javac compiler.
  2. Executing the bytecode program using java interpreter.

Applets are small java programs developed for Internet applications. An applet located on distant computer ( server ) can downloaded via internet and executed on local computer ( Client ) using a java capable browser. We can develop applets for doing anything from simple animated graphics to complex games and untilities. Since applets are embedded in an HTML ( Hyper Text Mark Up Language ) document and run inside a web page, creating and running applets are more complex than creating an application.

Stand alone programs can read and write files and perform specific certain operations that applets cannot do. An applet can only run with in a web browser.

Simple Java Programs

Class Sampleone

{

 Public static void main ( String srgs[ ])

{

 System.out.println(“ Java is better than  C Plus Plus “);

}

}

Class declaration

The first line

Class Sampleone

Declare a class which is an object oriented construct. Java is a true object oriented language and therefore everything must be placed inside a class . class is a keyword and declares that a new class definition follows. Sampleone is a java identifier that specifies the name of the class to be defined.

Opening Brace :

Every class in java begins with an opening brace “{“ and ends with an matching closing brace “}”appearing in the last line in the example.

The Main Line

The third line

Public static void main ( String args[])

Defines a method name main. Every java application must include the main method. This is the starting point of interpreter to be gin the execution og the program.  A java application can have any number of classes but only one of them must include main method to initiate the execution.

Public : The keyword public is an acces specifier that declares the main method as unprotected and there fore making it accessible to the other classes . This is similar to the C ++ public modifier.

Static : Next appears the keyword static which declares this method as one that belongs to the entire class and not a part if any objects of the class. The main must always be declared as static since the interpreter uses this method before any objects are created.

Void : The type modifier void states that the main method does not return any value .

The output line :

The only executable statement in the rogram is

System.out.println( “ Java is better than  C ++ “ ) ;

Since java us a true object oriented language , every method must be a part of an object. The println method is a member of the out object, which is static data member of System class. The line prints the string

Java is better than C ++

Java program example with multiple statements

Import java.lang.math;

Class squareroot

{

Public static voida main(String args[ ] ))

{

Double x = 5; // declaration and intitialization

Double y ;

Y = Math.sqrt(x);

System.out.ptintln (“y = “ + y );

}

}

Use of math functions

Import java.lang.Math :

The purpose of this statement is to instruct the interpreter to load the Math class from the package lang. ( This language is similar to inclue language in C ) . Math class contain the sqrt method required in the program.

Comments

Java permits both the single line  comments and multiple line comments . The single line comments begin  with // and ends at the end of the line . For longer comments we create comments by starting with a /* and ending with a */

An application with two classes

Class Room

{

float length;

float breadth;

   void getdata( float a , float b)

{  length = a;

Breadth = b;

}

}

Class roomarea

{

Public static void main ( String args[ ])

{

Float area ;

Room room1 = new room ();// creates an object room 1

Room1.getdata ( 14, 10 ); Assigns value to length and breadth

Area = room1. Length * room1. Breadth;

System.out.ptintln( “ Area = “ + area);

}

}

Java tokens :

A java program is basically a collection of classes. A class is defined by a set of declaration statements and methods containing executable statements. Smallest individual units in a program are known as tokens. The compiler recognizes them for building up expressions and statements. Java language includes fine types of tokens:

  1. Reserved keywords
  2. Identifiers.
  3. Literals
  4. Operators
  5. Separators

Identifiers: Identifiers are program designed tokens . They are used for naming classes, methods, variables, objects, labels, packages and interfaces in a program. Java identifiers views the following rules:

  1. They can have alphabets, digits and the underscore and dollar sign characters.
  2. They must not begin with a digit.
  3. Uppercase and lowercase letters are distinct.
  4. They can be of any length.

For example

Average

Sum

Literals : Literals in java are sequence of characters ( digits , letters and other characters) that represent constant values to be stored in variables. Java specifies five major types of literals :

  1. Integer literals
  2. Floating point literals
  3. Character literals
  4. String literals
  5. Boolean literals

Implementing a  Java Program

Implementation of a java application program involves a series of steps. They include :

  1. Creating the program
  2. Compiling the program
  3. Running the program .
  1. Creating the program

Class test

{

Public static void main ( String args[ ] )

{

System.out.println(“Hellow ! “);

System.out.println(welcome to the world of java “);

System.out.println(“ Let us leran java “);

}

}

We must save this program file as test.java ensuring that the file name contains the class name properly. This file is calles the source file . note that all java source files will have the extension java. Note that if a program contains multiple classes, the file name must be the classname of the class containing the main method.

Compiling the program : to compile the program we must run the java compiler javac, with the name of the source file on the command line as shown

Javac test.java

If everything is okay, the javac compiler creates a file called test.class containing the bytecodes of the program. Note that the compiler automatically names the bytecode file as

<classname>.class

Running the Program :

We need to use the java interpreter to run a stand alone program. At the command promt, type

Java test

Now, the interpreter looks for the main method in the program and begins execution from there . When executed , our program displays the following :

Hello!

Welcome to the world of java

Let us learn java

Leave Comment

Important Topics

Title
OOPS
Data Types
JAVA
JVM
Command Line Args
Machine Neutral
Scope of Variables
Operators :
Generic Type Casting
IF Else
Switch Statement
The while statement
The do statement
The for statement
Classes, objects and methods
Constructors
Methods Overloading
Static Members
Nesting of methods
Inheritance : Extending a Class
Overriding methods
Overriding methods
Final variable and methods
Abstract class in Java
Visibility control