Sunday, 21 April 2013

Vector and ArrayList

In this tutorial we will see about Vector and ArrayList in java. Both Vector and ArrayList shares common data structure "Array" internally.

Synchronized and non-synchronized
By default Vector is Synchronized and ArrayList is not Synchronized. By this for Thread safe we can use Vector and for non-thread safe we can use ArrayList. Even ArrayList can be converted to synchronized by Collections class using "Collections.synchronizedList(list)"

Vector in Collection API
Vector defined in first JDK version and later from Java 2 platform Vector got added with Java Collection API. Vector has been retrofitted to implement List Interface.
Once Vector added in Collection API, older methods in Vector class got updated to implement List Interface. Below are the methods got updated from Older version to new methods.

Old Vector MethodsNew Vector Methods
void addElement(Object)boolean add(Object)
boolean removeElement(Object)boolean remove(Object)
void removeElementAt(int)void remove(int)
void insertElementAt(Object, int)void add(index, Object)
Object elementAt(int)Object get(int)
Enumeration elements()Iterator iterator()
ListIterator listIterator()
void copyInto(Object[])Object[] toArray()
void removeAllElements()void clear()
void setElementAt(int)Object set(int, Object)

Where to use Vector and ArrayList
By performance wise ArrayList will be better in case of non synchronized operations and when we need for thread-safe operation then we need to opt for Vector.

Both Vector and ArrayList will re-size dynamically. Vector will double the size of its array automatically when its full, where as ArrayList will increase by half of its array size.

read more.. "Vector and ArrayList"

Monday, 15 April 2013

How to read local and remote file in Java?

In our earlier tutorial we have seen list of various file operations. In this tutorial we will see how to read a file from local path and from remote server. Reading files from local and from other server through HTTP will vary. Lets see both examples separately.

Reading from local path:


