Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Java program for Insertion sort . Arrange elements using Insertion Sort with tutorial

The insertion sort is a simple comparison sort algorithm. Each iteration of insertion sort removes an element from the input array and inserts it into the correct position in the array being sorted. Insertion sort keeps the left side of the array is sorted . At each iteration , a[i] is inserted at the appropriate position in the sorted array and i is increased. . The resulting array after ith iterations will have i+1 sorted elements from the left (i.e. a[1..i+1]) . Insertion sort is similar to selection sort. Advantage of Insertion sort is that it only traverse as many elements as required to find the right location , while selection sort must traverse all remaining elements to find the absolute smallest element.
Suppose we have the elements a[1..n] to be sorted. At each iteration of the algorithm, the array has two parts .For the i th iteration , first part is a[1..i+1] which is sorted, the second part a[i+2..n] is still unsorted . Assume that a[i+2] is assigned to a temp variable. In order to insert element a[i+2] into the sorted part, it is compared with a[i+1], a[i], a[i-1], a[i-2] , etc. Suppose a[i-1] is the appropriate position to insert , then the elements a[i+1] is shifted to a[i+2] and a[i] is shifted to a[i+1]. a[i-1] is shifted to a[i] , and temp value is inserted into a[i-1] .
Insertion sort is vey simple and efficient for small input data. It is much less efficient on large data .
Example : Now we have the following elements to be sorted . For each iterations , we can see the sorted and unsorted elements. The bold elements are sorted on each iteration.
6, 4,2, 9,3, 1

Iteration 1
4 6 2 9 3 1
Iteration 2
2 4 6 9 3 1
Iteration 3
2 4 6 9 3 1
Iteration 4
2 3 4 6 9 1
Iteration 5
1 2 3 4 6 9

The following is the code for Inssertion Sort
   
