Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, July 11, 2009

Windows unix cut command - column cut mode

The second part of the Windows Unix Cut command implements the column cut mode of the Cut command. By specifying flags such as -c for column cut mode and -p for entire file cut mode, the program can be used to cut the file based on column and file respectively.

This functionality is available in Editplus which offers column select option, but the command line tool can be very useful while cutting enormous files. The latest code is given below:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Cut {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(args[1]);
out = new FileOutputStream("cutoutput.txt");
if(args[0].equals("-p")){
int c,count=0,llim=Integer.parseInt(args[2]),ulim=Integer.parseInt(args[3]);
while ((c = in.read()) != -1) {
if((char)c=='\n'){
count =count-1;}
count++;
if(count>=llim && count<=ulim){
//System.out.println((char)c);
out.write(c);}
}
System.out.println("Total characters between range is "+(ulim-llim));
}
else if(args[0].equals("-c")){
int c,count=0,llim=Integer.parseInt(args[2]),ulim=Integer.parseInt(args[3]);
while ((c = in.read()) != -1) {
if((char)c=='\n'){
count =1;out.write('\n');/*System.out.println();*/}
count++;
if(count>=llim && count<=ulim){
//System.out.print((char)c);
out.write(c);}
}
System.out.println("Output to be viewed in Wordpad or higer only" );
}

} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Tuesday, June 16, 2009

Program to cut text file from character position x to y

I was searching for a windows equivalent to the Unix "cut" command. However, none could be found. So this java program will eventually do all that the Unix "cut" command does and more.

The functionality i required was to cut a text file between two given positions.Although this seems simple enough, notepad, textpad etc. don't have this facility. Hope this initial version will help those of you who want to cut a text file between two points. The program does not consider newline characters, but tab, space etc.. are considered while counting.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Cut {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(args[0]);
out = new FileOutputStream("cutoutput.txt");
int c,count=0,llim=Integer.parseInt(args[1]),ulim=Integer.parseInt(args[2]);

while ((c = in.read()) != -1) {
if((char)c=='\n'){
count =count-1;}
count++;
if(count>=llim && count<=ulim){
//System.out.println((char)c);
out.write(c);}
}
System.out.println("Total characters between range is "+(ulim-llim));
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Wednesday, May 20, 2009

Windows Process Monitor in java

It is required to monitor the status of few critical processes and services on business critical systems. Similarly other resources such as memory used and CPU time also require to be monitored.

These simple set of functions make use of the windows tasklist.exe utility to perform following functions:

  • Alert when a particular process, service, module is started.
  • Alert when memory usage of any particular or any process exceeds a certain value.
  • Alert if any particular or any process is not responding.
  • Alert if CPU Time for a particular process exceeds a certain value.
  • Monitor if a particular number of instances of a service, process, and module is running. If it falls below or goes above the mentioned number of instances- generate alert.
The java functions to use are given below.

import java.io.*;

import java.util.*;