public class ReadFile {
 public static void main(String[] args) {
  String fName = "/var/javadiscover/test.txt";
  BufferedReader br = null;
  try {
   FileReader myFile = new FileReader(fName);
   br = new BufferedReader(myFile);
   String line = null;
   while ((line = br.readLine()) != null) {
  } catch (IOException e) {
  } finally {
   if (br != null){
    try {
    } catch (IOException e) {

Reading from remote server through HTTP:


public class ReadFile {
 public static void main(String[] args) {
  InputStreamReader isr  = null;
  BufferedReader buffRead = null;
   String fName = "http://mydomain/test.txt";
   URL url  = new URL(fName);
   URLConnection conn  = url.openConnection();
   isr   = new InputStreamReader(conn.getInputStream());
   buffRead  = new BufferedReader(isr);
   String str = "";
   while ((str = buffRead.readLine()) != null) {
  } catch (FileNotFoundException e) {
  } catch (IOException e) {
  } finally{
    if(buffRead != null) buffRead.close();
    if(isr != null) isr.close();
   }catch (IOException e) {

read more.. "How to read local and remote file in Java?"

Friday, 12 April 2013

Sending email using Java Mail API

In this tutorial we will see how to send email using Java Mail API. We are using Gmail SMTP host for sending email in the below sample code.
Mainly we need 2 jar files to implement Java Mail API. Those jar's are

  • activation-1.0.2.jar
  • mail-1.4.1.jar

Below code have tested along with above jar files. 

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailViaGmail {
 public static void main(String[] args) {
  // To address
  String to = "";
  // If any CC email ids
  String cc = "";
  // If any BCC email ids
  String bcc = "";
  // Email Subject
  String subject = "Java Discover";
  // Email content
  String emailText = "Hi All, Welcome to Java Discover";

  // Sending Email using Gmail SMTP
  sendEmail(to, cc, bcc, subject, emailText);

 public static void sendEmail(String to, String cc, String bcc, String subject, String emailText) {
  // From address (Need Gmail ID)
  String from = "";
  // Password of from address
  String password = "frompassword";
  // Gmail host address
  String host = "";
  Properties props = System.getProperties();
  props.put("", host);
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class", "");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");
  props.put("mail.smtp.user", from);
  props.put("password", password);

  Session session = Session.getDefaultInstance(props, null);

  MimeMessage msg = new MimeMessage(session);
  try {
   msg.setFrom(new InternetAddress(from));
   // Adding To address
   msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
   // Adding CC email id
   msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
   // Adding BCC email id
   msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

   Transport transport = session.getTransport("smtp");
   transport.connect(host, from, password);
   transport.sendMessage(msg, msg.getAllRecipients());
   System.out.println("Email sent successfully.....");
  } catch (AddressException e) {
  } catch (MessagingException e) {

Suppose if you are getting exception while running above like, PKIX path building failed: unable to find valid certification path to requested target

then valid SSL certificate is missing in the machine which your running. Follow the steps given in link and try again. 

read more.. "Sending email using Java Mail API"

Variable arity method in Java

In this tutorial we will see about Variable Arity method in Java. Variable Arity method question is bit old interview question which used widely before JDK 5. But good to know about this feature in Java and also in Java 7 we have got an update with @SafeVarargs

Its nothing but passing an arbitrary set of arguments to a method. Method can have N no. of arguments but the condition that we can't pass arguments after Arity member. Arity member variable should be always last in the method and it can be primitive or non-primitive data type. Below are the few valid and invalid Variable Arity method definition in Java.


public void myMethod(int... arg){....}

public void myMethod(String... arg){....}

public void myMethod(Object... arg){....}

public void myMethod(int a, int b, int... arg){....}


public void myMethod(int... arg, int a){....}

Lets see small sample code how to pass values to Variable Arity method and how to print those values. 

public class ArityMethod {

 public static void myMethod1(int... arg){
  System.out.print("\nmyMethod1 : ");
  for (int i : arg) {
   System.out.print(i+", ");
 public static void myMethod2(String... arg){
  System.out.print("\nmyMethod2 : ");
  for (String str : arg) {
   System.out.print(str +" ");
 public static void myMethod3(int a, float b, Object... arg){
  System.out.print("\nmyMethod3 a value : "+a);
  System.out.print("\nmyMethod3 b value : "+b);
  System.out.print("\nmyMethod3 : ");
  for (Object str : arg) {
   System.out.print(str.toString() +" ");
 public static void main(String[] args) {
  myMethod2("hello", "welcome", "to", "Java Discover");
  myMethod3(100,3.0f, "hello", "welcome", "to", "Java Discover");


myMethod1 : 1, 2, 3, 4, 5, 

myMethod2 : hello welcome to Java Discover 

myMethod3 a value : 100
myMethod3 b value : 3.0
myMethod3 : hello welcome to Java Discover 

read more.. "Variable arity method in Java"

Thursday, 11 April 2013

How to create user defined immutable class in Java?

In this tutorial we will discuss about how to create immutable class in Java. When we say about immutable we will be remembered about important interview question like What is the difference between String and StringBuilder? We are familiar with String is a immutable and StringBuilder is mutable where values once assigned to String variable cannot the changed. 

Yes correct same way this is also interview question as how to create user defined immutable class in Java? Its simple just by Final modifier we can create our own immutable class. For this we need to make class, methods and member variable in the class as Final. By changing the modifier as final one cannot extend the class or override the methods and even cannot change the value once assigned to member variables. By this we can implement our own immutable class.

In below example code will show how to immutable class in Java.

public final class MyImmutableClass {
 private final String empName;
 public MyImmutableClass(String empName) {
  this.empName = empName;
 public String getEmpName(){
  return this.empName;

public class TestMyImmutable {
 public static void main(String[] args) {
  MyImmutableClass obj = new MyImmutableClass("Raj");
   * Values once assigned cannot to changed by using set methods.
   * Just we can get the value assigned to the variable.
  String empName = obj.getEmpName();
  System.out.println("Emp Name : "+empName);  

read more.. "How to create user defined immutable class in Java?"

Sunday, 7 April 2013

TreeMap using custom object sorting

We know that by default TreeMap will sort the values using key. Suppose if we need to sort the TreeMap using object stored in key part then we need to implement the Comparator interface and we need to @Override compare() method which will sort 2 Objects of key path and will give us the sorted output. 

Below single example will show you how to use custom Object sorting in TreeMap. TreeMap will take "Worker class instance" as key and "String name" as value. Where we need to sort the values using key based on the member variables in the Worker class. 

Class "MyNameComp" which implements the Comparator interface on "Worker" class and used to sort TreeMap based on name or salary. Below example will gives you sort on salary. Suppose if we need output based on name sorted then we need to un-comment "return obj1.getName().compareTo(obj2.getName());"

public class TreeMapUsingObjectSorting {
 public static void main(String a[]){
  TreeMap<Worker,String> map = new TreeMap<Worker, String>(new MyNameComp());
  map.put(new Worker("david",5000), "david");
  map.put(new Worker("joy",2000), "joy");
  map.put(new Worker("abel",7000), "abel");
  map.put(new Worker("ruby",9000), "ruby");
  for (Map.Entry<Worker, String> entry : map.entrySet()) {
   System.out.println("KEY : "+ entry.getKey() +" \t VALUE : "+entry.getValue());

public class Worker{
    private String name;
    private int salary;
    public Worker(String name, int salary){ = name;
        this.salary = salary;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public int getSalary() {
        return salary;
    public void setSalary(int salary) {
        this.salary = salary;
    /* Called by entry.getKey() 
       Overriding toString() method from super class Object
       Since key is Object we are return our own key value
    public String toString(){
     //return super.toString();
     return "("":"+this.salary+")";

public class MyNameComp implements Comparator<Worker>{

 public int compare(Worker obj1, Worker obj2) {
  // Sort TreeMap based on name
  //return obj1.getName().compareTo(obj2.getName());
  // Sort TreeMap based on salary
  if(obj1.getSalary() > obj2.getSalary()) return 1;
  else if(obj1.getSalary() < obj2.getSalary()) return -1;
  else return 0;


KEY : (joy:2000)   VALUE : joy
KEY : (david:5000)   VALUE : david
KEY : (abel:7000)   VALUE : abel
KEY : (ruby:9000)   VALUE : ruby

read more.. "TreeMap using custom object sorting"

How to create Factory Design Pattern in Java

Already we have seen Fully Singleton Design Pattern in our earlier tutorial, now we will see about Factory Design Pattern. 

Factory design pattern is one is the most important and widely used pattern every where in Java. The factory method pattern defines an interface for creating an object, but let sub-classes decide which class to instantiate based on the user requirement. JDK and most of all frameworks like Spring, Struts etc uses factory design pattern internally. Also factory design pattern can be classified into various types like Static Factory, Service Locator Factory and Abstract Factory. 

Lets see one simple example as getting various Computer instances based on the used requirement. As we already explained above we need to have a interface for creating and Object but sub-classes will decide which class need to be instantiated  As same way we are going to have interface called "Computer" and sub-classes like "Desktop", "WorkStation", "Server", "Laptop" and "SuperComputer" will implement "Computer" interface and will their own method definitions. 

public interface Computer {
 public String myComputerType();

public class Desktop implements Computer {
 public String myComputerType() {
  return "You have requested for Desktop";

public class WorkStation implements Computer {
 public String myComputerType() {
  return "You have requested for WorkStation";

public class Server implements Computer {
 public String myComputerType() {
  return "You have requested for Server";

public class Laptop implements Computer {
 public String myComputerType() {
  return "You have requested for Laptop";

public class SuperComputer implements Computer {
 public String myComputerType() {
  return "You have requested for SuperComputer";

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

  // Based on user requirement we will get the Object
  Computer obj = FactoryPattern.getComputerType("desktop");
  if(obj != null) 
  obj = FactoryPattern.getComputerType("laptop");
  if(obj != null) 
  obj = FactoryPattern.getComputerType("server");
  if(obj != null) 
 public static Computer getComputerType(String val){
  if(val.equalsIgnoreCase("desktop")) return new PC();
  else if(val.equalsIgnoreCase("workstation")) return new WorkStation();
  else if(val.equalsIgnoreCase("server")) return new Server();
  else if(val.equalsIgnoreCase("laptop")) return new Laptop();
  else if(val.equalsIgnoreCase("super")) return new SuperComputer();
  return null;


You have requested for Desktop
You have requested for Laptop
You have requested for Server

read more.. "How to create Factory Design Pattern in Java"