public class InsertionSort {
public static void main(String[] args) {
int array[] = { 6, 4,2, 9,3, 1 };
System.out.println("Given Elements ");
for (int k = 0; k< array.length; k++) {
System.out.print(array[k] + " ");
}
int j, temp;
// Logic for Insertion Sort
for (int i = 1; i < array.length; i++) {
temp = array[i];
j = i;
while ( j>0 && (array[j-1] > temp)) {
array[j] = array[j - 1];
j = j - 1;
}
array[j] = temp;
}
System.out.println("\nSorted Elements ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}


Output:
D:\as2\JF4>java InsertionSort
Given Elements
6 4 2 9 3 1
Sorted Elements
1 2 3 4 6 9
Read more...

Java program to print Beprisque numbers between two numbers

A number is called a Beprisque if it is the only number between a prime and a square number ( i.e. that number should be a prime number plus one and a square number minus one OR a prime number minus one and a square number plus one). For example , 10 is a Beprisque number because it is the only number between 9 which is a square number and 11 which is a prime number . 24 is also a Beprisque number because 24 is the only number between 23 which is a prime and 25 which is a square number . Now the logic to find the Beprisque number will be as follows. Take a number n . The number n is Beprisque number , if n-1 is prime and n+1 is square number OR n+1 is prime number and n-1 is square number. To implement the above logic , I have written two functions . 1) isPrime() which is to check the number is prime or not . 2) isSquare() is to check the given number is square or not. The folllowing code prints all the Beprisque numbers between given two numbers (min and max) where min, max is accepted through keyboard. The logic to check the given number is square or not will be (Math.sqrt(num) == (int) Math.sqrt(num)) where num is the given number i.e. squareRoot of number (num) should be an integer
*/
    
import java.util.Scanner;
public class BeprisqueNumbers {
public static void main(String argv[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter min");
int min = sc.nextInt();
System.out.println("Enter max");
int max = sc.nextInt();
System.out.println("Beprisque Numbers between " + min + " and " + max);

//Logic to print Beprisque Numbers
for (int n = min; n < max; n++) {
if ( isPrime(n - 1) && isSquare((double)(n+ 1)) || isPrime(n+ 1) && isSquare((double)(n- 1)) ) System.out.println(n);
}
}
//to check prime number
public static boolean isPrime(int num) {
int i=0;
for ( i = 2; i < num ; i++) {
if ((num % i) == 0 ) return false;
}
return true;
}
//to check square
public static boolean isSquare(double num) {
return (Math.sqrt(num) == (int) Math.sqrt(num));
}
}


Output :

Read more...

Java program that replaces two or more consecutive characters / blanks in a string by a single character / blank. Use Regular Expression.

Sometimes interview questions may be little bit tricky . The following tricky questions may be asked
1. A string has thousand or two thousand zeros . Replace all consecutive zeros with a single zero without using loop
2 String str = "200000000000000000000000500000000000000000" . Make it to 2050 without using loop
The answer should be in one line and should be a general solution to all similar problems , should not be a specific solution to a particular problem.
In college / school computer practical lab , the following program may be given to solve. WAP that replaces two or more consecutive characters / blanks in a string by a single character / blank. For example, if the input is Keppplarrr-222 2b issss 222.444 timmes the sizzzze of the eeearth and the output should be Keplar-2 2b is 2.4 times the size of the earth.
The solution to all the above questions, without using loop will be using Regular Expression (RegExp) . The answer using RegExp is , str.replaceAll( "(.)\\1+", "$1" )
"(.)\\1+ " - The meaning of the metacharater used in the expression is
(.) - match any charater
\1 - matchs text similar to that matched within the first parenthesized .
+ - One or more times
The program for the above questions is as follows . The problems are solved in two ways . One is using Regular Expressions and another is using for loop. In method 2 , charAt (int index), deleteCharAt(int index) are used where char charAt (int index) - Returns the char value at the specified index and StringBuffer deleteCharAt(int index) - Removes the char at the specified index*/
    
class ReplaceConsecutiveChar
{
public static void main (String args[])
{
//String inputStr ="Keppplarrr-222 2b issss 222.444 timmes the sizzzze of the eeearth";
String inputStr ="200000000000000000000000500000000000000000";
String newString=ReplConsectiveCharM1(inputStr);
String newString1 = ReplConsectiveCharM2(inputStr);
System.out.println("Input String : " + inputStr);
System.out.println("Using RegExp : "+ newString + "\nUsing For Loop : " + newString1);
}

// Method 1 : Using RegExp
public static String ReplConsectiveCharM1(String str)
{
return(str.replaceAll( "(.)\\1+", "$1" ));
}

// Method 2 : Using For Loop
public static String ReplConsectiveCharM2(String s)
{
StringBuffer sb=new StringBuffer(s);
for (int i=0; i<sb.length() ; i++)
{
for (int j=i+1; j<sb.length() ; j++)
{
if (sb.charAt(i) ==sb.charAt(j) )
{
sb.deleteCharAt(j);
j--;
}
else break;
}
}
return sb.toString();
}

}


Output


Read more...

Write own code for Java String indexOf() to find position of a given string in a source string

Let us first see what java String indexOf() does . It returns position of the given character / substring in a given String from the first occurance or starting from the specified position. IndexOf() is overloaded into four methods.
1. indexOf(int ch) - Returns the position / index of the given charater with in this string .
2. indexOf(int ch, int fromIndex) - Same as the above method but search starts from the the specified index.
3. indexOf(String str) - Returns the position / index of the given String with in this string
4. int indexOf(String str, int fromIndex) - Same as the 3rd method but search starts from the the specified index.
Now let us write code for indexOf(String source, String substr, int startPos, int occurrence, char caseSensitive) which does the same work with more options using Regexp, where source is the original string to search in , substr is the substring to be searched in the original string , startPos is the starting position to search , occurrence is used to tell which match to get. There may be more than one substring in the given string . If we give occurrence is 2 , then it will return the position of the second match. Matching can be done using CaseSensitive or Case In Sensitive . We have to pass 'N' for CaseInSensitive .
    
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
class customIndexOf
{
public static void main(String args[])
{
String source="Using Db2 UDB , Udfs can be created. DB2 UDFs is DB2 User Defined Functions";
String sub="db2";
System.out.println("Position of " + sub + " = "+ indexOf(source,sub,0,2,'N' ));
sub="UDFs";
System.out.println("Position of " + sub + " = "+ indexOf(source,sub,0,1,'Y' ));
sub="c";
System.out.println("Position of " + sub + " = "+ indexOf(source,sub,0,1,'N' ));
sub="DB2";
System.out.println("Using Java Index of () Position of " + sub + " = "+ (source.indexOf(sub, 0)+1));
}

public static int indexOf(String source, String substr, int startPos, int occurrence, char caseSensitive)
{
int position = 0;
int flag=2;
int occurrenceCount = 0;
if(caseSensitive=='Y') flag=0;
if ( source == null || source.length()==0) return -1;
Pattern pattern=null;
try
{
pattern = Pattern.compile(substr, flag);
}
catch (PatternSyntaxException e)
{
return 0;
}
Matcher matcher = pattern.matcher(source);
if (matcher.find(startPos))
{
position = matcher.start()+ 1;
occurrenceCount++;
while ((occurrenceCount < occurrence) && (matcher.find()))
{
position = matcher.start() + 1;
occurrenceCount++;
}
}

if (occurrenceCount!=occurrence) position =0 ;
return (position);
}
}



Output:

Read more...

Comparing Objects by values equality by overriding equal / hashCode() method with example.

Basically , Obj1.equals(Obj2) returns true , if Obj1 and Obj2 refer to the same object that means the references of two Objects (Obj1 & Obj2 ) point to the same object which is equal to if (Obj1==Obj2) . This is the default implementation of the equal method of an Object. But we need to compare one or more values of the two Objects. This can be done by overriding the equals method (i.e boolean equals(Object obj) ) . By overriding equal method , you can write your own logic to decide wheather two objects of the same class are equal or not that is the implementor decides which values should be equal to consider two objects to be equal. In our example , in Student class, the two student objects equality is decided by the total marks.
In the following program, Student class is defined with fields of name , Mark1 , Mark2, Mark3 and One constructor to assign values and public methods to access fields. We can create one or more student objects from Student class. Our objective is to check two student objects are equal or not based on the total value of 3 marks .So we have overrided the equal method by writing the logic to compare total marks of two objects of same class. The hashCode method has to be redefined as we are redefining the equals method . The concept is the Equal objects must have equal hash codes.

class Student
{
private String name;
private int mark1;
private int mark2;
private int mark3;
public Student(String name, int m1, int m2, int m3)
{
this.name=name;
this.mark1=m1;
this.mark2=m2;
this.mark3=m3;
}
public String getName() { return this.name; }
public int getMark1() {return this.mark1;}
public int getMark2() { return this.mark2; }
public int getMark3() { return this.mark3; }

public void printValues()
{
System.out.println("name : " + this.name);
System.out.println("M1 : " + this.mark1);
System.out.println("M2 : " + this.mark2);
System.out.println("M3 : " + this.mark3);
}
public boolean equals(Object obj)
{
boolean eq=false;
//if both object's reference is equal means , objects are equal
if(this == obj) return true;
if (obj instanceof Student)
{
Student student = (Student) obj;
int tot1=student.getMark1() + student.getMark2() + student.getMark3();
int tot2=this.getMark1() + this.getMark2() + this.getMark3();
if (tot1==tot2) eq=true;
//the following line checks name also to decide Object's equality
// if ((tot1==tot2) &&( student.getName().equals(this.getName())) ) eq=true;
return eq;
}
else
{
return false;
}
}
//hashCode() is overrided.
public int hashCode()
{
int hash = 19;
String tot1=Integer.toString(mark1+mark2+mark3);
hash = 37 * hash + tot1.hashCode();
//hashCode() of 'name' field is also considered in the below line. If equal method use 'name' field means , hashCode() also has to use.
//hash = 37 * hash + name.hashCode() +tot1.hashCode();
return hash;
}
}

//Class to create Students objects and compare two student objects for equality using overrided equal method

class OverrideEqual
{
public static void main(String args[])
{
Student stu1 = new Student("ABC", 50, 30, 21);
Student stu2 = new Student("XYZ", 50, 30, 21);
stu1.printValues();
System.out.println("");
stu2.printValues();
if ( stu1.equals(stu1) ) System.out.println("Both object references point to the same object"); else System.out.println("Both are different objects");
if ( stu1.equals(stu2 ) ) System.out.println("Both student are equal"); else System.out.println("Both students are not equal");
if ( stu2.equals(stu1 ) ) System.out.println("Two students are equal"); else System.out.println("Two student are not equal");
if (stu1.hashCode()==stu2.hashCode()) System.out.println("Both Student Object Hashcode are equal"); else System.out.println("Both Student Object Hashcode are not equal");

}
}


//Output :

Read more...

Decimal to Binary in Java using Loop Example code

/* The following code illustrates how to convert an Integer to Binary using loop . We can convert an Integrer to Binary in several ways . We have converted Integet to Binary in two ways . First funtion returns binary as String . IInd Function returns Binary as a integer. For returning as a string , we can easily concatenate the value of (number%2 ) in reverse order. In the second function , steps to conver integer to binary
For example, consider 10 as a integer.

1) 10 % 2 = 0 - Ist binary digit
2) 10/2 = 5
3) 5%2 = 1 - IInd binary digit
4) 5/2 = 2
5) 2%2 = 0 - IIIrd binary digit
6) 2/2 = 1
7) 1%2 = 1 - IV th binary digit

Now convert individual digitis as single number which gives the binary number.
0 + 1*10 + 0*100 + 1 * 1000 = 0+10+0+1000 = 1010 */



import java.util.Scanner;

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

Scanner sc = new Scanner(System.in);

System.out.println("Please enter Integer");

int number = sc.nextInt();

String bin=binary1(number);

long bin1=binary2(number);

System.out.println("Using Function 1 : Binary of " +number + " is " + bin);
System.out.println("Using Function 2 : Binary of " +number + " is " + bin1);
}

public static String binary1 (int num)
{
int sum=0;
int temp=1;
String bin="";
if (num==0) return "0";
while (num!=0)
{
bin=(num%2)+ bin;
num=num/2;

}
return bin;
}



public static long binary2 (int num)
{

long sum=0;
long temp=1;

while (num!=0)
{
sum = sum + temp*(num%2);
temp=temp*10;
num=num/2;

}

return sum;

}

}




