Java evolution (History of Java)

22 November 2009

In 1990, the Sun Microsystems Inc, US has got a project, which is developing remote control software. Different remote controllers having different processors and so they have to develop different software. The team leader James Gausling has thought that why don't we develop single software which can run on different remote controllers. He decided to develop a new language. Generally on those days, all are used C language, which is system dependent.

They have developed a new language named OaK in 1993. But OaK name is already registered. So, they have decided to rename it as JAVA (Good quality of Tea is coming from Java Islands). The Sun Microsystems has released Java in June 1995 on the occasion of Sun World Conference.

Features of Java:


1. Simple - Java is a simple programming language. Learning and practicing Java is easy because of its resemblance with C and C++. The difficult concepts in C++ have been eliminated in Java.

Java = C++ - Complexities

. For example pointer concept has been eliminated in Java.

Question: Why pointers are eliminated in Java?
Pointers lead to confusion for a programmer. Pointers may crash a program. Using pointer virus and hacking programs can be written.

1. Object oriented - Unlike C++, Java is a purely object oriented programming language. Java programs uses objects and classes.

Object: An object is anything that exists in this real world. An object has properties and behaviors (actions).

In our program variables are used to represent properties. Actions are represented by methods. i.e.; An object contains variables and methods. i.e.; Objects need memory. JVM will allocate the memory required for objects.

Class: A class is a model or blue print for creating objects. Class doesn’t exist physically, it is only our idea. i.e.; A class contains the definition for variables and methods of its objects.

Below table depicts some class names and objects.

Class names Objects
Flower Lilli, Jasmine, Lotus
Book NoteBook, TextBook, RefBook
Actor Chiranjeevi, Kamal Hasan, Rajani
Actress Radha, Anushka, Tamnna, Sneha Ullal
Shirt T-Shirt, S-Sleve, Glasour
Sweet Jilebi, Coa, Kalakanda


C++ is not purely an object oriented programming language because without creating an object or a class we can write a C++ program. Whereas, without creating at least one class we can't write a program. So, Java is said to be a purely object oriented programming language.

3. Distributed: - Java is a distributed technology. Information is distributed on various computers on a network. Using Java, we can write programs which capture information and distribute ii to clients.

4. Robust: - Java programs will not crash easily because of its exception handling and its memory management features. Memory management was handled by JVM> i.e.; allocation and de-allocation of memory handled by JVM.

Memory Allocation: JVM's class loader sub system will allocate required memory for a program.

Memory de-allocation: JVM's garbage collector will free the allocated memory. Garbage collector will check the memory between every time interval and it used Mark and Sweep algorithm to de-allocate the memory for unused variables and objects.

Exception handling: Exception means a run time error. In Java we can handle the exceptions.

5. Secure: - Java enables the construction of virus free and tamper free systems.

6. Architecture neutral: - Java's byte code is not machine dependent. It can be run on any machine with any processor and with any O/S.

7. Portable: - A program yielding the same result on any computer is said to be portable. Java program give same results on all machines. Everything is clearly defined in Java specification and nothing is left to O/S.

8. Interpreted: - Java programs are compiled to generate the byte code. This byte code can be downloaded and interpreted by the interpreter in JVM.

9. High performance: - Along with interpreter, there will be JIT (Just in time) compiler which enhances the speed of execution.

Read more...

What made Java more popular?

Let's have a quick look at what made Java more popular among the existing programming languages like COBOL, FORTRAN, PASCAL, C, C++.

Programming language:


I'm going to ask some general questions before I explain about programming languages.

1. What is a language?
Your answer - ??
My answer - A language is a communication tool between two persons, for example you're reading this because you know the language English.

2. Why do we need a language?
Your answer - ??
My answer - A language is used to fulfill our needs (requests).

Like two humans can communicate with each other with a language, a human can communicate with computer by using programming languages to fulfill needs. The program that we wrote cannot be directly recognized by the computer. Computer recognizes only machine code. So, we have to convert our program into machine understandable signals. For this purpose we are having translators.

Translator

- It is a program which coverts program into machine understandable code (electric signals or pulses). There are three types of translators available.

