Showing posts with label Java Interview. Show all posts
Showing posts with label Java Interview. Show all posts

What are Generics in Java with example. How to improve type safety of your code?

In core java interview , question like "what are generics? and the advantages of using generics?" may be asked. This tutorial answers the above questions with example code.
Introduction of generics in the Java programming improves the type safety of your code also helps to reduce the runtime errors because it makes more of your bugs detectable at compile time. This powerful feature of Java introduced in the release of JDK 5 which allows a type or method to operate on objects of various types . To implement generics , special syntax is used . Generics also enhance the Java language with special syntax to iterate entities of Lists, Map,etc. Following code illustrates how coding mistake can happen without using generics and how to avoid it ? ArrayList can contain multiple data types like String , Integer and others. Before JDK 5, there was nothing in Java to restrict this behavior, which caused many coding mistakes.

import java.util.ArrayList;
public class generics
{
public static void main(String arg[])
{
List al= new ArrayList();
al.add("one");
al.add(2);  // no compile error occurs
al.add("three");
accessList(al);
}
private static void accessList(List al) {
   for (int k = 0; k < al.size(); k++) {
     String s =(String) al.get(k);  //  runtime error  "java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String "occurs when the integer value is accessed 
   System.out.println(s);
   }
} 

To ensure the assignment to a variable of type String is type safe, the type casting is required. Now the above code can be written using generics to avoid the runtime errors.

List<String> genericsAL = new ArrayList<String>();
genericsAL.add("one");
//genericsAL.add(2); // this line makes compile error 
genericsAL.add("three");
accessGenericsList(genericsAL);
}
private static void accessGenericsList(List<String> al) {
   for (int k = 0; k < al.size(); k++) {
     String s =al.get(k);      //  No type casting is required. 
   System.out.println(s);
   }
} 

List<String> genericsAL = new ArrayList<String>(); Generic used in the statement enforces to accept only Strings. The following statement gives compile time error.
List<Object> genericsO = genericsAL;
List<String> genericsAL = new ArrayList<String>() - List is a generic interface that takes a type parameter (in this case String) . The type declaration for the variable genericsAL specifies that this is a List of Strings, written List<String> and no type casting is required for the line String s =al.get(k)
iterate using generics
If you want to iterate the above List using generics , you can use the following statement. For iterating the list using generics , a special syntax is used
for (String s : al ) System.out.println(s);
Let us see the how to define a Simple Generics . The interfaces List, Collection and Iterator are defined in package java.util for using generics as follows

public interface List<E> extends Collection<E>{
    void add(E x);
    Iterator<E> iterator();
}
public interface Iterator<E>{
    E next();
    boolean hasNext();
}

The element within the angle brackets are the declarations of the formal type parameters of the interfaces List , Collection and Iterator .All occurrences of the formal type parameter are replaced by the actual type argument. In our example , E is replaced with String.
The following code snippet accepts any kind of collection as a parameter and prints the elements.

   void displayCollection(Collection c) {
    Iterator i = c.iterator();
    for (k = 0; k < c.size(); k++) {
        System.out.println(i.next());
    }
}

How to write the equivalent code for the above code using generics. We can't use Collection<Object> . Because it accepts only Object type. Use wildcard type to accept any kind of collection. i.e Collection<?> -(called as collection of unknown ) collection whose element type matches anything . The code snippet is as follows

 void displayCollection(Collection<?> c) {
    for (Object e : c) {
        System.out.println(e);
    }
}

For example of HashMap using generics , you can visit my earlier post , Traverse HashMap
Note : Just like type declarations, method declarations can be generic . This is called generic methods. We can see generic methods with example in the later post.

Read more...

How to Override Object.equals() method in Java . Writing own equals() method to compare two objects based on values with example code

This tutorial covers how to write own version of equals() method and importance of the method. Before going to this , let us see litle bit about Object class which has equals() and hashcode() method. Object class is the superclass of all Java classes. Every classes in java are inherited from this class by default that means all methods of the Object class are inherited automatically. So by default , the classes that we create will have the methods equals() , hashcode() , toString(), etc ...
This tutorial covers the default implementation of equals method and when and why we need to override equals method for our class?
In default implementation , two objects are equal only if they refer to the exact same object (i.e. reference / memory address equality) . The following code represents the default equals method
public boolean equals(Object obj) { return (this == obj); }

When to override Object.equals() method? Please go through the following code and the output.
    
