Friday, August 28, 2009

Java : Simple program using Math class

Math class is present in java.lang package so no need to import, its there by default.
Math class provides all trigonometric functions like sin(), cos(), tan() etc. Also other functions like abs() for calculating absolute values, sqrt() for getting square root, pow(x,y) for calculating power of values etc and many other features. you can solve complex number problems. Also PI value by using Math.PI

lets see a simple example.



/* TestMathClass.java */


public class TestMathClass
{
public static void main(String[] args)
{
int angles[] = { 0, 30, 45, 60, 90, 180 };

System.out.println("----Trigonometric Values----");

for (int i=0;i< angles.length ;i++ )
{
double rad = Math.toRadians(angles[i]);

System.out.println("----Angle: " + angles[i]);
System.out.println("Sin: " + Math.sin(rad));
System.out.println("Cos: " + Math.cos(rad));
System.out.println("Tan: " + Math.tan(rad));
}

System.out.println("----Absolute Values----");

int i = 8;
int j = -5;
System.out.println("Absolute value of " + i + " is :" + Math.abs(i));
System.out.println("Absolute value of " + j + " is :" + Math.abs(j));

float f1 = 1.40f;
float f2 = -5.28f;
System.out.println("Absolute value of " + f1 + " is :" + Math.abs(f1));
System.out.println("Absolute value of " + f2 + " is :" + Math.abs(f2));

double d1 = 3.324;
double d2 = -9.324;
System.out.println("Absolute value of " + d1 + " is :" + Math.abs(d1));
System.out.println("Absolute value of " + d2 + " is :" + Math.abs(d2));

long l1 = 3L;
long l2 = -4L;
System.out.println("Absolute value of " + l1 + " is :" + Math.abs(l1));
System.out.println("Absolute value of " + l2 + " is :" + Math.abs(l2));


System.out.println("----Other Values----");

double x = 11.635;
double y = 2.76;

System.out.println("The value of e is " + Math.E);
System.out.println("exp(" + x + ") is " + Math.exp(x));
System.out.println("log(" + x + ") is " + Math.log(x));
System.out.println("pow(" + x + ", " + y + ") is " + Math.pow(x, y));
System.out.println("sqrt(" + x + ") is " + Math.sqrt(x));



System.out.println("The value of PI is : "+Math.PI);
}
}



/********OUTPUT*********/


----Trigonometric Values----
----Angle: 0
Sin: 0.0
Cos: 1.0
Tan: 0.0
----Angle: 30
Sin: 0.49999999999999994
Cos: 0.8660254037844387
Tan: 0.5773502691896257
----Angle: 45
Sin: 0.7071067811865475
Cos: 0.7071067811865476
Tan: 0.9999999999999999
----Angle: 60
Sin: 0.8660254037844386
Cos: 0.5000000000000001
Tan: 1.7320508075688767
----Angle: 90
Sin: 1.0
Cos: 6.123233995736766E-17
Tan: 1.633123935319537E16
----Angle: 180
Sin: 1.2246467991473532E-16
Cos: -1.0
Tan: -1.2246467991473532E-16
----Absolute Values----
Absolute value of 8 is :8
Absolute value of -5 is :5
Absolute value of 1.4 is :1.4
Absolute value of -5.28 is :5.28
Absolute value of 3.324 is :3.324
Absolute value of -9.324 is :9.324
Absolute value of 3 is :3
Absolute value of -4 is :4
----Other Values----
The value of e is 2.718281828459045
exp(11.635) is 112983.8311174165
log(11.635) is 2.454017796754255
pow(11.635, 2.76) is 874.0076417529531
sqrt(11.635) is 3.411011580162108
The value of PI is : 3.141592653589793

Friday, August 21, 2009

Java : Simple Thread Example

How to start new thread from main thread. Any program starts execution from main thread how ever you can start n numbers of threads from this main thread. Lets see a simple Thread example, just compile and run main program and see output.

/* MainClass.java */

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

System.out.println("Main Thread Started");

AnotherClass ac = new AnotherClass();
//Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
ac.start();