Interpreter - Coverts only one line of the program at a time

Compiler - Coverts all lines of a program in a single step (Note: Compiler is 10 times faster than the interpreter)

Assembler - Converts assembly language instructions into machine level language.

Here I explain a sample process of compiler with C compiler. When you write and compile a program C language, the below tasks will be carried out
When we compile a program, the compiler will create a new object code (.obj) file. An object code is equivalent machine code for our program. Whenever we first execute our program, the compiler will create an executable file. An EXE file has the machine language instructions (A group of instructions that understand by a micro processor are called as instruction set) including header files also. (It directly executed without compiler). The first microprocessor in the world - 4044. Later on 8080, 8085, 8086, 8088, 80286, 80386, 80486, 80586 have been developed.

System dependent program


If a program is executable only on the computer system where it was developed - called system dependent program. All the existing languages before the invention of Java are system dependent. For example if you write a program on Windows which can't be executed on Linux. Hence, we can't use these languages to develop software which runs on internet.

Java is system independent, hence it is highly suitable for internet. Whenever we compile java source, it will create a class file. A class file contains byte code equivalent to our program. Each instruction size of a byte code is 1 byte. There are total of 220 byte code instructions available.

When we compile Java program, compiler will rewrite the program as another set of instructions. The rewritten code is said to be byte code.

JVM


JVM refers Java Virtual Machine. JVM is a program which will convert byte code instructions into machine language instructions understandable by Micro processor. Right Java program write once, later on run anywhere.

JVM is a system dependent, because it was developed in C language, where as class file is a system independent.

Question: What is the difference between class file and exe file
EXE file contains machine language instructions understandable by Micro processor, where as class file contains byte code instructions for JVM. EXE file is system dependent, where as class file is a system independent.

Sun Microsystems has developed different JVMs for different operating systems. Hence, you can write a single Java program and generate the class file which can be executed on any other operating system.

Read more...

Selection sort algorithm, flow chart, analysis and Java program

11 September 2009

Selection sort


Selection sort is a simple algorithm which will be applicable to sort the small lists or mostly sorted lists. Selection sort would sort by finding the minimum (in case of ascending) or maximum (in case of descending) value and swap that with the first element of the list.

Name selection is called because, it selects an intended element to be swapped with the first element.

Algorithm


START
DECLARE n, list, min
ACCEPT n
ACCEPT n values into an array list
FOR EACH i IN 0 to n-1
LOOP
min := i;
FOR EACH j IN i+1 to n-1
LOOP
IF list[j] < list[min] THEN
min := j;
END IF
END LOOP
IF i <> min THEN
temp := list[i];
list[i] := list[min];
list[min]:= temp;
END IF
END LOOP
END


Java program


import java.io.*;

/**
* This class demonstrates the bubble sort.
* @author SANTHOSH REDDY MANDADI
* @version 1.0
* @since 10 September 2009
*/
public class SelectionSort
{
public static void main(String[] args) throws Exception
{
int values[]=new int[5];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter "+values.length+" values to sort using bubble sort");
for(int i=0;i<values.length;i++)
{
try{
values[i]=Integer.parseInt(br.readLine());
}catch(NumberFormatException e)
{
e.printStackTrace();
values[i]=0;
}
}
selectionSort(values);
for(int i=0;i<values.length;i++)
{
System.out.print(values[i]+" ");
}
}

/**
* This method will sort the passed array
* @author SANTHOSH REDDY MANDADI
* @since 10-Sep-2009
* @param an array of the list of values to be sorted
*/
public static void selectionSort(int[] values)
{
//Iterating the list till the end of the list except last one
for (int i=0; i<values.length-1;i++)
{
//Considering the minumum value is current iteration array element
int min = i;
//Trying to find out the smallest element in the array
for(int j=i+1; j<values.length;j++)
{
if (values[j]<values[min])
{
min = j;
}
}
//If smallest element found other than the current iteration array element, swapping will happen
if (i != min)
{
int swap = values[i];
values[i] = values[min];
values[min] = swap;
}
}
}
}


Explaination


Let us consider we've executed the above program by inputting the values (53, 24, 31, 64, 3). Here is how the list will be modified in each iteration.