public class GetProcess {

public static void main(String[] args){

//few example uses of the functions.

System.out.println(CheckIfProgramXIsNotResponding(""));

System.out.println(CheckIfProgramXIsUsingMoreThanYKBOfMemory("java.exe",4200));

System.out.println(CheckIfProgramXIsUsingMoreThanZOfCPUTime("System", 0,0,1));

System.out.println(CheckIfNInstancesOfProgramXAreExecuting("svchost.exe",5));

System.out.println(CheckIfNInstancesOfServiceXAreRunning("MDM",1));

System.out.println(CheckIfNInstancesOfModuleXAreRunning("ntdll.dll",29));

}

/*These functions can be used along with a configuration file or a front end to perform monitoring of Windows systems.*/

private static boolean CheckIfProgramXIsNotResponding(String ProgName){

//returns true if given program is NOT RESPONDING. If no argument is passed, returns true if any program is not responding.

String argument="tasklist.exe /NH /FI ".concat("\"").concat("STATUS eq NOT RESPONDING").concat("\"");

return checkProcessInfo(argument, ProgName);

}


private static boolean CheckIfProgramXIsUsingMoreThanYKBOfMemory(String ProgName,int MemoryInKb){

//returns true if given program is using more than Y KB of Memory.If no argument is passed, returns true if any programs memory is more than Y KB.

String line,argument="tasklist.exe /NH /FI ".concat("\"").concat("MEMUSAGE gt ")+MemoryInKb;

argument=argument.concat("\"");

return checkProcessInfo(argument, ProgName);

}


private static boolean CheckIfProgramXIsUsingMoreThanZOfCPUTime(String ProgName,int Hours,int Minutes,int Seconds){

//returns true if given program is using more than Z CPUTime.If no argument is passed, returns true if any programs memory is using more than Z CPUTime.

String line,argument="tasklist.exe /NH /FI ".concat("\"").concat("CPUTIME gt ")+Hours+":"+Minutes+":"+Seconds;

argument=argument.concat("\"");

return checkProcessInfo(argument, ProgName);

}


private static boolean CheckIfNInstancesOfProgramXAreExecuting(String ProgName,int n){

//returns true if N instances of ProgramX are executing.

String line,argument="tasklist.exe /NH /FI ".concat("\"").concat("IMAGENAME eq ").concat(ProgName).concat("\"");

return checkProcessCount(argument,ProgName,n);

}


private static boolean CheckIfNInstancesOfServiceXAreRunning(String ProgName,int n){

//returns true if N instances of Service X are running.

String line,argument="tasklist.exe /NH /FI ".concat("\"").concat("SERVICES eq ").concat(ProgName).concat("\"");

return checkProcessCount(argument,"",n);

}


private static boolean CheckIfNInstancesOfModuleXAreRunning(String ProgName,int n){

//returns true if N instances of Module X are running.

String line,argument="tasklist.exe /NH /M ".concat(ProgName);

return checkProcessCount(argument,"",n);

}


private static boolean checkProcessInfo(String argument,String ProgName){

String line;

try {

System.out.println(argument);

Process p = Runtime.getRuntime().exec(argument);

BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

while ((line = input.readLine()) != null) {

if (!line.trim().equals("")) {

if(line.startsWith(ProgName)){

return true;}//return status

}

}

input.close();

}

catch (Exception err) {

err.printStackTrace();

}

return false;

}


private static boolean checkProcessCount(String argument,String ProgName,int n){

String line;

int count=0;

try {

System.out.println(argument);

Process p = Runtime.getRuntime().exec(argument);

BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

while ((line = input.readLine()) != null) {

if (!line.trim().equals("")) {

if(line.startsWith(ProgName)){

count++;}

}

}

input.close();

}

catch (Exception err) {

err.printStackTrace();

}

System.out.println(count);

if(n==count){

return true;}//return status

return false;

}

}

Tuesday, May 12, 2009

Sequential Screen Capture Utility

This is a simple java program that allows you take sequential screen prints with very less efforts.



import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;



public class ScreenCapture {


public static void main(String[] argv) throws Exception{

int i,time;
String option="S";
if(argv.length > 0) {
try {
time = Integer.parseInt(argv[0]);
for(i=0;i< time;i++){
captureandstorescreenshot();}}catch(NumberFormatException nfe) {
if (argv[0].equalsIgnoreCase("-help"))
{System.out.println("ScreenCapture Utility \n\n Usage:Run the program to capture screenshots for the next x seconds using the command [javac ScreenCapture x].\n Ex:javac ScreenCapture 20\n");
}
else if (argv[0].equalsIgnoreCase("-SE"))
{
while(!option.equalsIgnoreCase("X")){
InfiniteLoop t = new InfiniteLoop();
if(option.equalsIgnoreCase("S")){
t.start();}
Console console = System.console();
option= console.readLine("Enter E to end,S to start and X to exit?");
if(option.equalsIgnoreCase("E")){
Thread.sleep(1);
t.interrupt();}
}
}
else{
System.err.println(argv[0]+" is not a valid number of seconds.'javac ScreenCapture -help' for syntax.");
System.exit(-1);}}}
}
public static void CaptureAndStoreScreenShot(){
try{
Calendar rightNow = Calendar.getInstance();
Dimension scrensize = Toolkit.getDefaultToolkit().getScreenSize();
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(scrensize));
//difference (measured in milliseconds) between the current time and midnight, January 1, 1970 UTC
String filename ="screen"+System.currentTimeMillis()+".jpg";
ImageIO.write(img, "JPG", new File(filename));
}catch(Exception e){return;}
}
}