for(int i=0;i<=10 ;i++ )
{
System.out.println("Main "+i);

try
{
//Get current Thread
Thread.currentThread().sleep(300);
}
catch (InterruptedException ex)
{
//sleep() method throws this checked exception
System.out.println("Exception in MainClass thread : "+ex);
}

}
System.out.println("Ending Main Thread");
}
}


/* AnotherClass.java */


//Inheriting from thread class
public class AnotherClass extends Thread
{
//Overrideing rum method from thread class
public void run()
{
System.out.println("Another Thread Started");

for (int j=0;j<=10 ;j++ )
{
System.out.println("Another "+j);

try
{
//sleep() method can be used here directly becz it is publicly inherited from Thread class
sleep(100);
}
catch (InterruptedException ex)
{
//Handling InterruptedException rather to declare becz overriding function cannot throw any new checked exception
System.out.println("Exception in AnotherClass thread : "+ex);
}
}
System.out.println("Ending Another Thread");
}
}



/**********OUTPUT***************/

Main Thread Started
Main 0
Another Thread Started
Another 0
Another 1
Another 2
Main 1
Another 3
Another 4
Another 5
Main 2
Another 6
Another 7
Another 8
Main 3
Another 9
Another 10
Ending Another Thread
Main 4
Main 5
Main 6
Main 7
Main 8
Main 9
Main 10
Ending Main Thread

Java : Get System Input using Scanner class

Simple program to scan input from user using Scanner class. You can get Long, Shot, Byte, String, Int etc.


/* ScanInput.java */

import java.util.Scanner;

public class ScanInput
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);

System.out.println("Enter String : ");

String strVal = scan.nextLine();

System.out.println("You Entered : "+strVal);

System.out.println("Enter Int : ");

int intVal = scan.nextInt();

System.out.println("You Entered : "+intVal);

scan.close();

}
}


/******OUTPUT*********/


Enter String :
This is a string
You Entered : This is a string
Enter Int :
234
You Entered : 234

Java : Sorting and Randomly iterating Hashtable

As Hashtable is unordered and unsorted by default many time its required to sort it or randomly access its data. Same applicable with LinkedHashMap, TreeMap, HashMap.

In below example ArrayList is used to sort and shuffle Hashtable's key.


/* TestHash.java */

import java.util.*;

public class TestHash
{
public static void main(String[] args)
{
Hashtable<Integer,String> data = new Hashtable<Integer,String>();

//Temp ArrayList is used to store keys of Hashtable
ArrayList<Integer> temp = new ArrayList<Integer>();

data.put(1,"ABC");
data.put(0,"LMN");
data.put(5,"PQR");
data.put(3,"XYZ");

Integer key;

System.out.println("Default Unorderd and Unsorted");
//Iterating Hashtable
Enumeration<Integer> enu = data.keys();
while(enu.hasMoreElements())
{
key=enu.nextElement();
System.out.println(key+" "+data.get(key));

//Putting Hashtable keys in ArrayList
temp.add(key);
}

//Sorting keys of Hashtable
Collections.sort(temp);

//iterating ArrayList using for each loop
System.out.println("Sorted");
for (Integer val : temp)
{
System.out.println(val+" "+data.get(val));
}

//Shuffling keys of Hashtable
Collections.shuffle(temp);

//iterating ArrayList using for each loop
System.out.println("Randomly Iterating");
for (Integer val : temp)
{
System.out.println(val+" "+data.get(val));
}

}
}


/******OUTPUT*******/

Default Unorderd and Unsorted
5 PQR
3 XYZ
1 ABC
0 LMN
Sorted
0 LMN
1 ABC
3 XYZ
5 PQR
Randomly Iterating
3 XYZ
0 LMN
5 PQR
1 ABC

Java : Iterating ArrayList

Program to Iterate ArrayList, You can iterate ArrayList of String, Integer, Double, Long, Byte, Character etc.

1st Method simple standard way to iterate.
2nd Method using for each loop.


/* IterateArrayList.java */

import java.util.ArrayList;

