Wednesday, 20 July 2011

java

History of the Developement of Java

Java is a programming language and environment invented by James Gosling and others in 1994. Java was originaly named Oak and was developed as a part of the Green project at the Sun Company.
The writing of Java began in December of 1990. Patrick Naughton, Mike Sheridan, and James Gosling and were trying to figure out the "next wave" in computing.

Started out in 1991 as Project Green focussed on O/S software for consumer electronic devices James Gosling recognized inadequacy of C++ and initiated development of Oak language Green went through several false starts before dissolving Small group decided to adapt Oak (later named Java) to a web technology -- result was a new web browser, WebRunner (later named HotJava), operational in 1994 Paper on Oak byte codes presented by Gosling at Programming Language Design and Implementation (PLDI) conference in 1995
Introduction
Java is an object-oriented programming language developed by Sun Microsystems and released in 1995. Modelled after C++, the Java language was designed to be small, simple, and portable across platforms and operating systems, at both the source and binary level. One of the resons for Java's popularity is its ability to bring executable content to the web.Java has only the necessary functionality needed to implement its feature set. It has omitted the features of C and C++ which have been considered to be "unsafe" pointer "forging" operator overloading static objects Memory is managed automatically, relieving the programmer from being responsible for freeing unused space There is no Java preprocessor - the program that you see is the same program that the Java compiler sees.

 

Let The Games Begin...

CONCEPTS OF OOPS
As you know all computer programs consist of two elements: code and data.
Furthermore, a program can be conceptually organized around its code or around its data. That is some programs are written around "'what is happening" and other are written around "who is being affected". These are two paradigms that govern how a program is constructed. The first way is called process oriented model. This approach characterizes a program as a series of linear steps. The process oriented model can be thought of as code acting on data. Procedural languages such as C employ this model to considerable success. To manage increasing complexity the second approach called object oriented programming was conceived. Object oriented programming organizes a program around its data( that is its object) and a set of well defined interfaces to that data. An object oriented program can be characterized as data controlling access to code.

CLASSES
The importance of object-oriented programming is that it enables programmers to organize their programs in ways that resemble the organization of objects in the real world, which makes programming easier and more logical. Using object- oriented programming, the overall programs are made up of many different components (called "objects"), each of which has a specific role in a program and can talk to the other components in predefined ways.Classes are called as a template or they can be called as a prescription of an object.
Without class no object can exist and every object has a class.

OBJECTS
Every thing in this world is called an object. An object is created by the method and data in the class.
METHODS
Methods are nothing but functions. In procedural languages these are called functions. In OOP they are called method. It is a function that can be used by the object or an object can be created by the method.
PIE FEATURES OF OOPS
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.


ENCAPSULATION
Encapsulation is a mechanism that binds together code and data it manipulates, and keeps both safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.
INHERITANCE
Inheritance is the process by which one object acquires the properties of another object.
This is important because it supports the concept of hierarchical classification. Most knowledge is made by hierarchical classification.
POLYMORPHISM
It is a feature that allows one interface to be used for general class of actions. The specific action is determined by the exact nature of the situation. More generally the concept of polymorphism is often expressed by the phrase "one interface, multiple methods".
WHAT IS JAVA?
Java is an object oriented programming language. Java is an enhanced form of C++. From C java drives its syntax. Many of java's object oriented features are influenced by C++. Java is platform independent. It can run on any platform. Java has a compiler and an interpreter.
Its compiler generates intermediate code which is the further interpreted by its interpreter.
PROGRAMMING STRUCTURE OF JAVA
Now lets look at the programming structure of java. Every program should be started from the reserved word class. Let us see a sample program.
Class Example {
Public static void main(String arg[]) {
System.out.println("this is first program in java");
}
}

every program of java must be saved in the BIN folder of the JDK. The file's extension should be somefile.java. the file name should be same as the name of class. In this case it would be Example.java.
CONTROL STATEMENTS IN JAVA
Java has two control statements which are if and else if. They are used as follows.
If (condition) statements
Else
Statements
Parenthesis can also be used if there are more than one statements in if or else closure.