Output :

Running the above program

D:\as2\JF1>java binaryLoop
Please enter Integer
10
Using Function 1 : Binary of 10 is 1010
Using Function 2 : Binary of 10 is 1010

D:\as2\JF1>java binaryLoop
Please enter Integer
25
Using Function 1 : Binary of 25 is 11001
Using Function 2 : Binary of 25 is 11001


Read more...

Java Program to Convert Integer to Binary using Recursion

// The following code illustrates how to convert an Integer to Binary using Recursion. We can also convert an integer to Binary using the toBinaryString(number) method using Integer Class.




import java.util.Scanner;

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

Scanner sc = new Scanner(System.in);

System.out.println("Please enter Integer");

int number = sc.nextInt();

System.out.println("Using toBinaryString(number) Binary of " +number + " is " + Integer.toBinaryString(number)); // Convers Integer to Binary using toBinaryString(number) method...

String binary=binary(number);

System.out.println("Using Recursion Binary of " +number + " is " + binary);

}

// The Following Recursive function converts Integer to Binary...

public static String binary (int num)
{

if (num==0) return "0"; else if (num==1) return "1";
else if (num<0) return ("-" + binary(-num));
else return( binary(num/2 ) +( char) ((num%2) +48)); }
}


In the above function ((num%2) +48) gives the ascii value of a digit . (char) ((num%2) +48) converts ascii to char ( for example ascii value 48 is equal to digit 1 , 49-> 1)