class InfiniteLoop extends Thread
{
public void run(){
for( ; ;){
ScreenCapture.CaptureAndStoreScreenShot();
if (Thread.interrupted()) {
// System.out.println("Interrupted");
return;
}
}
}
}
The below error occurs in older versions(Pre java 2) while interrupting the thread. It seems like a bug in older versions of java.

AWT blocker activation interrupted:
java.lang.InterruptedException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:429)
at sun.awt.AWTAutoShutdown.activateBlockerThread(AWTAutoShutdown.java:30
9)
at sun.awt.AWTAutoShutdown.setToolkitBusy(AWTAutoShutdown.java:226)
at sun.awt.AWTAutoShutdown.notifyToolkitThreadBusy(AWTAutoShutdown.java:
118)
at sun.awt.windows.WToolkit.(WToolkit.java:217)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
orAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
onstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
at java.lang.Class.newInstance0(Class.java:308)
at java.lang.Class.newInstance(Class.java:261)
at java.awt.Toolkit$2.run(Toolkit.java:760)
at java.security.AccessController.doPrivileged(Native Method)
at java.awt.Toolkit.getDefaultToolkit(Toolkit.java:739)
at ScreenCapture.CaptureAndStoreScreenShot(ScreenCapture.java:44)
at InfiniteLoop.run(ScreenCapture.java:58)

Friday, April 24, 2009

Java Desktop Fortune teller

This is a simple java desktop application that "predicts" your fortune. It makes use of a getfortune method to display predefined fortune texts in a label. The getFortune method uses the random function from the "import java.lang.Math.*" package to choose the fortune to display.

fortune teller
public String getFortune() {
String prediction[]={"You will die a horrible death at 3:00 PM","You will win a lottery today","You will slip and fall today","Beware of red Vehicles","You will get a promotion today","You will become king one day","You will win the Nobel prize next year","You will win every contest you enter today","Your boss will go on leave for the next week","You will buy a car soon","You will become God"};
int forval=(int)Math.round(Math.random()*10);
return prediction[forval];
}

The different fortunes are stored in an array of strings and the value obtained from the random function is used as the array index. The value from random is between 0 and 1, and is multiplied by 10 to get the final value. Hence, the array will not go out of bound.

Friday, April 3, 2009

Goldilocks - program to check the temperature

import java.io.Console;
import java.io.IOException;

class Goldilocks
{
public static void main(String[] args) throws IOException
{
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
String portemp = c.readLine("Enter the temperature of some porridge in degree centigrade: ");
int temp =(int)Float.parseFloat(portemp);
if (temp>40)
System.out.println("Too hot");
else if(temp<40)
System.out.println("Too cold");
else
System.out.println("just right ");
}
}

Monday, February 2, 2009

Simple Java Program to understand enum basics

/*
------------------------------------------------------------------------
Simple Java Program to understand enum basics
------------------------------------------------------------------------
*/
enum Cars{ESCORT,FIAT,ALTO,ZEN}
class EnumExample{

public static void main(String args[]){

Cars oldest = Cars.FIAT;
System.out.println(oldest);

for(Cars c :Cars.values())
System.out.println(c);
}
}
/*
------------------------------------------------------------------------
Output of enum example
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>javac EnumExample.java

C:\Users\flower\Documents\javaprogs>java EnumExample
FIAT
ESCORT
FIAT
ALTO
ZEN

*/