class equalTest
{
public static void main(String arg[])
{
Employee emp1=new Employee(1561, "John", "Smith");
Employee emp2=new Employee(1561, "John" ,"Smith");
Employee emp3=emp1;
if (emp1.equals(emp2)) System.out.println("Both Employees(emp1 , emp2) are equal");
else System.out.println("Both Employees(emp1 , emp2) are not equal");

if (emp3.equals(emp1)) System.out.println("Both Employees(emp1 , emp3) are equal");
else System.out.println("Both Employees(emp1 , emp3) are not equal");

String name1="John Smith";
String name2="John Smith";

if (name1.equals(name2)) System.out.println("Both Names(name1 , name2) are equal");
else System.out.println("Both Names(name1 , name2) are not equal");

}
}

class Employee
{
int empCode;
private String firstName;
private String surname;

public Employee(int empCode, String firstName, String surname)
{
this.empCode=empCode;
this.firstName=firstName;
this.surname=surname;
}
}

Output :
D:\as2\JF4>java equalTest
Both Employees(emp1 , emp2) are not equal
Both Employees(emp1 , emp3) are equal
Both Names(name1 , name2) are equal

Before overriding , it is very important to keep in mind the distinction between equality and identity . In the above code , emp1 and emp2 has identical data i.e. employee code , first name and surname are equal for both objects . But the output is Both Employees(emp1 , emp2) are not equal . Because, by default the equals method of object checks whether the two reference variables(emp1 and emp2 ) refer to the same object . In the above code , both are different objects that is not identical . But emp1 and emp3 are identical . So the output is Both Employees(emp1 , emp3) are equal .
emp1 and emp2 objects are logically equal but not identical . In this situation , we have to override equals method sothat the it can also check the logical equality . But name1 and name2 are two different string objects . But the output is Both Names(name1 , name2) are equal . Because String class overrides the equals method to compare two string objects for equality based on the values and returns true if they hold the same characters in the same sequence.
Date class defines the equals method as follows . This is the value-based approach to equality (logical equality) . Both Date objects are equal if the getTime() method returns the same long value (milliseconds) for both
public boolean equals(Object obj) {
return obj instanceof Date && getTime() == ((Date) obj).getTime();
}

So when is it appropriate to override Object.equals? When a class requires logical equality ( i.e. two objects are equal if they have identical data)) that differs from object identity, and a superclass has not already overridden equals method to implement the desired behavior . This is generally applicable for value classes such as String , Integer and Date, etc . When we compare two objects using the equals method , we may expect to find out whether they are logically equivalent, not whether they refer to the same object. In this situation , we need to override equals method.
typesafe enum value class that does not require the equals method to be overridden . Because typesafe enum classes guarantee that at most one object exists with each value, Object’s equals method is equivalent to a logical equals method for such classes. When you override the equals method of java.lang.Object , you must adhere to its general contract which is given below
Let us say a, b and c are references of any objects . The equals method is
1. reflexive: a.equals(a) must return true i.e. any object must be equal to itself
2. symmetric: a.equals(b) must be true if b.equals(a) is true. i.e. if first object is equal to a second and the second object is equal to first
3. transitive: if a.equals(b) returns true and b.equals(c) returns true, then a.equals(c) must return true . i.e. if first object is equal to a second and the second object is equal to a third, then the first object must be equal to the third.
4. consistent: multiple invocations of a.equals(b) should return the same result (i.e. either always true or always false) unless any of the object's information is modified
5. Non-nullity : x.equals(null) must return false where x is non-null reference. i.e. all objects must be unequal to null. Allowing null value should not throw NullPointerException .
Note : It is better to check null i.e. if (o == null) return false;. But ,this test is not necessary as we include another test instanceof operator to check that its argument is of the correct type i.e. if (!(o instanceof MyType)) return false; This take takes care of the null check also . instanceof operator is specified to return false if its first operand is null . null objects will always fail instanceof.
equals() method will have the following condtions and statements in the following order and applicable for the above class Employee
public boolean equals(Object other) {
1. check other object refers the same object . use == operator . If so, return true
- if (other==this ) return true
2. check that its argument is of the correct type before type casting
- if (!(other instanceof Employee)) return false // takes care of null check also .
3. type cast the argument to an appropriate type to access its fields
- Employee emp = (Employee) other
4. check to see if the fields (relevent to logical equality) of the argument matches the corresponding fields of this object . If all checks succeed, return true. For primitive fields (except float or double) , use the == operator for comparisons; for object reference fields, invoke the equals method recursively .To avoid NullPointerException, when the fields contain null values , please include null check as given below.
- return empCode == emp.empCode && (firstName == emp.firstName || (firstName != null && firstName.equals(emp.firstName) ))&& (surname == emp.surname || (surname != null && surname.equals (emp.surname)))

}
Note : instanceof is most suitable for immutable class or final class which can not be extended . As instanceof returns true for subclass also , we can use getCalss() method for type check as given below
if((other == null) || (other.getClass() != this.getClass())) return false . null check also required.