public class IterateArrayList
{
public static void main(String[] args)
{
ArrayList<Integer> data = new ArrayList<Integer>();

for (int i=0;i<10 ;i++ )
{
//Java 5 supports Autoboxing (int added in Arraylist)
data.add(i);
}

System.out.println("Iterateing using 1st Method");

//Iterating ArrayList
for (int i=0;i<data.size() ;i++ )
{
System.out.println(data.get(i));
}


System.out.println("Iterateing using 2st Method");

//Iterating using for each loop
for(Integer val : data)
{
System.out.println(val);
}
}
}


/********OUTPUT********/
Iterateing using 1st Method
0
1
2
3
4
5
6
7
8
9
Iterateing using 2st Method
0
1
2
3
4
5
6
7
8
9

Friday, August 14, 2009

Java : Generate CSV File

This is simple program to generate CSV file. As we know csv is nothing but comma separated values, so we will write file with '.csv' extension.


/* GenerateCSVFile.java*/

import java.io.*;

public class GenerateCSVFile
{
public static void main(String[] args)
{
//name of the file, it takes default path ie. current directory
//you can also provide absolute/relative path
String CSVFileToWrite = "MyCSVFile.csv";//file with .csv extension

try
{
File file=new File(CSVFileToWrite);
FileWriter fw =new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);

for(int line = 0 ; line < 10 ; line ++)
{
bw.write("A"+line+",B"+line+",C"+line);//writing comma separated values
bw.newLine();
bw.flush();//flushing
}

bw.close();//closing BufferedWriter

System.out.println("File generated sucessfully : "+file.getAbsolutePath());

}
catch (IOException ex)
{
ex.printStackTrace();
}

}
}

Java : Generate Random Numbers between minimum and maximum range.

This is simple java program to generate random numbers between minimum and maximum (both inclusive) given range. For example in below code input minimum number is 200 and maximum number is 300.

/* RandomNumber.java*/

import java.util.Random;

public class RandomNumber
{
public static void main(String[] args)
{
int min = 200;
int max = 300;

Random ran = new Random();

for (int i=0;i<10 ;i++ )
{
System.out.println(ran.nextInt(max - min + 1) + min);
}
}
}



/*****OUTPUT*****/

272
251
214
245
246
228
240
212
294
285

Thursday, August 6, 2009

Java : Date and Time Formats and Calendar Class

Java Date and Time Formats



Customized Date and Time Formats
PatternOutput
dd MMMM yyyy EEEE06 August 2009 Thursday
dd.MM.yy06.08.09
yyyy.MM.dd G 'at' hh:mm:ss z2009.08.06 AD at 04:26:45 IST
EEE, MMM d, ''yyThu, Aug 6, '09
hh:mm:ss:SSS a04:40:52:110 PM
HH:mm z16:41 IST
dd/MM/yyyy EE06/08/2009 Thu
dd-MMM-yyyy hh:mm:ss a EEEE06-Aug-2009 04:36:22 PM Thursday


Simple Java program to get today's date,yesterday's date and tomorrow's date using Calendar class.

/* GetDate.java */

import java.util.Calendar;
import java.text.SimpleDateFormat;

public class GetDate
{
public static void main(String[] args)
{
//get yesterday's date
Calendar calYesterday = Calendar.getInstance();
calYesterday.add(Calendar.DAY_OF_MONTH, -1);
String yesterday=new SimpleDateFormat("dd/MM/yyyy").format(calYesterday.getTime());

//get today's date
Calendar calToday = Calendar.getInstance();
String today=new SimpleDateFormat("dd/MM/yyyy").format(calToday.getTime());

//get tomorrow's date
Calendar calTomorrow = Calendar.getInstance();
calTomorrow.add(Calendar.DAY_OF_MONTH, +1);
String tomorrow=new SimpleDateFormat("dd/MM/yyyy").format(calTomorrow.getTime());


System.out.println("Yesterday : "+yesterday);

System.out.println("Today : "+today);

System.out.println("Tomorrow : "+tomorrow);

}
}

/*******OUTPUT********/

Yesterday : 05/08/2009
Today : 06/08/2009
Tomorrow : 07/08/2009

You can also use Date class to get today's date

//String today = new SimpleDateFormat("dd/MM/yyyy").format(new java.util.Date());


Calendar Class




Lets look at a program for testing Calendar fields.