Iteration - list values
First - 3 24 31 64 53
Second - 3 24 31 64 53
Third - 3 24 31 64 53
Fourth - 3 24 31 53 64
Fifth - 3 24 31 53 64

Above program has been tested in JDK 1.4, 1.5, and 1.6.

Click here to check out other programs that I've developed.

Read more...

Java and Javascript JCrop (JQuery plugin) image cropper

04 September 2009

Recently I've implemented a cropper functionality based on the Java by using Java script API JCrop, an official plugin of JQuery. Here is how the cropper functionality works.

Lots of websites gives you about the crop functionality through PHP. JQuery official website also provides a demo in PHP. Here is how you can implement through Java programming language.

1. Download the JCrop, an open source plugin of JQuery.
2. Embed the JS and CSS for JCrop in JSP.
3. Insert an image on your JSP (web page) with an unique ID
4. Invoke the JCrop function on the unique ID of the image with all the required parameters i.e.; user can choose the dimensions so that JCrop utility will set the values to the hidden fields. Based on these values, you've to crop the image in Java.
5. Write a servlet / struts action class to crop the image based on the parameters

The HTML output for you JSP should look like below



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="/cmint/js/jquerymin.js"></script>
<script type="text/javascript" src="/cmint/js/jcrop.js"></script>
<link rel="stylesheet" href="/cmint/css/myhc/jcrop.css" type="text/css" />
<title>Crop and save</title>
</head>
<body>
<img src="http://203.197.128.203/commimg/myhotcourses/test/HC2.jpg" id="cropbox"/>
<script type="text/javascript">
$(window).load(function(){
var jcrop_api;
initJcrop();
function initJcrop()//{{{
{
jcrop_api = $.Jcrop('#cropbox',{ onChange: setCoords, onSelect: setCoords });
jcrop_api.setSelect([100,100,300,300]);
jcrop_api.setOptions({ allowSelect: true, allowMove: true, allowResize: true, aspectRatio: 1 });
}
});
function setCoords(c)
{
jQuery('#x1').val(c.x);
jQuery('#y1').val(c.y);
jQuery('#x2').val(c.x2);
jQuery('#y2').val(c.y2);
jQuery('#w').val(c.w);
jQuery('#h').val(c.h);
};
</script>
<form action="/cmint/cropper">
<input type="hidden" name="x1" id="x1"/>
<input type="hidden" name="y1" id="y1"/>
<input type="hidden" name="x2" id="x2"/>
<input type="hidden" name="y2" id="y2"/>
<input type="hidden" name="w" id="w"/>
<input type="hidden" name="h" id="h"/>
<input type="submit" value="Crop" name="action" />
</form>
</body>
</html>


Java program to crop the image


1. Get the buffered image reference by reading the file, which was shown to user to crop
2. Invoke the getSubImage method with the buffered image reference created in step 1 by passing the values user selected using cropper tool. getSubImage will return the buffered reader reference with the resultant image in the buffer.
3. Store the image with the cropped buffered image


package cropper.view;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;

/**
* A servlet which crops the image based on the JCrop tools parameters
* @author SANTHOSH REDDY MANDADI
* @version 1.0
* @since 04th September 2009
*/
public class ImageCropperSrv extends HttpServlet
{
public void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
//Get all the parameters which were populated by JCrop
int x1=Integer.parseInt(request.getParameter("x1"));
int y1=Integer.parseInt(request.getParameter("y1"));
int x2=Integer.parseInt(request.getParameter("x2"));
int y2=Integer.parseInt(request.getParameter("y2"));
int w=Integer.parseInt(request.getParameter("w"));
int h=Integer.parseInt(request.getParameter("h"));
System.out.println(x1+" "+y1+" "+x2+" "+y2+" "+w+" "+" "+h);

//Get the file name from the server
String file=request.getParameter("file");

//String serverPath="E:/Santhosh/Applications/ImageCropper/servlets app/public_html/nature/";
String serverPath="/commimg/myhotcourses/test/";
String sourceFile=serverPath+"HC"+file+".jpg";

//Get the buffered image reference
BufferedImage image=ImageIO.read(new File(sourceFile));

//Get the sub image
BufferedImage out=image.getSubimage(x1,y1,w,h);

//Store the image to a new file
ImageIO.write(out,"jpg",new File(serverPath+"HC"+file+"t.jpg"));

//Sending the output to the client by showing the cropped image with dimensions
PrintWriter printer=response.getWriter();
response.setContentType("text/html");
printer.println("Photo cropped from "+x1+","+y1+" to the width of "+w+" and height of "+h);
printer.println("<img src=\""+serverPath+"HC"+file+"t.jpg"+"\" />");
}
}