Aoid common mistakes when overriding
1. You must override hashCode in every class that overrides equals. If not , it will result in a violation of the general contract for Object.hashCode, which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable. For overriding hashCode() method , please gothrough my earlier tutorial Why and When to override Object.hashCode() method?
2. Don’t use any other type other than Object as argument in the equals method declaration .
Wrong : public boolean equals(Employee o) {... } - this method does not override Object.equals() , but overloads it instead. Object.equals accepts only the argument of type Object ,
Correct : public boolean equals(Object o) {... }

The above Employee class with equals() and hashCode() method is given below. The equals() method of Object class is overrided in the code to compare objects based on values.
    
class equalOverride
{
public static void main(String arg[])
{
Employee emp1=new Employee(1561, "John", "Smith");
Employee emp2=new Employee(1561, "John" ,"Smith");
Employee emp3=emp1;
if (emp1.equals(emp2)) System.out.println("Both Employees(emp1 , emp2) are equal");
else System.out.println("Both Employees(emp1 , emp2) are not equal");
if (emp3.equals(emp1)) System.out.println("Both Employees(emp1 , emp3) are equal");
else System.out.println("Both Employees(emp1 , emp3) are not equal");
String name1="John Paul";
String name2="John Paul";
if (name1.equals(name2)) System.out.println("Both Names(name1 , name2) are equal");
else System.out.println("Both Names(name1 , name2) are not equal");
}
}

class Employee
{
int empCode;
private String firstName;
private String surname;

public Employee(int empCode, String firstName, String surname)
{
this.empCode=empCode;
this.firstName=firstName;
this.surname=surname;
}
public boolean equals(Object other) {
if (other==this ) return true;
if (!(other instanceof Employee)) return false;
Employee emp = (Employee) other;
return empCode == emp.empCode && (firstName == emp.firstName || (firstName != null && firstName.equals(emp.firstName) ))&& (surname == emp.surname || (surname != null && surname.equals (emp.surname))) ;
}

public int hashCode() {
int hash = 17;
hash = hash * 19 + empCode;
hash = hash * 31 + firstName.hashCode();
hash = hash * 13 + (surname == null ? 0 : surname.hashCode());
return hash;
}
}



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...

String Vs String Buffer . Difference between String & StringBuffer class example

Java String object is immutable that means the content of the String Object contents cannot be modified after they are created . There are no methods available to manipulate the contents of the string once it is created. Methods that operate on a string returns a new string rather than manipulating the original copy of the string. String concatenation is done using "+" operator which creates many temporary objects and increases garbage collection . So String concatenation using "+" may be avoided.
The StringBuffer class represents a mutable string of characters that means their values can be changed after they are created. There are methods like append , insert are available which allows to manipulate the contents of the string once it is created . String concatenation is done using append method which avoids creating many temporary strings. So it is better to use the Java StringBuffer object to concatenate strings because it is more efficient.
Note : Both String and String buffers are safe for use by multiple threads because the operations on string will create a new string and String buffer methods are synchronized . Every string buffer has a initial capacity. If the internal buffer used by the string buffer overflows, it is automatically made larger.
String buffer / StringBuilder are used by the compiler to implement the binary string concatenation operator +. StringBuilder is similar to StringBuffer except String bulider is not synchronised. For example, the code:
input = "StringConcatenation is done using " + "StringBuffer.append " +4 + " u" is compiled to the equivalent to the following line.
input = new StringBuffer().append("StringConcatenation is done using ").append("StringBuffer.append ").append(4).append(" u").toString()
   
class StringCat
{
public static void main(String...args)
{
String input = "StringConcatenation is done using " + "StringBuffer.append " +4 + " u"
System.out.println("Output= "+ input);
}
}

Compile the above program using javac StringCat.java and Run the using javap -c StringCat which will display the bytecode of the StringCat.class as follows.
   
Compiled from "StringBuffer.java"
class StringBuffer extends java.lang.Object{
StringBuffer();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return

public static void main(java.lang.String[]);
Code:
0: ldc #2; //String StringConcatenation is done using StringBuffer.append 4 u
2: astore_1
3: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
6: new #4; //class java/lang/StringBuilder
9: dup
10: invokespecial #5; //Method java/lang/StringBuilder."<init>":()V
13: ldc #6; //String Output=
15: invokevirtual #7; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
18: aload_1
19: invokevirtual #7; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
22: invokevirtual #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
25: invokevirtual #9; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
28: return

}


Read more...

How to Sort HashMap by Values . Write Own Compare Method in Java Example