/* CalendarField.java */

import java.util.Calendar;

public class CalendarField
{
public static void main(String[] args)
{
//get today's date
Calendar calToday = Calendar.getInstance();

//Field indicating the day of the month.
System.out.println("DATE : "+calToday.get(Calendar.DATE));

//Field indicating the month.
System.out.println("MONTH : "+calToday.get(Calendar.MONTH ));

//Field indicating the day of the month.
System.out.println("DAY_OF_MONTH : "+calToday.get(Calendar.DAY_OF_MONTH ));

//Field indicating the day of the week.
System.out.println("DAY_OF_WEEK : "+calToday.get(Calendar.DAY_OF_WEEK ));

//Field indicating the ordinal number of the day of the week within the current month.
System.out.println("DAY_OF_WEEK_IN_MONTH : "+calToday.get(Calendar.DAY_OF_WEEK_IN_MONTH ));

//Field indicating the day number within the current year.
System.out.println("DAY_OF_YEAR : "+calToday.get(Calendar.DAY_OF_YEAR ));

//Field indicating the week number within the current month.
System.out.println("WEEK_OF_MONTH : "+calToday.get(Calendar.WEEK_OF_MONTH ));

//Field indicating the hour of the day.
System.out.println("HOUR_OF_DAY : "+calToday.get(Calendar.HOUR_OF_DAY ));

//Field indicating the hour of the morning or afternoon.
System.out.println("HOUR : "+calToday.get(Calendar.HOUR ));

//Field indicating the minute within the hour.
System.out.println("MINUTE : "+calToday.get(Calendar.MINUTE ));

//Field indicating the second within the minute.
System.out.println("SECOND : "+calToday.get(Calendar.SECOND));

//Field indicating the millisecond within the second.
System.out.println("MILLISECOND : "+calToday.get(Calendar.MILLISECOND ));

//Field indicating the year.
System.out.println("YEAR : "+calToday.get(Calendar.YEAR ));

//Field indicating the week number within the current year.
System.out.println("WEEK_OF_YEAR : "+calToday.get(Calendar.WEEK_OF_YEAR ));

//Field indicating the era, e.g., AD or BC in the Julian calendar.
System.out.println("ERA : "+calToday.get(Calendar.ERA ));
}
}


/*******OUTPUT********/

DATE : 6
MONTH : 7
DAY_OF_MONTH : 6
DAY_OF_WEEK : 5
DAY_OF_WEEK_IN_MONTH : 1
DAY_OF_YEAR : 218
WEEK_OF_MONTH : 2
HOUR_OF_DAY : 19
HOUR : 7
MINUTE : 40
SECOND : 47
MILLISECOND : 157
YEAR : 2009
WEEK_OF_YEAR : 32
ERA : 1

Tuesday, August 4, 2009

java.lang.NoSuchMethodError: com.caucho.server.connection.CauchoRequest.isInitial()Z

500 Servlet Exception


[show] java.lang.NoSuchMethodError: com.caucho.server.connection.CauchoRequest.isInitial()Z

java.lang.NoSuchMethodError: com.caucho.server.connection.CauchoRequest.isInitial()Z
   at com.caucho.server.connection.AbstractHttpResponse.finishInvocation(AbstractHttpResponse.java:2271)
   at com.caucho.server.connection.AbstractHttpResponse.finishInvocation(AbstractHttpResponse.java:2237)
   at com.caucho.server.connection.AbstractHttpResponse.sendError(AbstractHttpResponse.java:567)
   at com.caucho.server.connection.AbstractHttpResponse.sendError(AbstractHttpResponse.java:525)
   at com.caucho.server.connection.HttpServletResponseImpl.sendError(HttpServletResponseImpl.java:277)
   at com.caucho.servlets.FileServlet.service(FileServlet.java:274)
   at com.caucho.server.dispatch.ServletFilterChain.doFilter(ServletFilterChain.java:103)
   at com.caucho.server.webapp.WebAppFilterChain.doFilter(WebAppFilterChain.java:189)
   at com.caucho.server.dispatch.ServletInvocation.service(ServletInvocation.java:266)
   at com.caucho.server.http.HttpRequest.handleRequest(HttpRequest.java:292)
   at com.caucho.server.port.TcpConnection.handleRequests(TcpConnection.java:577)
   at com.caucho.server.port.TcpConnection$AcceptTask.doAccept(TcpConnection.java:1211)
   at com.caucho.server.port.TcpConnection$AcceptTask.run(TcpConnection.java:1152)
   at com.caucho.util.ThreadPool$Item.runTasks(ThreadPool.java:759)
   at com.caucho.util.ThreadPool$Item.run(ThreadPool.java:681)
   at java.lang.Thread.run(Thread.java:619)