Sunday, January 25, 2009

Simple Java Program that uses my assertion

/*
------------------------------------------------------------------------
Simple Java Program that uses my assertion
------------------------------------------------------------------------
*/

class MyAssertionExample{

static boolean myassertionenabled;//default value is false
static void myassert (boolean b){
if(myassertionenabled & !b){
throw new AssertionError();
}

}

public static void main(String args[]){

try{
if (args[0].equals("ea")){
myassertionenabled=true;}
}catch(ArrayIndexOutOfBoundsException AE){}//dont throw exception if no arguments are passed
int a=1;
try{
myassert(a==2);//value of 'a' should be 2, else throw an assertion exception error
}catch(AssertionError E){
System.out.println("Value of a is not equal to 2 and assertion is enabled");
}
}
}
/*
------------------------------------------------------------------------
Output of AssertionExample with assertions enabled
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>javac MyAssertionExample.java

C:\Users\flower\Documents\javaprogs>java MyAssertionExample ea
Value of a is not equal to 2 and assertion is enabled

------------------------------------------------------------------------
Output of AssertionExample with assertions not enabled
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>java MyAssertionExample

*/

Simple Java Program to understand assertions

/*
------------------------------------------------------------------------
Simple Java Program to understand assertions
------------------------------------------------------------------------
*/

class AssertionExample{

public static void main(String args[]){

int a=1;
try{
assert(a==2);//value of 'a' should be 2, else throw an assertion exception error
}catch(AssertionError E){
System.out.println("Value of a is not equal to 2 and assertion is enabled");
}
}
}
/*
------------------------------------------------------------------------
Output of AssertionExample with assertions enabled
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>javac AssertionExample.java

C:\Users\flower\Documents\javaprogs>java -ea AssertionExample
Value of a is not equal to 2 and assertion is enabled

------------------------------------------------------------------------
Output of AssertionExample with assertions not enabled
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>java AssertionExample

*/

Sunday, January 18, 2009

Simple java program to understand class imports

/*---------------------------------------------------------------------------------------
Simple java program to understand class imports
---------------------------------------------------------------------------------------*/
import javaprogs.basic.*;
import javaprogs.packagexamples.*;
import javaprogs.packagexamples.car;

class carexample{

public static void main(String args[]){
int j =2;

car fiat = new car();
fiat.setnumberoftyres(j);
fiat.displaynumberoftyres();

}
}

/*
---------------------------------------------------------------------------------------
Output of program to understand class imports
---------------------------------------------------------------------------------------
ambiguous reference
---------------------------------------------------------------------------------------
The output before adding the line "import javaprogs.packagexamples.car;"
---------------------------------------------------------------------------------------
C:\Users\flower\Documents>javac carexample.java
carexample.java:12: reference to car is ambiguous, both class javaprogs.packagex
amples.car in javaprogs.packagexamples and class javaprogs.basic.car in javaprog
s.basic match
car fiat = new car();
^
carexample.java:12: reference to car is ambiguous, both class javaprogs.packagex
amples.car in javaprogs.packagexamples and class javaprogs.basic.car in javaprog
s.basic match
car fiat = new car();
^
2 errors
---------------------------------------------------------------------------------------
The output after adding the line "import javaprogs.packagexamples.car;"
---------------------------------------------------------------------------------------
C:\Users\flower\Documents>javac carexample.java

C:\Users\flower\Documents>java carexample
Number of tyres is:3
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
The output if the line "import javaprogs.basic.car;" was added instead of the line "import javaprogs.packagexamples.car;"
---------------------------------------------------------------------------------------
C:\Users\flower\Documents>javac carexample.java

C:\Users\flower\Documents>java carexample
Number of tyres is:2
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
The car class inside "javaprogs.packagexamples" package
---------------------------------------------------------------------------------------
package javaprogs.packagexamples;

public class car{

private int numberoftyres;

public void setnumberoftyres(int i){

numberoftyres=i+1;
}

public void displaynumberoftyres(){
System.out.println("Number of tyres is:"+numberoftyres);
}

}
---------------------------------------------------------------------------------------
The car class inside "javaprogs.basic" package
---------------------------------------------------------------------------------------
package javaprogs.basic;

public class car{

private int numberoftyres;

public void setnumberoftyres(int i){

numberoftyres=i;
}

public void displaynumberoftyres(){
System.out.println("Number of tyres is:"+numberoftyres);
}

}
---------------------------------------------------------------------------------------
*/

