Wednesday, 15 September 2010

Hello world in java

Java source code

A Java program is a collection of one or more java classes. A Java source file can contain more than one class definition and has a .java extension. Each class definition in a source file is compiled into a separate class file. The name of this compiled file is comprised of the name of the class with .class as an extension.


public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}//End of main
}//End of HelloWorld Class
 
I created a class named “HelloWorld” containing a simple main function within it. The keyword class specifies that we are defining a class. The name of a public class is spelled exactly as the name of the file (Case Sensitive). All java programs begin execution with the method named main(). main method that gets executed has the following signature : public static void main(String args[]).Declaring this method as public means that it is accessible from outside the class so that the JVM can find it when it looks for the program to start it. It is necessary that the method is declared with return type void (i.e. no arguments are returned from the method). The main method contains a String argument array that can contain the command line arguments. The brackets { and } mark the beginning and ending of the class. The program contains a line ‘System.out.println(”Hello World”);’ that tells the computer to print out on one line of text namely ‘Hello World’. The semi-colon ‘;’ ends the line of code. The double slashes ‘//’ are used for comments that can be used to describe what a source code is doing. Everything to the right of the slashes on the same line does not get compiled, as they are simply the comments in a program.
Java Main method Declarations
class MainExample1 {public static void main(String[] args) {}}
class MainExample2 {public static void main(String []args) {}}
class MainExample3 {public static void main(String args[]) {}}
 

Overview of java

Java is a simple and yet powerful object oriented programming language and it is in many respects similar to C++. Java originated at Sun Microsystems, Inc. in 1991. It was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. It was developed to provide a platform-independent programming language.

Platform independent

Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.

Java Virtual Machine

What is the Java Virtual Machine? What  is its role?
Java was designed with a concept of ‘write once and run everywhere’ i.e. WORE. Java Virtual Machine plays the central role in this concept. The JVM is the environment in which Java programs execute. It is a software that is implemented on top of real hardware and operating system. When the source code (.java files) is compiled, it is translated into byte codes and then placed into (.class) files. The JVM executes these bytecodes. So Java byte codes can be thought of as the machine language of the JVM. A JVM can either interpret the bytecode one instruction at a time or the bytecode can be compiled further for the real microprocessor using what is called a just-in-time compiler The JVM must be implemented on a particular platform before compiled programs can run on that platform.

Object Oriented Programming

Since Java is an object oriented programming language it has following features:
  • Reusability of Code
  • Emphasis on data rather than procedure
  • Data is hidden and cannot be accessed by external functions
  • Objects can communicate with each other through functions
  • New data and functions can be easily addedJava has powerful features. The following are some of them:-

    Simple
    Reusable
    Portable (Platform Independent)
    Distributed
    Robust
    Secure
    High Performance
    Dynamic
    Threaded
    Interpreted
Object Oriented Programming is a method of implementation in which programs are organized as cooperative collection of objects, each of which represents an instance of a class, and whose classes are all members of a hierarchy of classes united via inheritance relationships.
OOP Concepts
Four principles of Object Oriented Programming are
Abstraction
Encapsulation
Inheritance
Polymorphism
Abstraction
Abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.
Encapsulation

Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior ; encapsulation serves to separate the contractual interface of an abstraction and its implementation.
Encapsulation
* Hides the implementation details of a class.
* Forces the user to use an interface to access data
* Makes the code more maintainable.
Inheritance
Inheritance is the process by which one object acquires the properties of another object.
Polymorphism
Polymorphism is the existence of the classes or methods in different forms or single name denoting different
implementations.

Java is Distributed

With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and access the objects across net via URLs.


Java is Multithreaded

One of the powerful aspects of the Java language is that it allows multiple threads of execution to run concurrently within the same program A single Java program can have many different threads executing independently and continuously. Multiple Java applets can run on the browser at the same time sharing the CPU time.

Java is Secure

Java was designed to allow secure execution of code across network. To make Java secure many of the features of C and C++ were eliminated. Java does not use Pointers. Java programs cannot access arbitrary addresses in memory.

Garbage collection