We can sort the Hashmap by putting all values in a TreeMap . By default TreeMap is sorted by Keys. To sort it by values , we have to write own compare method of comparator interface. The compare method compares its two arguments . By default two arguments are objects which is having key of Map. If both arguments are equal then it returns 0 . If first argument is less than the second argument , returns a negative integer, If first argument is greater than the second argument , returns a Positive integer. Now we have to sort by values. So we have to get the values using key i.e map.get(key) . Now we have to write our own logic to compare the values . The return value will be 0 or 1 or -1 . If more than one elements are equal it adds only the first value. If both arguments are equal means it returns 0 that means Hashmap is having duplicate values. As HashMap does not allow duplicate values ,to allow duplicate values , we have to return other than 0 value. In our example , when both values are equal , we compare both keys rather than values , thus returns other than 0. The following program is compatible for sorting of strings and also positive numbers. Negative numbers are sorted properly because we are using String.compareTo to compare two values. So it is always better to pass same type of values and change the compareTo logic accordingly. For example if all the values are integer means , the logic will be Integer e1 = (Integer)thisMapValues.get(o1); Integer e2 = (Integer) thisMapValues.get(o2); if (e1==e2) return return String.valueOf(o1).compareTo(String.valueOf(o2)) ; else if (e1<e2) return -1 ; else return 1;

import java.util.*;
public class HashMapSortValue{
private static class OwnCompare implements Comparator
{
private Map thisMapValues = null;
public OwnCompare (Map mapValues)
{
super();
thisMapValues = mapValues;
}

public int compare(Object o1, Object o2)
{
String e1 = String.valueOf(thisMapValues.get(o1));
String e2 = String.valueOf( thisMapValues.get(o2));
if (e1.compareTo(e2)==0) return String.valueOf(o1).compareTo(String.valueOf(o2)); else return e1.compareTo(e2);

}
}

public static void main(String[] args) {
Map hm = new HashMap();
hm.put ("Employee1", 60000);
hm.put ("Employee2", 50000);
hm.put ("Employee2", "absent");
hm.put ("Employee3", 25000);
hm.put ("Employee4","retired");
hm.put ("Employee5","absent");
hm.put ("Employee6",20000);
hm.put ("Employee7",20000);
hm.put ("Employee8",50000);
hm.put ("Employee9",60000);
System.out.println("List Before Sorting : " + hm);
SortedMap sortedByValue = new TreeMap(new HashMapSortValue.OwnCompare(hm));
sortedByValue.putAll(hm);
System.out.println("List After Sorting by Value " +sortedByValue);
}
}


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...

Java Autoboxing / Unboxing with Example code

In older versions of java , int (or any other primitive value) are not accepted by a collection. Consider the following code for converting array to ArrayList which gives the compile error due to Collection accepts object references not primitive int values. The solution for this error is to box primitive values into the appropriate wrapper class . In this case we have to convert int to Integer wrapper class . Now replace the line lst.add(numbers[i]); with lst.add(new Integer(numbers[i])); here we have converted int to Integer wrapper class.



import java.util.*;
class listExample
{
public static void main(String args[])
{
List lst = new ArrayList();
int numbers[] ={10,30, 55, 65,33};
for (int i=0;i<5;i++)
{
lst.add(numbers[i]); // Error listExample.java:13: cannot resolve symbol , symbol : method add (int) , location: interface java.util.List . Solution : Replace lst.add(numbers[i]); with lst.add(new Integer(numbers[i]));
System.out.println(numbers[i]);
}
}
}

When we need an int, we have to unbox the Integer using the intValue method . Consider the following lines of code , where add method accepts two Object references (Not a primitive value) , when we compile the code in older version of java , it throws error , because we are adding two objects reference and assigning to a primitive int variable. . Replacing the int d=a+b; with int d=a.intValue()+b.intValue(); will solve the problem.


class Addition
{
public static void main(String args[])
{
Integer k=new Integer(123);
Integer k1=new Integer(1523);
add (k, k1);

}
public static void add( Integer a , Integer b )
{
int d=a+b; // using unbox
System.out.println("Addition = " + d );

}
}

The following example illustrates autoboxing and unboxing . In the main function , we have declared 4 variables a, b , c, d . a & b are primitive type variables. c & d are Integer class variables. Now in our code , we have assigned primitive type int value to Integer c & Integer d . In older version , the this line gives compile error. But in java 1.5 , it does not give any error due to autoboxing . The autoBoxUnbox( Integer a , Integer b ) accepts two object reference. So when we call autoBoxUnbox(a,b) where a , b are int values , in java 1.5 no error is coming due to autoboxing. In the autoBoxUnbox method , the line int d=a+b; d is an int variable. but a & b are Integer variable. Here a & b are converted to int variable by unboxing in java1.5 , In java 1.4 we have to use Integer.intValue() to convert Integer to int.


