Java Reflection

In this tutorial we will see about Java Reflection and how to use. Java Reflection is a important topic and need to use only when its necessary in our programming. It deals with class and methods at run-time and as its API we need to include necessary classes in our program.

Java reflection is used in most of application and frameworks. For example JUnit is most commonly used for unit testing by the programmers. Where we used to specify the methods with @Test annotation which will mark to the JUnit as testcase and will be executed automatically by calling corresponding class and methods using Java Reflection.

Lets see small example of Java Reflection by parameter and without parameter.


class MyClass{
 
 public void simpleMethod(){
  System.out.println("Hi, inside simple method...");
 }
 
 public void methodWithStringParam(String name){
  System.out.println("Hi, "+name);
 }
 
 public void methodWithIntParam(int value){
  System.out.println("Value passed : "+value);
 }
 
 public void methodWith2Param(String name1, int value){
  System.out.println("Hi, "+name1+" & "+value);
 }
 
 public String methodWithReturn(){
  return "Java Discover";
 }
}



import java.lang.reflect.Method;
 
public class ReflectionTesting { 
 
public static void main(String[] args)  {
  
  try {
   // Create class instance at runtime
   Class cls = Class.forName("com.test.MyClass");
   Object obj = cls.newInstance();
   
   
   // Calling method simpleMethod() without parameters 
   Class param1[] = {};
   Method method = cls.getDeclaredMethod("simpleMethod", param1);
   method.invoke(obj, null);
  
   
   // Calling method methodWithStringParam() with String parameter
   Class param2[] = new Class[1];
   param2[0] = String.class;
   method = cls.getDeclaredMethod("methodWithStringParam", param2);
   method.invoke(obj, new String("Java Discover"));
   
   
   // Calling method methodWithIntParam() with String parameter
   Class param3[] = new Class[1];
   param3[0] = Integer.TYPE;
   method = cls.getDeclaredMethod("methodWithIntParam", param3);
   method.invoke(obj, 1000);
   
   
   // Calling method methodWith2Param() with String and Integer parameters
   Class param4[] = new Class[2];
   param4[0] = String.class;
   param4[1] = Integer.TYPE;
   method = cls.getDeclaredMethod("methodWith2Param", param4);
   method.invoke(obj, new String("Java Discover"), 2006);
   
   
   // Calling method methodWithReturn() with return 
   method = cls.getDeclaredMethod("methodWithReturn", param1);
   String rValue = (String)method.invoke(obj, null);
   System.out.println("Returned value : "+rValue);
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}



OUTPUT:

Hi, inside simple method...
Hi, Java Discover
Value passed : 1000
Hi, Java Discover & 2006
Returned value : Java Discover




Java Clone()



In this tutorial we will see about Java Clone and how to implement in our coding. Before jumping into coding lets discuss What is Java Clone and how its working.

What is Java Clone?
Clone is nothing but creating a copy of Object with the same state of cloning Object. For example if we clone a Object called "obj1" to "obj2" then new Object will be created with same state and value. There are Shallow copy and Deep copy which we will discuss in our next tutorial.

How its Working?
Suppose if we need to use clone for our class then we need to implement Cloneable interface in our class with clone() method, which will create a copy of super class and return's the Object. Below example will gives you how to use use clone() on user defined class and Collection Objects.



public class MyClass implements Cloneable {

 String name;
 String company;

 public MyClass(String name, String company) {
  System.out.println("Inside Constructor....");
  this.name = name;
  this.company = company;
 }

 public String getName() {
  return this.name;
 }

 public String getCompany() {
  return this.company;
 }

 public Object clone() {
  try {
   MyClass cloned = (MyClass) super.clone();
   return cloned;
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
   return null;
  }
 }
}




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

  MyClass obj1 = new MyClass("Kamal", "ABC Limited.");

  System.out.println("\nName    : " + obj1.getName());
  System.out.println("Company : " + obj1.getCompany());

  // Cloning the Object
  MyClass obj2 = (MyClass) obj1.clone();

  System.out.println("\nName    : " + obj2.getName());
  System.out.println("Company : " + obj2.getCompany());

  ArrayList<String> arr1 = new ArrayList<String>();
  arr1.add("Java");
  arr1.add("J2EE");
  System.out.println("\nFirst ArrayList  : "+arr1);
  
  ArrayList<String> arr2 = (ArrayList<String>) arr1.clone();
  System.out.println("\nSecond ArrayList : "+arr2);
 }
}



OUTPUT:


Inside Constructor....

Name    : Kamal
Company : ABC Limited.

Name    : Kamal
Company : ABC Limited.

First ArrayList  : [Java, J2EE]

Second ArrayList : [Java, J2EE]




Java Interview Questions


Java Interview Questions

In this tutorial we will see about some basic Java programming questions asked in interview. Below are the list of few questions and along with solution.

  • Reversing a String without reverse() function
  • Add numbers from the given input
  • Count no. of words in the line or paragraph
  • Find Armstrong number or not
  • Find Prime number or not

Reversing a String without reverse() function

public class StringReverse {
 
 public static void main(String[] args) {
  
  String str = "Java Discover";
  System.out.println("Input String : "+str);
  str = myReverseFunction(str);
  System.out.println("Reversed String : "+str);
 }
 
 /**
  * Need to reverse a String without reverse() function
  * @param str
  * @return
  */
 public static String myReverseFunction(String str){
  char[] chars = str.toCharArray();
  StringBuilder sb = new StringBuilder();
  for (int i=str.length()-1;i>=0;i--) {
   sb.append(chars[i]);
  }
  return sb.toString();
 }
}