Output :

Running the above program

D:\as2\JF1>java binary
Please enter Integer
10
Using toBinaryString(number) Binary of 10 is 1010
Using Recursion Binary of 10 is 1010

D:\as2\JF1>java binary
Please enter Integer
100
Using toBinaryString(number) Binary of 100 is 1100100
Using Recursion Binary of 100 is 1100100

D:\as2\JF1>java binary
Please enter Integer
25
Using toBinaryString(number) Binary of 25 is 11001
Using Recursion Binary of 25 is 11001


Read more...

How to read Input thru Keyboard in Java with Example , Getting Input from Console

In java there are several ways to read input through keyboard .
1) Using the BufferedReader Class
2) Using the JOptionPane class using GUI
3) Using the Scanner class in JDK 1.5

The following example shows how to use all the above mentioned classes to get input from the console Keyboard. */




import javax.swing.JOptionPane;
import java.util.*;
import java.io.*;
public class InputKeyBoard
{

public static void main(String args[]) throws IOException
{
String st_name = JOptionPane.showInputDialog("Enter Your Name: "); // Displays Input Dialog Box to get Input

Scanner sc = new Scanner(System.in);
System.out.println("Please enter Qualification");
String className = sc.next();

System.out.println("Please enter Mark1");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String strMark1 = br.readLine();
int mark1 = Integer.parseInt(strMark1);

System.out.println("Please enter Mark2");
int mark2 = sc.nextInt();

System.out.println("Please enter Mark3");
int mark3 = sc.nextInt();

int average=(mark1+mark2+mark3)/3;

System.out.println("Name :" + st_name);
System.out.println("Class :" + className);
System.out.println("Mark1 = " + mark1 + ", Mark2= " + mark2 + ", Mark3= " + mark3 );
System.out.println("Average :" + average);

}
}