Automatic garbage collection is another great feature of Java with which it prevents inadvertent corruption of memory. Similar to C++, Java has a new operator to allocate memory on the heap for a new object. But it does not use delete operator to free the memory as it is done in C++ to free the memory if the object is no longer needed. It is done automatically with garbage collector.

Java Applications

Java has evolved from a simple language providing interactive dynamic content for web pages to a predominant enterprise-enabled programming language suitable for developing significant and critical applications. Today, It is used for many types of applications including Web based applications, Financial applications, Gaming applications, embedded systems, Distributed enterprise applications, mobile applications, Image processors, desktop applications and many more. This site outlines the building blocks of java by stating few java examples along with some java tutorials.

Wednesday, 1 September 2010

Deterministic lifetime of object in c++ as compared to java

C++ approach of Object Destruction

Some object-oriented programming languages, notably C++, have explicit destructor methods for any cleanup code that may be needed when an object is no longer used. The most common activity in a destructor is reclaiming the memory set aside for objects. Because Java does automatic garbage collection, manual memory reclamation is not needed and so Java does not support destructors.
Of course, some objects utilize a resource other than memory, such as a file or a handle to another object that uses system resources. In this case, it is important that the resource be reclaimed and recycled when it is no longer needed.
So cpp follows deterministic approach of object destruction.

Java Approach of object destruction

Java's approach is automatic garbage collection. You can add a finalize method to any class. The finalize method will be called before the garbage collector sweeps away the object. In practice, do not rely on the finalize method for recycling any resources that are in short supply—you simply cannot know when this method will be called. So java follows non-deterministic approach.

Advantage of Garbage collection

See here for advantage of garbage collection.

Disadvantage of Garbage collection

See here for disadvantage of Garbage collection

 

Final note

Garbage collection has increased problem, rather than solving many. Due to limited memory, we can get out of memory error. But this problem or disadvantage, we have to live with java.

Monday, 2 August 2010

Removing duplicates

package duplicates;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class Nodups {
/**
* @Michael Gagala
* ver 1.0
* This program will read in a strings from an input file, and
* printed the strings in a sorted order with duplicates removed
* 15 Aug 2009
*/
public static void main(String[] args) {
String file = “”;
boolean done = false;
int count = 0;
int tsCount = 0;
ArrayList wds = new ArrayList ();
TreeSet ts = new TreeSet(wds);

do{
try{
file = JOptionPane.showInputDialog(“Enter the name of the file.”);
FileReader dataFile = new FileReader(file);
Scanner sc = new Scanner(dataFile);
while(sc.hasNext()){
String aLine = sc.next();
wds.add(aLine);
count++;
}
ts.addAll(wds);
tsCount = ts.size();
Iterator it = ts.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println(“\nThere were ” + count + ” words in the orginal file.”);
System.out.println(“\nThere were ” + tsCount + ” words in the sorted file.”);
done = true;
}//close try
catch (FileNotFoundException e){
System.out.println(“File not found, please re-enter.”);
}//close catch
}//close do
while(!done);
}//close main
}//close class

Prims.java