import java.util.*;
class autoBoxUnbox
{
public static void main (String args[])
{
int a = 100;
int b = 100;
Integer c=300;
Integer d=300;
autoBoxUnbox(a,b);
autoBoxUnbox(c,d);
}

public static void autoBoxUnbox( Integer a , Integer b ) // using autoboxing
{
Integer c=a+b;
int d=a+b; // using unboxing
System.out.println("Given Numbers " + a + " , " + b);
System.out.println("Addition = " + c );
System.out.println("Addition using unbox= " + d );
System.out.println(" ");
}
}


Output :

D:\as2\JF2>java autoBoxUnbox
Given Numbers 100 , 100
Addition = 200
Addition using unbox= 200

Given Numbers 300 , 300
Addition = 600
Addition using unbox= 600
Read more...

int Vs Integer in Java Example ,Difference between Integer Wrapper & int primitive

int is a primitive data type . It is a 32-bit signed two's complement integer which can have a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). Integer is a wrapper class for int. The constuctor for Integer class is Integer(int num / String str) . So Integer class wraps a primitive type int value in an object. An object of Integer class contains a single field whose type is int .
An int stores a number where as Integer points a reference of an object that contains a number .Integer class is an example of immutable object which represents a single value that cannot change over the lifetime of the object.

We may use Integer rather than a primitive due to some of the below mentioned reasons.
1. Some Methods of a class (for example methods of collection class like List , Map, etc can hold object references) accept only object reference (not primitive value) as an argument . 2. Integer class has many methods & constants which can be used in many ways . For example Constants of the Integer class, such as MIN_VALUE & MAX_VALUE, SIZE which is used to define the lower , upper value & number of bits to represent an int value and Methods of Integer Class su as parseInt , toString() are useful when dealing with an int.

Converting an Integer to int vice versa is very easy .
To convert to Integer from int. // box
int number =100;
Integer numWrap=new Integer(number);

//To convert to int from Integer // unbox
Integer numWrap1=new Integer(200);
int num =numWrap1.intValue();

If you use java 1.4 , then you have to manually box , unbox using the above commands.

The following example code will be compiled with java version 1.5 and above .No need to box manually. In Java 1.5 , new feauture autoboxing , unbox is introduced .

 

class intVsInteger
{
public static void main(String[] args)
{
int num1 = 100;
int num2 = 100;
int num3 = 160;
int num4 = 160;
Integer num5=300; // by autoboxing available from jdk 1.5
Integer num6=300; // by autoboxing
int num7=num5+num6; // by autoboxing

System.out.println( "num1= "+num1 );
System.out.println("num2= "+num2 );
System.out.println("num1==num2 " + ( num1==num2) );
System.out.println( "num3= "+num3 );
System.out.println("num4= "+num4 );
System.out.println("num3==num4 " + (num3==num4) );
System.out.println( "num5= "+num5 );
System.out.println("num6= "+num6 );
System.out.println("num5==num6 " + (num5==num6) );
System.out.println("Below value using Integer class");
intVsInteger(num1,num2);
intVsInteger(num3,num4);
intVsInteger(num5,num6);
}

public static void intVsInteger( Integer a , Integer b ) // using autoboxing
{
System.out.println( "a= "+a );
System.out.println("b= "+b );
Integer c=a+b;
int d=a+b; // using unbox
System.out.println("c= " + c );
System.out.println(a==b );

}
}


Output of the program

D:\as2\JF2>java intVsInteger
num1= 100
num2= 100
num1==num2 true
num3= 160
num4= 160
num3==num4 true
num5= 300
num6= 300
num5==num6 false
Below value using Integer class
a= 100
b= 100
c= 200
true
a= 160
b= 160
c= 320
false
a= 300
b= 300
c= 600
false

The intVsInteger method accepts Integer object . So the object reference is passed to the method not the value. if both are pointing to the same reference of the object , then the output will be true otherwise the output will be false.When using primitive type , if both values are equal means , num1=num2 will be true.


Read more...

Formating date in Current / any Locale in Java with Style Example code

DateFormat helps to format and parse dates for any locale . DateFormat has many methods for obtaining default date / time formatters based on the default or a given locale and a number of formatting styles. The formatting styles include SHORT (23/07/11 ) , MEDIUM ( Jul 23, 2011 ), LONG (July 23, 2011 ) , FULL (Saturday, 23 July 2011 ). DateFormat has a method getDateInstance() which is used to get the normal date format for that country

To format a date in the current Locale,

dateFormatStr = DateFormat.getDateInstance().format(myDate);

To format a date for a different Locale, specify it in the call to getDateInstance().

DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.UK);

The following code formats the current date into various different locales with different styles (SHORT, MEDIUM, LONG, FULL)

  

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

public class DateFormatLocale