//Note : When we use Scanner Class , No need to parse integer, long , ....

Running the above program :

Output :

D:\as2\JF1>java InputKeyBoard
Please enter Qualification
MBA
Please enter Mark1
90
Please enter Mark2
93
Please enter Mark3
96
Name :John
Class :MBA
Mark1 = 90, Mark2= 93, Mark3= 96
Average :93


Read more...

File Copy in Java with Example, Code to copy contents of one file to another file.

/*The following program accepts two files from the command line and copies one file into another file.
For copying one file to another file , we may check the following conditions.

1) Source file exists or not
2) It is a file or not
3) The file is readble or not (using canRead()))
4) Target file already exists or not . If already exists , prompt to overwrite.
5) Destination folder exist or not
6) Target folder is writeable or not
For checking the above conditions, we can use File class in java.io.


For Copying the file ,
-> We have to create InputStream and OutputStream
-> Read the bytes from the source file until EOF
-> Write the bytes into the target file.



I have used 2 methods to copy the files. In the method 2 , the whole file contents are read at once and copied to the target file.
*/



import java.io.*;
import java.util.*;

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


if(args.length!=2) { System.out.println("Improper arguments . Syntax : java filecopy sourcefile targetfile "); System.exit(0); }

File source_file=new File(args[0]);
File target_file=new File(args[1]);

// First make sure the source file exists, is a file, and is readable.
if (!source_file.exists())
{

System.out.println("Source File Not Found");
System.exit(0);
}

if (!source_file.isFile())
{

System.out.println(source_file + " is Not a file");
System.exit(0);
}


if (target_file.isDirectory())
target_file = new File(target_file, source_file.getName());

String YN="Y";
if (target_file.exists()) {
System.out.print("Target file already exists . Do you overwrite ? (y/n) ");
System.out.flush();
Scanner scanner=new Scanner(System.in);
YN=scanner.next();
}
//BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
// String response = in.readLine();

// Check the response. If not a Yes, abort the copy.
if (YN.equalsIgnoreCase ("Y") )
{
String target_dir = target_file.getParent();

if (target_dir == null) target_dir = System.getProperty("user.dir");
File folder = new File(target_dir);
if (!folder.exists())
{
System.out.println("Destination Folder doesn't exist " + target_dir);
System.exit(0);
}

if (folder.isFile())
{
System.out.println("Destination is not a directory: " + target_dir);
System.exit(0);
}

}
else
{
System.out.println("Abort Overwriting" ) ;
System.exit(0);
}