Monday, December 22, 2008

Java GUI to convert Julian date to Gregorain and vice versa

This simple java desktop application can convert Julian dates into Gregorain and Gregorian dates to Julian dates.This tool is useful for those working with both distributed and mainframes at the same time. The dates in the distributed platforms are in Gregorian format(DD/MM/YYYY) and in Julian format (YY/DDD)in the mainframes.

The conversion makes use of the below functions to do the calculations.

public boolean isleapyear(int year){
if ((year%4!=0)||(year%4==0)&&(year%100==0)&&(year%400!=0))
return false;
else
return true;
}

public void jultogreg() {
int gdate,gmonth;
int mondays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int jyear=Integer.parseInt(jTextField1.getText());
int jdate=Integer.parseInt(jTextField2.getText());
if(jyear>=10 && jyear<100){jTextField3.setText("20"+jyear);}
else if(jyear>0 && jyear<100){jTextField3.setText("200"+jyear);}
else {JFrame mainFrame = JulianToGregorianApp.getApplication().getMainFrame(); JOptionPane.showMessageDialog(mainFrame, "The Julian Year is out of range. Enter a value greater than 1 and less than 99.", "Input Error", JOptionPane.ERROR_MESSAGE);} if(jdate<1 ||jdate >367){
JFrame mainFrame = JulianToGregorianApp.getApplication().getMainFrame(); JOptionPane.showMessageDialog(mainFrame, "The Julian Date is out of range. Enter a value greater than 1 and less than 367.", "Input Error", JOptionPane.ERROR_MESSAGE);} if((isleapyear(jyear))){mondays[1]++;}
gdate=jdate; for(gmonth=0;gmonth<12;gmonth++){
if((gdate-mondays[gmonth])<1){ gmonth++;
if ((gdate-mondays[gmonth])==0) {gdate=mondays[gmonth];} jTextField4.setText(gmonth+"");
jTextField5.setText(gdate+""); break;}
gdate-=mondays[gmonth]; } }

public void gregtojul() {
int i;
int gmondays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int ggyear=Integer.parseInt(jTextField3.getText());
int ggmonth=Integer.parseInt(jTextField4.getText());
int ggdate=Integer.parseInt(jTextField5.getText());
if((isleapyear(ggyear))){gmondays[1]++;} ggmonth--;
for(i=0;i<ggmonth;i++){ ggdate+=gmondays[i]; }
jTextField2.setText(ggdate+""); }

The conversion takes into consideration if the year is a leap year or not to do the calculations. The leap year or not function is very handy in determining if a given year is leap or not.

Tuesday, December 16, 2008

Simple Java Program to understand String Manipulation