{
public static void main(String args[])
{
Date today = new Date();

Locale[] locales ={Locale.CHINA, Locale.UK, Locale.GERMANY, Locale.FRANCE, Locale.US };
int[] fmt_styles={ DateFormat.SHORT,DateFormat.MEDIUM,DateFormat.LONG, DateFormat.FULL};
DateFormat format;
String[] fmt_style_str={ "SHORT", "MEDIUM", "LONG", "FULL"};
for (int i=0; i<locales.length;i++)
{
System.out.println("\n The date format for the country " + locales[i].getDisplayCountry() );
for (int j=0; j<fmt_styles.length;j++)
{
format = DateFormat.getDateInstance(fmt_styles[j], locales[i]);
System.out.println("\n " + fmt_style_str[j] + " is " + format.format(today));

}
}

String dateCurrentLocale = DateFormat.getDateInstance().format(today);

System.out.println("Date format for the current locale " + dateCurrentLocale);

}
}

Output of the Program:

java DateFormatLocale

The date format for the country China

SHORT is 7/23/11

MEDIUM is Jul 23, 2011

LONG is July 23, 2011

FULL is Saturday, July 23, 2011

The date format for the country United Kingd

SHORT is 23/07/11

MEDIUM is 23-Jul-2011

LONG is 23 July 2011

FULL is Saturday, 23 July 2011

The date format for the country Germany

SHORT is 23.07.11

MEDIUM is 23.07.2011

LONG is 23. Juli 2011

FULL is Samstag, 23. Juli 2011
....
......


Read more...

Convert Charater Arrays to String in Java | Example code using String.copyValueOf()

You can convert character arrays to string in two ways .
1. String Class has a method copyValueOf() can be used to create a String object from charater arrays. (i.e. array of type char[])
a) String str=String.copyValueOf(charArray) -> All the characters of array is converted to String
b) String str = String.copyValueOf(charArray, 5, 4) - > Only 4 charactes starting from 5th position , are converted to string.

2. String class supports several constructors . One of the constructor accepts array of characters and string object is created by the initialised array of charaters. String str=new String ('a','e','i','o','u');

The following example code explains how the character arrays are converted to string object using the above two methods.

  

public class CharArrayToString {

public static void main(String[] arg) {
char[] charArray = { 'V', 'o', 'w', 'e', 'l', 's', ':', 'a', 'e', 'i', 'o', 'u' };

System.out.println("Given CharArray\n");
for (char c:charArray) System.out.println(c);

String str = new String(charArray);
System.out.println("After converting to String using Constructor : " + str);

String str1 = String.copyValueOf (charArray);

System.out.println("After converting to String using copyValueOf method : " + str1);

// converting subset of charater arrays to string
System.out.println("\n");
System.out.println("Converting subset of charater arrays to string\n ") ;
String str2 = new String(charArray,0,5);
System.out.println("Using Constructor : " + str2);

String str3 = String.copyValueOf (charArray,7,5);

System.out.println("Using copyValueOf method : " + str3);

}

}

After Running the above program Output :

java CharArrayToString
Given CharArray

V
o
w
e
l
s
:
a
e
i
o
u
After converting to String using Constructor : Vowels:aeiou
After converting to String using copyValueOf method : Vowels:aeiou


Converting subset of charater arrays to string

Using Constructor : Vowel
Using copyValueOf method : aeiou


Read more...

array to ArrayList in Java with Example | Convert arrays to ArrayList in Java

There may be some situation where arrays needs to be converted to ArrayList . arrays are fixed length. After arrays are created , they cannot grow or shrink . So it is better to use ArrayList where you don't know how many elements the array will hold. Moreover arrays can have only similar data type elements . Arraylist is a collection which can have different data type objects. ArrayList size can increase or decrease dynamically.
There are lot more ways to convert array to ArrayList .

1. Using Arrays.asList(array)
2. Add all array values to the ArrayList using ArrayList.add (value)
3. Using Collections.addAll( ArrayList, array) */



import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class ArrayToAL
{
public static void main(String[] args)
{
String[] languages = {"Java", "C", "C++", "Pascal", "Basic"};

method1(languages);
method2(languages);
method3(languages);

}


private static void method1(String[] array)
{

List languageList = Arrays.asList(array); //asList(array)
System.out.println("Using Method1\n");
for (String l : languageList) System.out.print(l+"\t");
System.out.println("\n");

}


private static void method2(String[] array)
{

ArrayList languageList = new ArrayList();

for (String a : array) languageList.add(a); // ArrayList.add(value)
System.out.println("Using Method2\n");

for (Object l : languageList) System.out.print(l+"\t");
System.out.println("\n");
}


private static void method3(String[] array)
{

ArrayList languageList = new ArrayList();
Collections.addAll( languageList ,array); // Collections.addAll( ArrayList, array)
System.out.println("Using Method3\n");
for (Object l : languageList) System.out.print(l+"\t");

}

}