try
{

copyFile(source_file, target_file);
// copy(source_file, target_file); // for using the method 1

}
catch (Exception e)
{
System.out.println("Error");
}



}


//Method 1


private static void copy(File source, File target) throws IOException {

System.out.println("Copying File......");

InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target);

byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) !=-1) {
out.write(buf, 0, len);
}
in.close();
out.close();

System.out.println(" file copied");
}


// Method 2

private static void copyFile(File source, File target) throws IOException {

System.out.println("Copying File......");

InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target);

// Transfer bytes from in to out
byte[] buf = new byte[(int) source.length()];
in.read(buf);

out.write(buf);

in.close();
out.close();

System.out.println(" file copied");
}

}


Running the above program

D:\as2\j2eeforum>java FileCopy FileCopy.java FileCopy2.java
Copying File......
file copied

D:\as2\j2eeforum>java FileCopy d:\as2\kk.txt kk1.txt
Target file already exists . Do you overwrite ? (y/n) y
Copying File......
file copied


D:\as2\j2eeforum>java FileCopy d:\as2\kk.txt kk1.txt
Target file already exists . Do you overwrite ? (y/n) n
Abort Overwriting

D:\as2\j2eeforum>java FileCopy d:\as2\kkk.txt kk1.txt
Source File Not Found
Read more...

Java String to Date , Date to String Example code using SimpleDateFormat , parse , format

SimpleDateFormat Class is used for Parsing ( String to Date ) and Formatting (Date to String ) . It has many methods . For converting String to Date and vice-versa , the following methods are used .

1) parse(String text, ParsePosition pos) - Parses text from a string to convert to a Date
2) format(Date date, StringBuffer toAppendTo, FieldPosition pos) - Formats the given Date into a date/time string(which may be dd/MM/yyyy,dd/MMM/yyyy, yyyyy.MMMMM.dd GGG hh:mm aaa etc ) and appends the result to the given StringBuffer.

The following code converts spring to date and date to string ......
    
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatParse {

public static void main(String[] args) {

SimpleDateFormat out = new SimpleDateFormat("dd/MM/yyyy");

SimpleDateFormat out1 = new SimpleDateFormat("dd-MMM-yyyy");

System.out.println("String to Date : " + StringToDate(15, 06, 2011) );// which returns a date

System.out.println("String to Date : " + StringToDate("15/06/2011") );// which returns a date

// Now Date is converted into String for printing in a format (dd/mm/yyy or dd/MMM/yyyy)

System.out.println("Date to String : " + out.format (StringToDate(15, 06, 2011) ));// which returns a string

System.out.println("Date to String : " + out1.format (StringToDate("15/06/2011") )); // which returns a string

}



// The following two functions are used to convert string to date (One accepts (dd/mm/yyyy) , another method accepts day, month & year)




public static Date StringToDate(String dateString) // Accepts a Date String and Converts to Date
{
SimpleDateFormat in= new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
try {

date = in.parse(dateString);

} catch (ParseException e)
{
e.printStackTrace();
}
return date;
}


public static Date StringToDate(int day, int month, int year) // Accepts a Day , Month and Year and Converts to Date
{
SimpleDateFormat in = new SimpleDateFormat("dd/MM/yyyy");
String dateString = day + "/" + month + "/" + year;
Date date=new Date();
try {

date = in.parse(dateString);

} catch (ParseException e)
{
e.printStackTrace();
}
return date;
}
}


Output of the above program :

String to Date : Wed Jun 15 00:00:00 IST 2011
String to Date : Wed Jun 15 00:00:00 IST 2011
Date to String : 15/06/2011
Date to String : 15-Jun-2011


Read more...

Code for generating Time Stamp in Java

The following code generates timestamp using java code in two ways.

import java.io.*;
import java.util.*;
import java.text.*;
import java.sql.Timestamp;

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

java.util.Date today=new java.util.Date();
java.sql.Timestamp todayTimeStamp =new java.sql.Timestamp(today.getTime());
java.sql.Timestamp now=new java.sql.Timestamp( System.currentTimeMillis() );
DateFormat df = new SimpleDateFormat ("yyMMddHHmmssSS");
df.setLenient(false);
String timeStamp=df.format(today);
//Date date1=df.parse("10/06/2010");
//Date date2=df.parse(dateSt2);

System.out.println("Timestamp SQL "+ todayTimeStamp);
System.out.println("Timestamp SQL2 "+ now);
System.out.println("Timestamp Util "+ timeStamp);

}
catch(Exception e){
System.out.println("Error" + e);
}
}
}
Read more...

Code for Comparing two dates in Java , Get date from keyborad and Compare

We can compare two dates in Java in the following ways

Ist Method :
-----------

Steps:
-----
1) Get two dates in the format of dd/mm/yyyy as a string.
2) Convert the Dates String to Date format using DateFormat Class.
3) Now Compare the two dates.

The following code is used to compare two dates , wheather it is equal , greater or Less than the other date.

import java.io.*;
import java.util.*;
import java.text.*;

public class DateCheck {
public static void main(String [] args){
try{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
DateFormat df = new SimpleDateFormat ("dd/MM/yyyy");
System.out.println("Enter any Date1");
String dateSt1= br.readLine();
System.out.println("Enter any Date2");
String dateSt2= br.readLine();
Date date1=df.parse(dateSt1);
Date date2=df.parse(dateSt2);
if(date1.equals(date2))
{
System.out.println("Both Dates are equal");
}
else if(date1.before(date2))
{
System.out.println("Date1 is greater than Date2");
}

else
{
System.out.println("Date2 is greater than date1");
}

}
catch(Exception e){
System.out.println("Error");
}
}
}


II) Method II
---------

Steps :

1) Get two dates as day , month , year
2) Covert into Date format using Calender Class set method
3) Compare 2 dates.

import java.util.*;
import java.text.*;
import java.io.*;
public class DateCheckCal{
public static void main(String args[]){

Calendar cal = Calendar.getInstance();
Calendar today = Calendar.getInstance();
String day="";
String month="";
String year="";

try{

BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));

System.out.println("Enter the Day in number (from 1 to 31)");
day= br.readLine();

System.out.println("Enter the Month in number (from 0 to 11) ");
month= br.readLine();

System.out.println("Enter the Month in number (eg. 1999)");
year= br.readLine();
} catch (Exception e)
{
}


cal.set(Integer.parseInt(year) , Integer.parseInt(month)-1, Integer.parseInt(day),12,0,0 ); // Month starts from 0. Set Time to is 12:00:00 for both date

today.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH), 12,0,0);

if(cal.before(today)) System.out.print("Today (" + new SimpleDateFormat("dd/MM/yyyy").format(today.getTime()) + ") is greater than the input date " + new
SimpleDateFormat("dd/MM/yyyy").format(cal.getTime()));

else if(cal.after(today)) System.out.print("Today(" + new SimpleDateFormat("dd/MM/yyyy").format(today.getTime()) + ") is less than the input date " + new
SimpleDateFormat("dd/MM/yyyy").format(cal.getTime()));

else
System.out.print("Both dates are equal.");
}
}
Read more...

Java Code to check a number Polindrome or Not

The following code is used to find wheather the given number is polindrome or not.
It accepts the number from the keyboard and reverses the number. If the entered number matches with the reverse number then it is polindrome otherwise the given number is not polindrome.

import java.io.*;

public class Palindrome {
public static void main(String [] args){
try{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter any number");
int number= Integer.parseInt(br.readLine()); // reads number as a string from keyboard and converts to number
int orgNum = number;
int rev=0;
System.out.println("Entered Number= "+orgNum);
// Logic for Reversing umber

while(number>0)
{
int d=number%10;
number=number/10;
rev=rev*10+d;

}

System.out.println("Reverse number= "+ rev);
if(orgNum == rev){
System.out.print("Given Number is palindrome");
}
else{
System.out.println("Given Number is not palindrome");
}

}
catch(Exception e){
System.out.println("Error");
}
}
}

Output 1 :
--------

Enter any number
432
Entered Number= 432
Reverse number= 234
Number is not palindrome