The above program has been tested under 1.4, 1.5, 1.6 and under Oracle App server, Apache Tomcat.

Click here to check out other programs that I've developed.

Read more...

Bubble sort algorithm, flow chart, analysis and Java program

Bubble sort


Bubble sort is a simple and common sorting algorithm. It sorts by iterating through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. This process will be continued until all the elements are being sorted i.e.; no swapping is required in the list.

Bubble sort name came for this algorithm due to - like a bubble comes to the top of the water, each iteration will push one smaller element to the top of the list (if the algorithm is for ascending order).

Performance


Bubble sort is not the efficient algorithm in terms of the performance because its worst-case and average complexity both О(n2), where n is the number of items being sorted.

Algorithm



START
DECLARE n, list
ACCEPT n
ACCEPT n values into an array list
DO
swapped := false;
FOR EACH i IN 0 to n-1
LOOP
IF list[i] > list[i+1] THEN
temp := list[i]
list[i]:=list[i+1]
list[i+1]:=temp
END IF
END LOOP
WHILE swapped = true
END


Java program



import java.io.*;

/**
* This class demonstrates the bubble sort.
* @author SANTHOSH REDDY MANDADI
* @version 1.0
* @since 04th September 2009
*/
public class BubbleSort
{
public static void main(String[] args) throws Exception
{
int values[]=new int[5];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter "+values.length+" values to sort using bubble sort");
for(int i=0;i<values.length;i++)
{
try{
values[i]=Integer.parseInt(br.readLine());
}catch(NumberFormatException e)
{
e.printStackTrace();
values[i]=0;
}
}
bubbleSort(values);
for(int i=0;i<values.length;i++)
{
System.out.print(values[i]+" ");
}
}

/**
* This method will sort the passed array
* @author SANTHOSH REDDY MANDADI
* @since 4-Sep-2009
* @param an array of the list of values to be sorted
*/
public static void bubbleSort(int[] values)
{
boolean swapped=false;
do
{
//When initializing the each loop assing false to swapped flag
swapped = false;
//Looping through the list
for(int i=0; i<values.length-1; i++)
{
//Comparing the adjecent elements
if(values[i]>values[i+1])
{
//Swapping
int temp=values[i];
values[i]=values[i+1];
values[i+1]=temp;
//Swapped is true
swapped=true;
}
}
}while (swapped);
}
}


Explanation:


Let us consider we've executed the above program by inputting the values (43, 25, 21, 56, 4). Here is how the list will be modified in each iteration.
swapped value = false

First iteration:


43 25 21 56 4 » 25 43 21 56 4 - swapped since 43 > 25
25 43 21 56 4 » 25 21 43 56 4 - swapped since 43 > 21
25 21 43 56 4 » 25 21 43 56 4 - not swapped since 43 < 56
25 21 43 56 4 » 25 21 43 4 56 - swapped since 54 > 4

Second iteration:


25 21 43 4 56 » 21 25 43 4 56
21 25 43 4 56 » 21 25 43 4 56
21 25 43 4 56 » 21 25 4 43 56
21 25 4 43 56 » 21 25 4 43 56

Third iteration:


21 25 4 43 56 » 21 25 4 43 56
21 25 4 43 56 » 21 4 25 43 56
21 4 25 43 56 » 21 4 25 43 56
21 4 25 43 56 » 21 4 25 43 56

Fourth iteration:


21 4 25 43 56 » 4 21 25 43 56
4 21 25 43 56 » 4 21 25 43 56
4 21 25 43 56 » 4 21 25 43 56
4 21 25 43 56 » 4 21 25 43 56