After Running the program , the following output will be displayed

java ArrayToAL
Using Method1

Java C C++ Pascal Basic

Using Method2

Java C C++ Pascal Basic

Using Method3

Java C C++ Pascal Basic


Read more...

Java String to Character Array Example Code | How to copy chars from string to char Array

In several ways, we can copy the charaters of a string object into an character array. (ie. converting the string to an array of characters.) Using the following String methods we can convert the string to an array of characters
charAt(i);
toCharArray();
getChars(int srcBegin, int srcEnd, char[] dest, int destBegin) .

The following code illustrates how to convert String to array of charaters using above 3 methods.*/


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

String inputString = "Techlabs4u.com";
int len = inputString.length();
char[] charArray1 = new char[len];
char[] charArray3 = new char[len];
// Converting using String to array of chars using charAt(i);
for (int i = 0; i < len; i++) {
charArray1[i] = inputString.charAt(i);
}

// Converting String to array of chars using toCharArray();

char[] charArray2=inputString.toCharArray();

// Converting String to array of chars using getChars();

inputString.getChars( 0, len, charArray3, 0) ;

System.out.println("From charArray1\n");
for (char c:charArray1) System.out.println(c);

System.out.println("From charArray2\n");
for (char c:charArray2) System.out.println(c);

System.out.println("From charArray3\n");
for (char c:charArray3) System.out.println(c);

}
}



Running the above program will output the following

java StringToChrArray
From charArray1

T
e
c
h
l
a
b
s
4
u
.
c
o
m
From charArray2

T
e
c
h
l
a
b
s
4
u
.
c
o
m
From charArray3

T
e
c
h
l
a
b
s
4
u
.
c
o
m
Read more...

String Split in Java using Pattern.split() Example Code using Regular Expression (util.regex)

The following program splits the given string using the split method of Pattern Calss of the package java.util.regex available with JDK 1.4 onwards. An instance of the Pattern class represents a regular expression which is specified in string . Pattern Class has various methods . Some of the methods are as follows.

1. compile(String regex) -> Compiles the given regular expression into a pattern.
2. split(CharSequence input) -> Splits the given string using the pattern.
3. matches(String regex, CharSequence input) -> Compiles the given regular expression (regex) and Matches the given input string against it.

The following Program splits the given input string by the delimiter # , white space and commas

   

import java.util.regex.*;
import java.util.Scanner;
public class SplitByRegex {
public static void main(String[] args) throws Exception {

Pattern pattern = Pattern.compile("[#,\\s]+"); // created pattern using # comma whitespace

Scanner sc=new Scanner(System.in).useDelimiter("\n"); //Accepts Line of String
System.out.println("Enter Line to Split "); //
String inputStr=sc.next();
System.out.println("Enterd Line : " + inputStr + "\n");
String[] resultStr = pattern.split(inputStr);
System.out.println("\nResult Strings after Split\n");
for (int i=0; i<resultStr.length; i++)
System.out.println((i+1) +"." + resultStr[i]);
}
}

Running the Program :

D:\as2\JF1>java SplitByRegex
Enter Line to Split
Mumbai # Calcutta # Chennai # Delhi , US, Washinton , Canada Singapore Malasia
India
Enterd Line : Mumbai # Calcutta # Chennai # Delhi , US, Washinton , Canada Sing
apore Malasia India


Result Strings after Split

1.Mumbai
2.Calcutta
3.Chennai
4.Delhi
5.US
6.Washinton
7.Canada
8.Singapore
9.Malasia
10.India


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...

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...

Java Number to String Example , Integer to String in Java


/*Converting a number to string can be done very eaisly in java .We can do in many ways .

1. We can use toString() method of Integer , Byte , Long class . The Integer and Long classes also provide the methods like toBinaryString(), toHexString(), toOctalString();
2. String.valueOf can be used to convert number to string.
3. java.text.DecimalFormat is used to parse and format numbers in any locale
4. Simple Concatenation (+) : Any integer concatenated with string is converted to string . */




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

Example1();
Example2();
}

// Example 1:

private static void Example1()
{

System.out.println("Example 1 ");

int number = 1932;

System.out.println ("Given Number is : " + number); // using concatenation

System.out.println(" Number to String by toString(): " + Integer.toString(number)); // using toString of Integer

System.out.println(" Number to String by valueOf(): " + String.valueOf(number)); // using valueOf of String

System.out.println(" Number to Binary : " + Integer.toBinaryString(number));

System.out.println(" Number to Hexadecimal : " + Integer.toHexString(number));

System.out.println(" Number to Octal : " + Integer.toOctalString(number));

}

// Example 2:

private static void Example2()
{

System.out.println("Example 1 ");
DecimalFormat df= new DecimalFormat("##,###.##");

int number = 400;

String str1="" + number ; //using concatenation

String str2 = "Number is "+number; //using concatenation

double decimal = 65132.39 ;

String numInFormat = df.format(decimal);

System.out.println("String1 = " +str1);
System.out.println("String2 = " +str2);
System.out.println("Number in Format = " +numInFormat);
}

}



Output :
-----------
D:\as2\JF1>java NumberToStr
Example 1
Given Number is : 1932
Number to String by toString(): 1932
Number to String by valueOf(): 1932
Number to Binary : 11110001100
Number to Hexadecimal : 78c
Number to Octal : 3614
Example 1
String1 = 400
String2 = Number is 400
Number in Format = 65,132.39
Read more...

Java String to Integer Example . Use of Integer.ValueOf(), parseInt()

/* Many times , We may come accross a situation where a string needs to be changed to an Integer . For example when we accept a input through keyboard , it will be read as String . For doing any calculation , we have to convert the string to an integer . Integer Object has methos like valueOf & parseInt for converting sting to integer.
We can convert String to Integer using the following ways

Integer.valueOf - converts String to Integer Object
Integer.parseInt - converts String to int primitive type
If we pass a string to the constructor of the Integer object , it returns Integer Object. */



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

Example1();
Example2();
}

// Example 1:

private static void Example1()
{

System.out.println("Example 1 ");
String numStr ="110";
Integer number = new Integer(numStr);

String numStr1="0005";
int number1 = Integer.valueOf(numStr1);

String numStr2="0007";
int number2=Integer.parseInt(numStr2); //converts to integer primitive type.

System.out.println( "Number String is ( string concatenation)" + numStr+numStr2+numStr2);

int result=number+number1+number2;
Integer result1=number+number1+number2;

System.out.println("Input Numer" + number);
System.out.println("Input Numer1" + number1);
System.out.println("Input Numer2" + number2);

System.out.println( "After Converting Integer ( string concatenation) " + number+number1+number2);
System.out.println( "result " + result);
System.out.println( "result1 " + result1);

}

// Example 2:

private static void Example2()
{

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

String numStr="";
int number=0;
int sum=0;

System.out.println("Example 2 ");
System.out.println("Enter Numbers to add & type quit to exit ");

do
{

try
{
numStr=br.readLine();
number = Integer.parseInt(numStr);
}
catch (Exception e)
{
if (numStr.equalsIgnoreCase("quit") )
{
System.out.println("Quiting....");
number=0;
}
else
{
System.out.println("Invalid Input");
number=0;
}
}
sum = sum + number;
} while (numStr.compareTo("quit") !=0);

System.out.println("Sum is =" +sum);
}

}



Output :
--------

D:\as2\JF1>java StringToInt
Example 1
Number String is ( string concatenation)11000070007
Input Numer110
Input Numer15
Input Numer27
After Converting Integer ( string concatenation) 11057
result 122
result1 122
Example 2
Enter Numbers to add & type quit to exit
7
5
3
7
2
quit
Quiting....
Sum is =24
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...

Scanner in Java with Example. How to read input from Key Board & File using java.util.Scanner Class?

Scanner in Java :
The Scanner class in java.util (java.util.Scanner) can read input from Keyboard (System.in) or Files and parse primitive types and strings using regular expressions. Scanner breaks its input text into tokens using a delimiter . By default, a scanner uses white space to separate tokens. The resulting tokens can be converted into values of different types using the various next methods.
I have exaplained with various examples , how to read input from System.in , File

Example 1 : The following code allows a user to read a number from System.in and calculates Surface Area and Perimeter of a Rectangle




import java.util.*;

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

System.out.print("Enter base (in cm): ");
double b = scanner.nextDouble();

System.out.print("Enter height (in cm): ");
double h = scanner.nextDouble();

double area=b*h*1/2;
System.out.println("Area of Triangle =" +area);
}
}


Running the Above Prgram

Output :

D:\as2\j2eeforum>java AreaRectangle
Enter Breadth 50
Enter Height 20
Area of Rectangle = 1000.0
Perimeter of Rectangle = 140.0

Example 2 : The fllowing code allows to read lines from a file "AreaRectangle.java" and prints the contents of Java file line by line..





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

public class FileRead
{
public static void main(String []args){
try {
Scanner fr = new Scanner(new File("d:\\as2\\AreaRectangle.java"));
fr.useDelimiter (System.getProperty("line.separator"));

while (fr.hasNext()) {
System.out.println(fr.next());
}
fr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

}
}


Running the above program will print all lines of the "AreaRectangle.java" one by one.
Read more...

 
Copyright 2011 Java Online