LOOPS IN JAVA
There are three types of loops in java, for, while and do while. The syntax of loops is as follows.
For(declaration;condition; increment/decrement)

{
statemenst

}
while(condition)

{
statements

}
do
{
statements
}while(condition)

OPERATORS IN JAVA
There are different kinds of operators in java which are as follows.
< less than
> greater than
= = equal to
= assignment operator
? ternary operator
| | Boolean OR
&& Boolean AND
++ increment operator
-- decrement operator
% Modulus
+= addition assignment
-= subtraction assignment
*= multiplication assignment
%= modulus assignment
>> shift right
<< shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
ARRAYS IN JAVA
An array is a group of like-typed variables that are referred to by a common name. Array of any type can be created and may have one or more dimensions.
ONE DIMENSIONAl ARRAY
A one dimension array is essentially a list of like typed variables. To create an array you first must create an array variable of desired type. The general form of the one dimension array is like as follow.
Type var-name[];
Here type declares the base type of the array. The base type determines the data type of each element that comprises an array. For example the following declares an array named month_days with type ":array of int":
Int month_days[];
MULTIDIMENSIONAL ARRAYS
In java multidimensional arrays are actually arrays of arrays. These as you might expect look and act like regular multidimensional arrays. However as you will see there are a couple of differences. To declare a multidimensional array variable, specify each additional index using another set of square brackets. For example the following declares a two dimensional array variable called twoD.
Int twoD[][]= new int[4][5]
CLASSES AND OBJECTS IN JAVA
When you define a class you declare its exact form and nature. You do this by specifying the data that it contains and the code that operates on that data. While very simple classes may contain only code data, most real world classes contain both.
A class is declared by the use of the class keyword. General form of class declaration is as follows.
Class classname
{

type instance variable1
type instance variable2

type methodname(parameter list)
{
// body of method
}

to create an object of a certain class we use a new word new. Consider an example.
Class myclass
{

}
classname objectname=new classmethod();

CLOSER LOOK AT NEW
As explained the new operator allocates memory for an object. It has genral form as:
Class-var=new classname();
Here class-var is a variable of the class type being created. The class name followed by parentheses specifies the constructor for the class. A constructor defines what occurs when an object of a class is created. Constructors are important part of all classes and have many significant attributes.
CONSTRUCTORS OF JAVA
A constructor is a method which is invoked when an object of a class is created. It has no return type in java. Its name must be same as the name of class. It can accept parameter . here we look at how they function in java.
Class student
{
int age;
string name;

student() //constructor
{
age=0;
name="junaid";
}

in java the overloading of constructors is possible. An overloading means using same name of constructor with different parameters. An example is given.
Class student
{
int age;
string name;

student() //constructor
{
age=0;
name="junaid";
}

student(int n, string s) // constructor overloading
{
age=n;
name=s;
}

DESTRUCTORS IN JAVA
In C++ dynamically allocated objects must be manually released by use of a delete operator. Java uses different approach. the technique is called
GARBAGE COLLECTION.
Java uses finalize() method for garbage collection. To add a finalize to a class you simply define the finalize() method. The java run time calls that method whenever it is about to recycle an object of that class. Inside the finalize() method you will specify those actions that must be performed before an object is destroyed. Tha garbage collector runs periodically checking for objects that are no longer referenced by any running state or indirectly though other referenced objects.
void finalize()
{
finalization code
}

METHODS IN JAVA
Methods in java can have return type and can accept the parameters. They can be called without creation of objects. These methods are called static methods. Following is an example of methods.
Class junaid
{
int empno;
void jd()
{
empno=0;
}
void display()
{
System.out.print("employee number"+empno)
}
}
class demo
{
public static void main(String arg[])

{
emp A=new emp();
A.jd();
A.diisplay();
}
}

methods in java can be overloaded and override .

INHERITANCE IN JAVA
Inheritance means the parent class can have some child classes and the child classes can have or can inherit all the properties of parent class. The parent class can also be called as super class and the child class can be called as subclass.
A keyword extends is used in order to make a child class of parent class. Following is an example of this.
Class a
{
//variables
}
class b extends a
{
// variables
}

all the variables of a super class cannot be accessed by the base class except of those which are public. Private members of a super class cannot be accessed by the child class.
Similarly constructors of a super class can also be used by the child class. To call a method of a super class through a base class, we use a keyword super. This can be used to call a method of super class. Following is an example.
Class A
{
// class variables
void method()
{
System.out.print("hi");
}
}
class B extends A
{
// class variable
void method2
{
super.method();
System.out.println("its me");
}
}
class demo
{
public static void main(String arg[])
{
B a=new B();
B.method2();
}
}

similarly multilevel inheritance is also possible in java. For example a parent class A can have two child classes B and C.

ABSTRACT CLASSES
Abstract classes are those which can be used for creation of objects. However their methods and constructors can be used by the child or extended class. The need for abstract classes is that you can generalize the super class from which child classes can share its methods. The subclass of an abstract class which can create an object is called as "concrete class". Following is an example
Abstract class A
{
abstract void method1();
void method2()
{
System.out.println("this is concrete method");
}
}
class B extends A
{
void method1()
{
System.out.println("B is implementation of method1");
}
}
class demo
{
public static void main(String arg[])
{
B b=new B();
b.method1();
b.method2();
}
}


EXCEPTION HANDLING IN JAVA
Run time errors are called as exceptions. Java provides a way to deal with these run time errors. A run time error can occur due to illegal operation such as an integer divided by zero. Java has a class called throw able that deals with exceptions and errors. This class has a subclass called exception. The exception class has further subclasses such as arithmetic exception, I/O exception, ArrayIndexOutOfBOund exception etc. there are two reserved words in java for dealing with exception, which are try and catch. We will look at some example that how we deal with exceptions.
Class myclass
{
public static void main(String arg[])
{
int a, b, c;
try
{
a=20;
b=0;
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println(":zero divide error");
}
}
}

in the above program the try clause tells the compiler to try to execute the code. But if it fails to execute then an exception is generated and is thrown which is caught by catch clause. In java there maybe multiple catches to catch an exception. The following is an example of it.
Class test
{
public static void main(String arg[])
{
int a,b,n[];
try
{
n=new int[2];
b=arg.length;
a=20/b;
n[2]=a;
System.out.println("RESULT"+a);
}
catch(ArithmeticException a)
{
System.out.println("zero divide error");
}
catch(ArrayIndexOutofBoundException e)
{
System.out.println("error"+e);
}
}
}

similarly there maybe multiple try clauses in java.

THROW AND THROWS
So far java runtime system was throwing exceptions. Your program can also throw exceptions explicitly using a throw statement. The general form of throw is as:
Throw throwable instance
Here throwable object must be an object of type throwable or a subclass of throwable. Here we see an example.
Class test
{
public static void ExcepTest() throws Arithmetic Exception
{
throw new ArithmeticExcption("demo");
}
public static void main(String arg[])
{
try
{
ExcepTest();
}
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}

in java if a method is capable of throwing an exception then it must specify its this behavior so that callers of that method can guard themselves against this exception. This can be done by using throws statement in declaration of that method. We will see a exception program to understand this clearly.
class Myexception extends Exception
{
protected int errno;
Myexception(int n)
{
errno=n;
}
public String toString()
{
return "Myexception:"+errno;
}
}
class test
{
public static void ExcepTest(int a) throws Myexception
{
if(a>1&& a<=10)
System.out.println("number:"+a);
Else
Throw new Myexception(a);
}
public static void main(String arg[])
{
try
{
ExcepTest(5);
ExcepTest(10);
ExcepTEst(15);
}
catch(Myexception c)
{
System.out.println("invalid number:"+e)
}
}
}

FINALLY CLAUSE
As exception is caught, the program terminates and you see the output, what ever it is. If in a program there is a chance of exception then you will put that code in try/catch clause. Now in same the program if you have some code which you want to be executed in every condition (whether before exception or after it is caught), then you will put that code in finally clause. The code in this clause executes in every condition even if the exception is generated and is caught. Following is the program.
Class myclass
{
public static void main(String arg[])
{
int a=3, b=0,c;
try
{
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println("zero divide error");
}
finally
{
System.out.println("checking of FINALLY clause ");
}

}
}

MULTITHREADING IN JAVA
Executable part of an application is called as thread. We often interact with threads while using many applications. For example, if we use MS-word application then we see that a thread (spell checker) runs continuously as we continue typing. It continuously checks the spelling of words we type, from its dictionary. Java provides a way to create these threads. There are two ways for creating threads in java. One is by extending THREAD class and other is by implementing EUNNABLE interface. We will see an example of creating thread. As we know that the main program is itself a thread so therefore we will see a sample program of main program.
Class test
{
public static void main(String arg[])
{
Thread t=Thread.currentThread();
System.out.println(t);
t.setName("test thread");
System.out.println(t)
}
}

the output of this program will give the thread's name that is "main", its priority that is 5 and its representation. The priorities of thread are between 1 and 10 the normal priority is
5. Now we will see how we create threads from extending thread class.

Class newthread extends Thread
{
newthread()
{
super("demo thread");
System.out.println("child thread:"+this);
Start();
}
public void run()
{
try
{
for(int i=5;i>0;i--)
{
System.out.println("child thread:"=i);
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println("child interrupted");
}
System.out.println("exiting child thread");
}
}
class demo
{
public static void main(String arg[])
{
new Newthread();
try
{
for(int i=5;i>0i--)
{
System.out.println("main thread:"+i);
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("main thread interrupted")
}
System.out.println("main thread exiting");
}
}

in java threads can be prioritized. They can be given priorities between 1 and 10. there are several methods for thread for example isAlive() and join(). There is possibility that one thread can communicate with another. For example one thread may want to know whether another thread is alive or dead. This is done by isAlive() method. If you want to know that a thread is finished or not, you can call isAlive() method defined by thread class. Its general form is:
final Boolean isAlive()
if it returns true then it means thread is running. If it returns false then thread has stooped. While isAlive() is occasionally useful, the method that you will commonly use to wait for a thread to finish is called join().
Final void join()throws InterruptedExcepption
This method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread until the specified thread joins it. Additional forms of join() allow you to specify a maximum amount of time that you want to wait for specified thread to terminate.
SYNCHRONIZATION
When two or more threads want to share some shared resources then it must be ensured that only one thread will use that resource at a time. The process by which it is done is called synchronization. We will see an example of it.
class callme
{
void call(String msg)
{
System.out.println("["+msg);
Try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("interrupted");
}
System.out.println("]");
}
}
class caller implements Runnable
{
String msg;
Callme target;
Thread t;
Public Caller(Callme targ, String s)
{
target=targ;
msg=s;
t=new Thread(this);
t.start();
}
public void run()
{
target.call9msg);
}
}
class Synch
{
public static void main(String arg[])
{
Callme target=new Callme();
Caller ob1=new Caller(target,"hello");
Caller ob2=new Caller(target,"Synchronized");
Caller ob3=new Caller(target,"world");
Try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("interrupted");
}
}
}

Conclusion
As Java's popularity grows, it becomes more and more crucial to provide reliable ways to write Java programs that perform scientific computation. There are basically two reasons why Java is often claimed to be inappropriate for scientific computing. The first reason is that Java is generally interpreted and is therefore unable to run at machine speed. The second reason is that no standard numerical libraries have been translated yet to Java bytecode (or source for that matter). The first reason seems to be less and less or a concern as native compilers are being provided by software developers, so that Java can be used as any other language to develop code on those platforms. Even the speed of applets can be raised to new levels with JIT techniques. However, compiled Java source on those platforms is of course not portable anymore as it is not targeting the JVM any more.

No comments: