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 = "to@gmail.com";
  // If any CC email ids
  String cc = "cc@abcmail.com";
  // If any BCC email ids
  String bcc = "bcc@abcmail.com";
  // 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 = "from@gmail.com";
  // Password of from address
  String password = "frompassword";
  // Gmail host address
  String host = "smtp.gmail.com";
  
  Properties props = System.getProperties();
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  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));

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



IMP:
Suppose if you are getting exception while running above like,

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: 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. 







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.


Valid:

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

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

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

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


Invalid:

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) {
  myMethod1(1,2,3,4,5);
  myMethod2("hello", "welcome", "to", "Java Discover");
  myMethod3(100,3.0f, "hello", "welcome", "to", "Java Discover");
 }
}


OUTPUT:


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 








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);  
 }
}







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){
        this.name = name;
        this.salary = salary;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.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.name+":"+this.salary+")";
    }
}




public class MyNameComp implements Comparator<Worker>{

 @Override
 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;
    } 
}

OUTPUT:


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









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) 
   System.out.println(obj.myComputerType());
  
  obj = FactoryPattern.getComputerType("laptop");
  if(obj != null) 
   System.out.println(obj.myComputerType());
  
  obj = FactoryPattern.getComputerType("server");
  if(obj != null) 
   System.out.println(obj.myComputerType());
 }
 
 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;
 }
}



OUTPUT:


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









How to Override equals() and hashcode() methods in Java?

In this tutorial we will see how to Override equals() and hashcode() method in our code. First up all lets see what is equals and hashcode method.
  • equals() method indicates whether other Object is equal to same class Object. It will return boolean value as true when both Objects are equal and false when both Objects are not equals.
  • hashcode() method returns the hashcode of the Object passed and will be called automatically first whenever we use equals() method to compare 2 Objects. 
Lets see java examples for Overriding equals and hashcode method. In this example we will use HashMap to store "MyObject" class instance in key part. 

We all knows that HashMap won't allow duplicate key. In that case first example we will see about storing Object in key without Overriding equals() and hashcode() methods and second example by Overriding equals() and hashcode() methods.

Without overriding equals() and hashcode() methods


class MyObject{

 String val;
 
 public MyObject(String val) {
  this.val = val;
 } 
}




public class MyTest {
 
 public static void main(String[] args) {
  
  MyObject obj1 = new MyObject("sunday"); // 1st 
  MyObject obj2 = new MyObject("monday"); // 2nd 
  MyObject obj3 = new MyObject("sunday"); // 3rd
  
  HashMap<MyObject, String> hm = new HashMap<MyObject, String>();
  hm.put(obj1, "1");
  hm.put(obj2, "2");
  hm.put(obj3, "3");
  hm.put(obj1, "4");
  hm.put(obj1, "5");
  
  System.out.println("HASHMAP SIZE : "+hm.size());
 } 
}


OUTPUT:


HASHMAP SIZE : 3

3 instance we have created and stored in HashMap.


With overriding equals() and hashcode() methods
class MyObject{
 String val;
 public MyObject(String val) {
  this.val = val;
 } 
 
 @Override
 public boolean equals(Object obj) {
  return ((MyObject)obj).val.equals(this.val);
 }
 
 @Override
 public int hashCode() {
  
  /*We will return same hashcode as 0 for 
  all Object since its same class Object
  */
  return 0;
 }
}


OUTPUT:

HASHMAP SIZE : 2


Same MyTest class and MyObject class Overrides equals() and hashcode() methods. In equals method we have compared 2 Objects of "MyObject" class member variable "val" and returned true when 2 objects have same value "sunday". Hence we have only 2 elements in HashMap. 







What is the difference between final, finally and finalize in Java?

 
In this tutorial we will see about difference between final, finally and finalize in Java. 

final - final is a keyword in Java used to indicate whether variable, method or class can be a final. 
Once a variable set as final then the value can't be changed. 
Once a method set as final then the method can't be override d.
Once a class set as final then the class can't be inherited or extended by other classes.

finally - finally is block used in exception handling. Finally can be followed by try-catch or without catch block. But once we place a finally block then it will be executed always. 

finalize - finalize is a method and used in garbage collection. finalize() method will be invoked just before the Object is garbage collected. It will be called automatically by the JVM on the basis of resource reallocating.  Even programmers can call finalize method by using System.gc(); but vendor to vendor (Different OS) will change and not sure 100% finalize method will be called. 

Lets see small program for final, finally and finalize



Example for final:


// Final class
public final class FinalTest {
 
 // Final member variable
 private final int id = 100; 
 
 // Final method
 public final void getValue(){
  System.out.println("Inside final method");
 }
}




Example for finally:


public final class FinallyTest {
 
 public int getValue1(){
  try{
   return 10;
  }catch(NumberFormatException e){
   e.printStackTrace();
  }finally{
   return 20;
  }
 }
 
 public int getValue2(){
  try{
   return 100;
  }finally{
   return 200;
  }
 }
 
 public static void main(String[] args) {
  FinallyTest obj = new FinallyTest();
  
  int val1 = obj.getValue1();
  int val2 = obj.getValue2();
  
  System.out.println("VALUE-1 : "+val1);
  System.out.println("VALUE-2 : "+val2);
 }
}




Example for finalize:


public final class FinalizeTest {
 
 @Override
 protected void finalize() throws Throwable {
  System.out.println("Inside Finalize method");
  super.finalize();
 }
 
 public static void main(String[] args) {
  try{
   FinalizeTest obj = new FinalizeTest();
  }catch (Exception e) {
   e.printStackTrace();
  }
  System.gc();
 }
}