/*
------------------------------------------------------------------------
Simple Java Program to understand String Manipulation
------------------------------------------------------------------------
*/
class VeryComplexHelloWorld{

public static void main(String args[]){
int i,j;
String helloworldmessage=" HelloWorld ";
String helloworld="H-E-L-L-O-W-O-R-L-D";
String[] listofchars;
String helloworldobtianedafterspliting="";
listofchars= helloworld.split("-");//splitting a string based on a delimiter
j=listofchars.length;//getting the length of an array
System.out.println("This Program does numerous manipulations to generate the Hello World message");
for(i=0;ihelloworldobtianedafterspliting=helloworldobtianedafterspliting.concat(listofchars[i]);//Concatinating strings
}
helloworldmessage=helloworldmessage.trim();//to remove leading and trailing spaces
helloworldmessage=helloworldmessage.toUpperCase();//Converting all characters of string to uppercase
if(helloworldmessage.equals(helloworldobtianedafterspliting)){//to compare two strings
System.out.println(helloworldmessage);
}
}
}
/*
------------------------------------------------------------------------
Output of Complex Hello World
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>javac VeryComplexHelloWorld.java

C:\Users\flower\Documents\javaprogs>java VeryComplexHelloWorld
This Program does numerous manipulations to generate the Hello World message
HELLOWORLD

------------------------------------------------------------------------

*/

Saturday, December 13, 2008

Simple Java Program to understand threading

/*
------------------------------------------------------------------------
Simple Java Program to understand threading
------------------------------------------------------------------------
*/
public class ThreadingExample{

private static class createdthread implements Runnable{

public void run(){
int i;
String threadname=Thread.currentThread().getName();//to get the name of current thread
System.out.format("%s is executing\n",threadname);
try{
for(i=0;i<4;i++){
Thread.sleep(1000);//pausing the thread for 1 second
System.out.format("%s",threadname+":"+i+"\n");
}
}catch(InterruptedException e){
System.out.format("%s is Interrupted\n",threadname);
}

}
}
public static void main(String args[]) throws InterruptedException{
int timeforexecutingt0;
timeforexecutingt0=Integer.parseInt(args[0]);
Thread t0 = new Thread(new createdthread());
Thread t1 = new Thread(new createdthread());
t0.start();//start executing thread 0
t1.start();//start executing thread 1
t0.join(timeforexecutingt0);//wait for thread 0 to finish within 'timeforexecutingt0'
t0.interrupt();//interrupt thread 0

}

}

/*
------------------------------------------------------------------------
Time for thread 0 will differ from one system to another. It may also differ based on the load on the system at the time of execution.Try finding whats the optimal time for your setup.
------------------------------------------------------------------------

C:\Users\flower\Documents\javaprogs>javac ThreadingExample.java

------------------------------------------------------------------------
Output when the execution time for thread 0 is not sufficient
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>java ThreadingExample 3000
Thread-0 is executing
Thread-1 is executing
Thread-1:0
Thread-0:0
Thread-1:1
Thread-0:1
Thread-0 is Interrupted
Thread-1:2
Thread-1:3

------------------------------------------------------------------------
Output when the execution time for thread 0 is sufficient
------------------------------------------------------------------------

C:\Users\flower\Documents\javaprogs>java ThreadingExample 5000
Thread-0 is executing
Thread-1 is executing
Thread-0:0
Thread-1:0
Thread-0:1
Thread-1:1
Thread-1:2
Thread-0:2
Thread-1:3
Thread-0:3

C:\Users\flower\Documents\javaprogs>*/

Simple java program to understand compiling and running a program inside a package

/*---------------------------------------------------------------------------------------
Simple java program to understand compiling and running a program inside a package
---------------------------------------------------------------------------------------*/
package javaprogs.basic;

class helloworld{

public static void main(String args[]){

System.out.println("Helloworld in basic package");

}

}
/*
---------------------------------------------------------------------------------------
Output of compiling and running a package
---------------------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs\basic>javac helloworld.java

C:\Users\flower\Documents\javaprogs\basic>cd ..

C:\Users\flower\Documents\javaprogs>cd ..

C:\Users\flower\Documents>java javaprogs.basic.helloworld
Helloworld in basic package
*/

Friday, December 12, 2008

Simple Java Program to understand finally Block