import java.io.*;
import java.util.*;
/**
* @Michael Gagala
* Implement Prim’s Algorithm
* 9 November2009
* ver 1.0
**/
class Graph {
int gph[][];
int vtx;
int edg;
void createGraph(String file) throws FileNotFoundException {
int vtx1;
int vtx2;
int wt;
try{
FileReader dataFile = new FileReader(file);
Scanner sc = new Scanner(dataFile);
vtx = sc.nextInt();
edg = sc.nextInt();
gph = new int[vtx + 1][vtx + 1];
for (int i = 1; i <= vtx; i++)
for (int j = 1; j <= vtx; j++)
gph[i][j] = 0;
for (int i = 1; i <= edg; i++) {
vtx1 = sc.nextInt();
vtx2 = sc.nextInt();
wt = sc.nextInt();
gph[vtx1][vtx2] = gph[vtx2][vtx1] = wt;
}
}
catch (FileNotFoundException e){
System.out.println(“Please check classpath, and re-enter.”);
}
}// close createGraph
void prim() {
int curpth[], pth[], visited[];
int current;
curpth = new int[vtx + 1];
pth = new int[vtx + 1];
visited = new int[vtx + 1];
for (int i = 1; i <= vtx; i++) {
curpth[i] = 255;
pth[i] = visited[i] = 0;
}
current = 1;
curpth[current] = 0;
visited[current] = 1;
int j = 1;
while (j != vtx) {
for (int i = 1; i <= vtx; i++) {
if (gph[current][i] != 0 && visited[i] != 1)
if (gph[current][i] < curpth[i]) {
curpth[i] = gph[current][i];
pth[i] = current;
}
}
int min = 255;
for (int i = 1; i <= vtx; i++) {
if (visited[i] != 1)
if (curpth[i] < min) {
min = curpth[i];
current = i;
}
}
visited[current] = 1;
j = j + 1;
}
int mincost = 0;
for (int i = 1; i <= vtx; i++)
mincost = mincost + curpth[i];
System.out.println(“\n The minimum cost: ” + mincost);
}// close prim
}// close Graph
public class prims {
public static void main(String[] args) throws FileNotFoundException {
try{
String file = args[0];
Graph g = new Graph();
g.createGraph(file);
g.prim();
}
catch (FileNotFoundException e){
System.out.println(“Please check classpath, and re-enter.”);
}
}// close main
}// close prims

Gambler.java

/*************************************************************************
* Compilation: javac Gambler.java
* Execution: java Gambler stake goal N
*
* Simulates a gambler who start with $stake and place fair $1 bets
* until she goes broke or reach $goal. Keeps track of the number of
* times she wins and the number of bets she makes. Run the experiment N
* times, averages the results, and prints them out.
*
* % java Gambler 50 250 1000
* Percent of games won = 19.0
* Avg # bets = 9676.302
*
* % java Gambler 50 150 1000
* Percent of games won = 31.9
* Avg # bets = 4912.13
*
* % java Gambler 50 100 1000
* Percent of games won = 49.6
* Avg # bets = 2652.352
*
*************************************************************************/

public class Gambler {

public static void main(String[] args) {
int stake = Integer.parseInt(args[0]); // gambler's stating bankroll
int goal = Integer.parseInt(args[1]); // gambler's desired bankroll
int T = Integer.parseInt(args[2]); // number of trials to perform

int bets = 0; // total number of bets made
int wins = 0; // total number of games won

// repeat N times
for (int t = 0; t < T; t++) {

// do one gambler's ruin simulation
int cash = stake;
while (cash > 0 && cash < goal) {
bets++;
if (Math.random() < 0.5) cash++; // win $1
else cash--; // lose $1
}
if (cash == goal) wins++; // did gambler go achieve desired goal?
}

// print results
System.out.println(wins + " wins of " + T);
System.out.println("Percent of games won = " + 100.0 * wins / T);
System.out.println("Avg # bets = " + 1.0 * bets / T);
}

}

PowersOfTwo.java

/*************************************************************************
* Compilation: javac PowersOfTwo.java
* Execution: java PowersOfTwo N
*
* This program takes a command-line argument N and prnts a table of
* the powers of 2 that are less than or equal to 2^N.
*
* % java PowersOfTwo 5
* 0 1
* 1 2
* 2 4
* 3 8
* 4 16
* 5 32
*
* % java PowersOfTwo 6
* 0 1
* 1 2
* 2 4
* 3 8
* 4 16
* 5 32
* 6 64
*
* Remarks
* ------------
* Only works if 0 <= N < 31 since 2^31 overflows an int.
*
*************************************************************************/

public class PowersOfTwo {
public static void main(String[] args) {

// read in one command-line argument
int N = Integer.parseInt(args[0]);

int i = 0; // count from 0 to N-1
int powerOfTwo = 1; // the ith power of two

// repeat until i equals N
while (i <= N) {
System.out.println(i + " " + powerOfTwo); // print out the power of two
powerOfTwo = 2 * powerOfTwo; // double to get the next one
i = i + 1;
}

}
}