Output 2 :
--------
Enter any number
676
Entered Number= 676
Reverse number= 676
Given Number is palindrome
Read more...

Class Variable Vs Instance Variable in Java with example

In the following class employee, empno, name, address are Instance Variable. Because they are local to the class , when number of objects are created of the same class , seperate copies of those variables are created. They are stored in different meory location.
Sno is the Class variable or static fields . Variable that have static modifier is called static fields or Class variable. They are associated with the class, rather than with any object. One memory location is shared for all the instance of the class and one time is initialised.



The output of the following code is
4
5
6
Whenever an employee object is created , sno is incremented by one. So employee id incremented

public class Emp{

public static void main (String arg[])
{
int k=0;
employee e=new employee(10,"emp1", "New delhi");

k=e.getID();
System.out.println(k);

employee e1=new employee(10,"emp2", "New delhi");
k=e1.getID();
System.out.println(k);

employee e2=new employee(10,"emp3", "New delhi");

k=e2.getID();
System.out.println(k);
}
}


class employee{

private int empno;
private String name;
private String address;
private int id;
private static int sno = 3;

public employee(int eno, String ename, String eadd){

empno = eno;
name = ename;
address = eadd;

// increments sno and assigns to id
id = ++sno;
}

// new method to return the id instance variable
public int getID() {
return id;
}

}
Read more...

Session invalidate when browser closed using ajax

The following code illustrates how to invalidate a session when a browser is closed using Ajax. We have call the unload() function using onbeforeUnload event which calls the sessionInvalidate function which uses AJAX to call the servlet which invalidates the session.

<script language="javaScript">

function unload()
{
sessionInvalidate();
}
</script>



Body part of the JSP
--------------------

<body onbeforeUnload="unload()" >

.....
....
...
</body>





function sessionInvalidate()
{
var url = 'servlet/misc.sessInv'; sessInv is the servlet class

if (window.ActiveXObject)
{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
httpRequest = new XMLHttpRequest();
}

httpRequest.open("GET", url, true);
httpRequest.onreadystatechange = function() {processRequest(); } ;
httpRequest.send(null);

}

function processRequest()
{
if (httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
{

}
else
{
alert("Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
}
}
}


Serverside Code :
---------------

public class sessInv extends HttpServlet{


protected void doGet(HttpServletRequest requestObject, HttpServletResponse responseObject)
throws IOException
{
HttpSession session = requestObject.getSession(true);

if (session!=null)
{
session.invalidate();
}

}

protected void doPost(HttpServletRequest requestObject, HttpServletResponse responseObject)
throws IOException
{
HttpSession session = requestObject.getSession(true);
if (session!=null)
{
session.invalidate();
}

}
}
Read more...

Calculate MD5 hash (Checksum) of a file in Java

MD5 Checksum is used to check the integrity of a file. Before sending the file on the network , MD5Checksum will be calculated for the file (ie. md5Hash1) . After downloading the file again MD5Checksum is calculated (ie. md5hash2) . if md5Hash1 & md5Has2 is equal then the file is not modified or corrupted or not affected by virus.
In linux the following command is used to calculate the MD5Checksum of a file.
$ md5sum filename.
$ md5sum -c file.txt ---> file.txt will contain morethan one files with actual md5 values. The command will return OK, if the md5checksum of a file matches with the value in the file.txt .
The following code is for calculating the MD5Checksum of a file in Java.

public static String getMD5Checksum(String filename) throws Exception {
byte[] chkSum = Checksum(filename);
String md5ChkSum = "";
for (int i = 0; i < chkSum.length; i++) {
md5ChkSum += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return md5ChkSum;
}


public static byte[] Checksum(String filename) throws Exception {
InputStream fileinpstream = new FileInputStream(filename);

byte[] buffer = new byte[1024];
MessageDigest md = MessageDigest.getInstance("MD5");
int numRead;
do {
numRead = fileinpstream.read(buffer);
if (numRead > 0) {
md.update(buffer, 0, numRead);
}
} while (numRead != -1);
fileinpstream.close();
return md.digest();
}
Read more...

 
Copyright 2011 Java Online