OUTPUT:


Input String : Java Discover
Reversed String : revocsiD avaJ



Add numbers from the given input
 

public class AddNumerals {
 
 public static void main(String[] args) {
  int value = 1234;
  int output = addNumerals(value);
  System.out.println("INPUT : "+value);
  System.out.println("OUTPUT : "+output);
 }
 
 /**
  * Add numerals in the given param value
  * For example input=1234 then output should be 1+2+3+4=10
  * @param value
  * @return
  */
 public static int addNumerals(int value){
  int output = 0;
  while(value > 0){
   output += value%10;
   value = value/10;
  }  
  return output;
 }
}



OUTPUT:


INPUT : 1234
OUTPUT : 10




Count no. of words in the line or paragraph
 

public class CountWords {

 public static void main(String[] args) {
  String line = "The string tokenizer class allows an application to break a string into tokens";
  int noOfWords = countNoOfWordsInLine(line);
  System.out.println("Input : "+line);
  System.out.println("No Of Words : "+noOfWords);
 }
 
 /**
  * Count no. of words in a line or paragraph 
  * @param line
  * @return
  */
 public static int countNoOfWordsInLine(String line){
  int output = 0;
  StringTokenizer tok = new StringTokenizer(line);
  output = tok.countTokens();
  return output;
 }
}



OUTPUT:


Input : The string tokenizer class allows an application to break a string into tokens
No Of Words : 13




Find Armstrong number or not
 

public class ArmstrongOrNot {
 
 public static void main(String[] args) {
  long input = 54748;
  boolean flag = checkArmstringOrNot(input);
  if(flag){
   System.out.println(input+" is Armstrong number");
  }else{
   System.out.println(input+" is NOT Armstrong number");
  }  
 }
 
 /**
  * Check given number is Armstrong number or not
  * For example, 371 is an Armstrong number, since 3^3 + 7^3 + 1^3 = 371 
  * @param input
  * @return
  */
 public static boolean checkArmstringOrNot(long input){
  int output = 0;
  long tmp = input;
        int length = Long.toString(input).length();
        while(tmp != 0){
         long rem = tmp % 10;
            long tmp1 = 1;
            for(int i = 0; i < length ;i++){
             tmp1 *= rem;
            }
            output += tmp1;
            tmp = tmp/10;
        }
        if(input == output){
            return true;
        }
        return false;
 }
}



OUTPUT:


54748 is Armstrong number




Find Prime number or not
 

public class PrimeOrNot {

 public static void main(String[] args) {
  int input = 23;
  boolean flag = primeOrNot(input);
  if(flag){
   System.out.println(input+" is a Prime number");
  }else{
   System.out.println(input+" is NOT a Prime number");
  }
 }
 
 /**
  * Check whether given number is Prime or Not
  * @param input
  * @return
  */
 public static boolean primeOrNot(int input){
  for(int i=2;i<=input/2;i++){
   if(input%i == 0){
    return false;
   }
  }
  return true;
 }
}



OUTPUT:


23 is a Prime number




More questions will be added shortly. 



Volatile in Java

Volatile is a important topic in Java where we will use in Multi-Threading. Volatile keyword will be used in variables and the value will be changed simultaneously by other threads. This makes compiler to read the value from main memory instead of reading from registers. If we say simply value will not be cached in register. And also this makes each thread to get current value of the variable and each thread will not change values unexpectedly.

The main use of Volatile is stops caching the values of variables in registers. When every time value got changes, immediately flushes the value to RAM where other threads can access the updated value directly.

Here we may think of synchronized which will holds a lock for an Object. Where as here its not suitable since we are just reading and updating value when we use Volatile keyword. Volatile can be applied on Object or Primitive types.

Before Java version 1.5 Volatile is not guarantee the atomicity of a 64-bit long load. For example while thread updating some 64 bit long and other reads can get half of old values and half of new values which will reside in improper value. Later from Java 1.5 onwards atomicity of volatile longs is guaranteed on 64-bit hardware also.

Lets see small example of using Volatile keyword which will works along with Multi Threading.



public class MyVolatile {
 
 static volatile long value = 1234567890L;
 
 public static void main(String[] args) {
  new Thread(new IncrementVolatileValue()).start();
  new Thread(new CheckVolatileValue()).start();
 }
 
 static class CheckVolatileValue implements Runnable{
  @Override
  public void run() {   
   for(int i=0;i<10;i++){
    System.out.println("Value Same : "+value);
   }
  }
 }
 
 static class IncrementVolatileValue implements Runnable{
  @Override
  public void run() {
   for(int i=0;i<10;i++){
    System.out.println("Value Incremented : "+value++);
   }
  }
 } 
}



In above example we are incrementing volatile variable in single Thread and by other Thread we are reading the value and printing in loop for checking the change of value. Both the threads are having its own stack and its own copy of variables in its own memory. Volatile keyword is used to say to the JVM "Warning, this variable can be changed by other Thread" so don't cache it, rather read every time from RAM.

So one who programmer need to decide whether he needs to use Volatile or not according to his business logic's.








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.

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









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:


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

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) {
    System.out.println(line);
   }
  } catch (IOException e) {
   e.printStackTrace();
  
  } finally {
   if (br != null){
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}



Reading from remote server through HTTP:


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class ReadFile {
 public static void main(String[] args) {
  InputStreamReader isr  = null;
  BufferedReader buffRead = null;
  
  try{
   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) {
    System.out.println(str);    
   }     
  
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  
  } finally{
   try{
    if(buffRead != null) buffRead.close();
    if(isr != null) isr.close();
   }catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}





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.