Resin/3.2.1 Server: ''




Hi friends,
I am getting this error on my Resin 3.2.1 web server, i tried lot to solve this error but could not succeed. This error comes when i refresh my pages, many times images does not appears or css not supported.
I tried reinstalling JAVA also reinstalling Resin but could not succeed to solve this error. I searched on net to solve this exception but did not found any source.

Any one getting same exception??
What reason it could be??
How to solve this Exception??

Javascript : Simple Digital / Analog clock

Digital Clock



<HTML>
<HEAD>
<TITLE> Digital Clock </TITLE>
<script type="text/javascript">

function updateClock ( )
{
var currentTime = new Date ( );

var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
var currentSeconds = currentTime.getSeconds ( );

// Pad the minutes and seconds with leading zeros, if required
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

// Choose either "AM" or "PM" as appropriate
var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";

// Convert the hours component to 12-hour format if needed
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

// Convert an hours component of "0" to "12"
currentHours = ( currentHours == 0 ) ? 12 : currentHours;

// Compose the string for display
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;

// Update the time display
document.getElementById("clock").innerHTML = currentTimeString;
}
</script>

</HEAD>

<BODY onload="updateClock(); setInterval('updateClock()', 1000 )">
<div id="clock"> </div>
</BODY>
</HTML>


Analog Clock



<HTML>
<HEAD>
<TITLE> Analog Clock </TITLE>
<script type="text/javascript">

window.CoolClock = function(canvasId,displayRadius,skinId,showSecondHand,gmtOffset)
{
return this.init(canvasId,displayRadius,skinId,showSecondHand,gmtOffset);
}

CoolClock.findAndCreateClocks = function()
{
var canvases = document.getElementsByTagName("canvas");
for (var i=0;i<canvases.length;i++)
{
var fields = canvases[i].className.split(" ")[0].split(":");
if (fields[0] == "CoolClock")
{
new CoolClock(canvases[i].id,fields[2],fields[1],fields[3]!="noSeconds",fields[4]);
}
}
}

CoolClock.addLoadEvent = function(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
window.onload = func;
else
window.onload = function()
{
oldonload();
func();
}
}

CoolClock.config =
{
clockTracker: {},
tickDelay: 1000,
longTickDelay: 15000,
defaultRadius: 85,
renderRadius: 100,
defaultSkin: "swissRail",
skins:
{
swissRail:
{
outerBorder: { lineWidth: 1, radius:95, color: "black", alpha: 1 },
smallIndicator: { lineWidth: 2, startAt: 89, endAt: 93, color: "black", alpha: 1 },
largeIndicator: { lineWidth: 4, startAt: 80, endAt: 93, color: "black", alpha: 1 },
hourHand: { lineWidth: 8, startAt: -15, endAt: 50, color: "black", alpha: 1 },
minuteHand: { lineWidth: 7, startAt: -15, endAt: 75, color: "black", alpha: 1 },
secondHand: { lineWidth: 1, startAt: -20, endAt: 85, color: "red", alpha: 1 },
secondDecoration: { lineWidth: 1, startAt: 70, radius: 4, fillColor: "red", color: "red", alpha: 1 }
}
}
};