Fifth iteration:


4 21 25 43 56 » 4 21 25 43 56
4 21 25 43 56 » 4 21 25 43 56
4 21 25 43 56 » 4 21 25 43 56
4 21 25 43 56 » 4 21 25 43 56

Since there're no swaps happened in the fifth operation, the outer loop will be stopped since the condition swapped = true false.

Above program has been tested in JDK 1.4, 1.5, and 1.6.

Click here to check out other programs that I've developed.

Read more...

Sun Certified Java Professional (SCJP) 1.5 Question Bank - 10

25 August 2009

If you haven't read the previous article, click here to read.

Question: 46
Given:
1. public class Base {
2. public static final String FOO = "foo";
3. public static void main(String[] args) {
4. Base b = new Base();
5. Sub s = new Sub();
6. System.out.print(Base.FOO);
7. System.out.print(Sub.FOO);
8. System.out.print(b.FOO);
9. System.out.print(s.FOO);
10. System.out.print(((Base)s).FOO);
11. } }
12. class Sub extends Base {public static final String FOO="bar";}
What is the result?
A. foofoofoofoofoo
B. foobarfoobarbar
C. foobarfoofoofoo
D. foobarfoobarfoo
E. barbarbarbarbar
F. foofoofoobarbar
G. foofoofoobarfoo

Answer: D




Question: 47
Which two statements are true? (Choose two.)
A. An encapsulated, public class promotes re-use.
B. Classes that share the same interface are always tightly encapsulated.
C. An encapsulated class allows subclasses to overload methods, but does NOT allow overriding methods.
D. An encapsulated class allows a programmer to change an implementation without affecting outside code.

Answer: A, D



Question: 48
Given classes defined in two different files:
1. package util;
2. public class BitUtils {
3. public static void process(byte[]) { /* more code here */ }
4. }
1. package app;
2. public class SomeApp {
3. public static void main(String[] args) {
4. byte[] bytes = new byte[256];
5. // insert code here
6. }
7. }
What is required at line 5 in class SomeApp to use the process method of BitUtils?
A. process(bytes);
B. BitUtils.process(bytes);
C. util.BitUtils.process(bytes);
D. SomeApp cannot use methods in BitUtils.
E. import util.BitUtils.*; process(bytes);

Answer: C



Question: 49
Given:
13. public class Pass {
14. public static void main(String [] args) {
15. int x = 5;
16. Pass p = new Pass();
17. p.doStuff(x);
18. System.out.print(" main x = " + x);
19. }
20.
21. void doStuff(int x) {
22. System.out.print(" doStuff x = " + x++);
23. }
24. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuff x = 6 main x = 6
D. doStuff x = 5 main x = 5
E. doStuff x = 5 main x = 6
F. doStuff x = 6 main x = 5

Answer: D



Question: 50
Given:
11. public static void test(String str) {
12. if (str == null | str.length() == 0) {
13. System.out.println("String is empty");
14. } else {
15. System.out.println("String is not empty");
16. }
17. }
And the invocation:
31. test(null);
What is the result?
A. An exception is thrown at runtime.
B. "String is empty" is printed to output.
C. Compilation fails because of an error in line 12.
D. "String is not empty" is printed to output.

Answer: A



If you would like to read all the SCJP Question bank articles, please click here

Read more...

Javascript - get HTML drop down label

23 August 2009

Normally when you're using drop downs, you can get the selected value through Javascript. Did you need of the selected drop down label previously? Here I'm going to give you a small function with which you can get it.


<SCRIPT type="text/javascript">
//Function to get the drop down label for the given index
function getDropDownLabel(element)
{
if($(element))
{
var obj=$(element);
return obj[obj.selectedIndex].firstChild.nodeValue;
}
}
function $(element)
{
return document.getElementById(element);
}
</SCRIPT>


You can give a try with below example...





This program has been tested on all the major browsers like IE >= 6.0, Mozilla >= 2.0 and Google chrome...

Read more...

About This Blog

A place where you can find the updates on the technologies Java, Web, HTML, Servlets, JSPs, Struts, Springs, and Hibernate.