/*------------------------------------------------------------------------
Simple Java Program to understand finally Block
------------------------------------------------------------------------*/
class finallyexample{
public static void main(String args[]){
int i,total=0;
try{
for(i=0;i<3;i++){
System.out.println(args[i]);
total+=Integer.parseInt(args[i]);//converting string to integer
}
System.out.println(" The total is " + total);
//this block is executed only when number of arguments is 3 or more }
catch (ArrayIndexOutOfBoundsException a){
//this block is executed only when number of arguments is less than 3
System.out.println("A minimum of 3 arguments are required");
} finally{
//this block is executed irrespective of the number of arguments passed to the program
System.out.println(" The total is " + total); } }}
/*------------------------------------------------------------------------
Output with the "finally" block
------------------------------------------------------------------------
C:\j2sdk1.4.2_04\bin>javac finallyexample.java
C:\j2sdk1.4.2_04\bin>java finallyexample 1 2 3
1
2
3
The total is 6
The total is 6
C:\j2sdk1.4.2_04\bin>java finallyexample 1 2
1
2
A minimum of 3 arguments are required
The total is 3
------------------------------------------------------------------------*/

Thursday, December 11, 2008

Simple Java Program to understand Exception Handling

/*------------------------------------------------------------------------
Simple Java Program to understand Exception Handling
------------------------------------------------------------------------*/
class exceptionexample{
public static void main(String args[]){
int i;
try{
for(i=0;i<3;i++){
System.out.println(args[i]);
}
} catch (ArrayIndexOutOfBoundsException e){
System.out.println("A minimum of 3 arguments arerequired");
} }}
/*------------------------------------------------------------------------
Output without the "try" block
------------------------------------------------------------------------
C:\j2sdk1.4.2_04\bin>javac exceptionexample.javaC:\j2sdk1.4.2_04\bin>java exceptionexample 1 2 3 4123C:\j2sdk1.4.2_04\bin>java exceptionexample 1 212Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at exceptionexample.main(exceptionexample.java:5)
------------------------------------------------------------------------
Output with the "try" block
------------------------------------------------------------------------
C:\j2sdk1.4.2_04\bin>java exceptionexample 1 212A minimum of 2 arguments are required
------------------------------------------------------------------------*/

Friday, April 25, 2008

Java - switch example

Java has a switch statement like most other languages. This example program demonstrates the switch statement without "break" after each case.

The output will be :This is three when x=3
This is default when x not equal to 1 or 2 or 3


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

int x=3;

switch(x){
case 1:
System.out.println("This is one");
default:
System.out.println("This is default");
case 2:
System.out.println("This is two");
case 3:
System.out.println("This is three");

}

}
}

Saturday, June 16, 2007

Forn loop- executing the for loop n times

The for loop is a useful control statement.But if you want to execute the for loop "n" number of times, just nesting it will work fine. The following java program will do that job well.


classforn {public static void main(String args[]){int i,j,n=Integer.parseInt(args[0]);
for(i=0;i<n;i++)
{ for(j=0;j<5;j++){
System.out.println(j); }

}

}
}

The output for

C:\javaprogs>java forn 3
would be
0
1
2
3
4
0
1
2
3
4
0
1
2
3
4
The problem arises when the for loop has to be executed different number of times during the "n" executions.Hope that makes sense. The number of times the for loop has to be executed has to be stored in a array of size n. So the modified program to execute the for loop as per the value stored in the array would be-


classforn {public static void main(String args[]){int i,j,n=Integer.parseInt(args[0]);
for(i=0;i<n;i++){
for(j=0;j<(Integer.parseInt(args[i+1]));j++){

System.out.println(j); }

}

}
}

The output for

C:\javaprogs>java forn 3 2 4 3
would be
0
1
0
1
2
3
0
1
2

The point is "Do we need a forn loop" or can this be done better using a "while" or "until". The extra overhead in storing the array and checking individual conditions can be avoided. If anybody has program that cant be solved using the while or until and requires a forn loop pls let me know.