CoolClock.prototype =
{
init: function(canvasId,displayRadius,skinId,showSecondHand,gmtOffset) {
this.canvasId = canvasId;
this.displayRadius = displayRadius || CoolClock.config.defaultRadius;
this.skinId = skinId || CoolClock.config.defaultSkin;
this.showSecondHand = typeof showSecondHand == "boolean" ? showSecondHand : true;
this.tickDelay = CoolClock.config[ this.showSecondHand ? "tickDelay" : "longTickDelay"];

this.canvas = document.getElementById(canvasId);

this.canvas.setAttribute("width",this.displayRadius*2);
this.canvas.setAttribute("height",this.displayRadius*2);

this.canvas.style.width = this.displayRadius*2 + "px";
this.canvas.style.height = this.displayRadius*2 + "px";

this.renderRadius = CoolClock.config.renderRadius;

this.scale = this.displayRadius / this.renderRadius;
this.ctx = this.canvas.getContext("2d");
this.ctx.scale(this.scale,this.scale);

this.gmtOffset = gmtOffset != null ? parseFloat(gmtOffset) : gmtOffset;

CoolClock.config.clockTracker[canvasId] = this;
this.tick();
return this;
},
fullCircle: function(skin)
{
this.fullCircleAt(this.renderRadius,this.renderRadius,skin);
},
fullCircleAt: function(x,y,skin)
{
with (this.ctx)
{
save();
globalAlpha = skin.alpha;
lineWidth = skin.lineWidth;
if (!document.all)
beginPath();
if (document.all)
// excanvas doesn't scale line width so we will do it here
lineWidth = lineWidth * this.scale;
arc(x, y, skin.radius, 0, 2*Math.PI, false);
if (document.all)
// excanvas doesn't close the circle so let's color in the gap
arc(x, y, skin.radius, -0.1, 0.1, false);
if (skin.fillColor)
{
fillStyle = skin.fillColor
fill();
}
else
{
// XXX why not stroke and fill
strokeStyle = skin.color;
stroke();
}
restore();
}
},
radialLineAtAngle: function(angleFraction,skin)
{
with (this.ctx) {
save();
translate(this.renderRadius,this.renderRadius);
rotate(Math.PI * (2 * angleFraction - 0.5));
globalAlpha = skin.alpha;
strokeStyle = skin.color;
lineWidth = skin.lineWidth;
if (document.all)
// excanvas doesn't scale line width so we will do it here
lineWidth = lineWidth * this.scale;
if (skin.radius)
{
this.fullCircleAt(skin.startAt,0,skin)
}
else
{
beginPath();
moveTo(skin.startAt,0)
lineTo(skin.endAt,0);
stroke();
}
restore();
}
},
render: function(hour,min,sec)
{
var skin = CoolClock.config.skins[this.skinId];
this.ctx.clearRect(0,0,this.renderRadius*2,this.renderRadius*2);

this.fullCircle(skin.outerBorder);

for (var i=0;i<60;i++)
this.radialLineAtAngle(i/60,skin[ i%5 ? "smallIndicator" : "largeIndicator"]);

this.radialLineAtAngle((hour+min/60)/12,skin.hourHand);
this.radialLineAtAngle((min+sec/60)/60,skin.minuteHand);
if (this.showSecondHand)
{
this.radialLineAtAngle(sec/60,skin.secondHand);
if (!document.all)
// decoration doesn't render right in IE so lets turn it off
this.radialLineAtAngle(sec/60,skin.secondDecoration);
}
},
nextTick: function()
{
setTimeout("CoolClock.config.clockTracker['"+this.canvasId+"'].tick()",this.tickDelay);
},

stillHere: function()
{
return document.getElementById(this.canvasId) != null;
},
refreshDisplay: function()
{
var now = new Date();
if (this.gmtOffset != null)
{
// use GMT + gmtOffset
var offsetNow = new Date(now.valueOf() + (this.gmtOffset * 1000 * 60 * 60));
this.render(offsetNow.getUTCHours(),offsetNow.getUTCMinutes(),offsetNow.getUTCSeconds());
}
else
{
// use local time
this.render(now.getHours(),now.getMinutes(),now.getSeconds());
}
},
tick: function()
{
if (this.stillHere())
{
this.refreshDisplay()
this.nextTick();
}
}
}

CoolClock.addLoadEvent(CoolClock.findAndCreateClocks);


</script>
</HEAD>

<BODY>
<canvas id="c1" class="CoolClock"></canvas>
</BODY>
</HTML>