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

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 








Java 7 - try-with-resources

In earlier tutorials we have seen couple of Java 7 features like Underscore in numeric literals, Switch Case with non-primitive data-type and Exception handling with multi-catch.

In this tutorial we will see about try-with-resources is a one of the fine feature added in Java 7.
 

For example if we need to allocate a resource for file handling or database connectivity then we need to explicitly close the resource which we have opened in our try block. In those cases it will be tedious to handle lot of resource management manually. In some of the cases we will have try with finally block where we will check for the resource closing. No matter whether the to resource has allocated or not finally block will be executed automatically for all time. Below is the simple example from earlier Java 7 as how we used to handle resources by using file handling.
 



public class MyOldFileHandling {
    public static void main(String[] arg){
        FileInputStream fstream = null;
        DataInputStream istream = null;
        BufferedReader breader = null;
        try {            
            fstream = new FileInputStream("test.txt");
            istream = new DataInputStream(fstream);
            breader = new BufferedReader(new InputStreamReader(istream));
            String line;
            while ((line = breader.readLine()) != null) {
                System.out.println (line);
            }            
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally{
            try{
                /* 
                 * Explicitly all resources need to be closed in 
                 * earlier java versions 
                */

                if(fstream != null)fstream.close();
                if(istream != null)istream.close();
                if(breader != null)breader.close();
            }catch(IOException ioe){
                ioe.printStackTrace();;
            }
        }
    }
}



In above program we can see explicitly programmers need to handle resource closing under finally block, whether resource has or not finally block will be executed compulsory. 

But in Java 7 onwards try-catch-resource feature introduced and programmer need not to worry about resource management once when we add resource in try statement as like bellow.
 



try(FileInputStreamfstream = new FileInputStream("test.txt")) {
.
.
}



Above statement will have same functionality of FileInputStream of our above program. Where as here resource closing close() method will be automatically called once try block completed. Even we can multiple resource under single try block as like below.
 



try(FileInputStreamfstream = new FileInputStream("test.txt");
    DataInputStream istream = new DataInputStream(fstream);
    BufferedReader breader = new BufferedReader(new InputStreamReader(istream))) {
.
.
}

Below example will show same above program will be handled using try-with-resource using Java 7.
 



public class MyNewFileHandling {
        public static void main(String[] arg){
        
        try (FileInputStream fstream = new FileInputStream("test.txt");            
             DataInputStream istream = new DataInputStream(fstream);
             BufferedReader breader = new BufferedReader(new InputStreamReader(istream))) {            
            
            String line;
            while ((line = breader.readLine()) != null) {
                System.out.println (line);
            }            
        } catch (IOException ex) {
            ex.printStackTrace();
        } 
    }
}




 

Java 7 - Underscores in Numeric Literals

 
In this tutorial we will discuss about Underscore in Numberic feature added in Java 7. This is a nice and small feature which has added in Java 7 gives good readability for our codes. Its nothing but we can use underscores ( _ ) in-between numberic values in our code. Underscore can be added anywhere in the value part with few constraints listed below,

ALLOWED:
In-between 2 numbers or hexadecimal values or binary values are allowed. Below are the few valied literals by using underscore which are given in Oracle docs.

long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi = 3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;

NOT ALLOWED:

Can't place underscore at beginning or end of the numberic value.
Adjacent to a decimal point in a floating point value literal is not allowed
Prior to an F or L suffix are not allowed
Positions where a string of digits is expected are not allowed
 

float pi1 = 3_.1415F; // Invalid; cannot put underscores adjacent to a decimal point
float pi2 = 3._1415F; // Invalid; cannot put underscores adjacent to a decimal point
long socialSecurityNumber1 = 999_99_9999_L;         // Invalid; cannot put underscores prior to an L suffix

int x1 = _52;            // This is an identifier, not a numeric literal
int x2 = 5_2;            // OK (decimal literal)
int x3 = 52_;            // Invalid; cannot put underscores at the end of a literal
int x4 = 5_______2;  // OK (decimal literal)

int x5 = 0_x52;        // Invalid; cannot put underscores in the 0x radix prefix
int x6 = 0x_52;        // Invalid; cannot put underscores at the beginning of a number
int x7 = 0x5_2;        // OK (hexadecimal literal)
int x8 = 0x52_;        // Invalid; cannot put underscores at the end of a number

int x9 = 0_52;         // OK (octal literal)
int x10 = 05_2;       // OK (octal literal)
int x11 = 052_;       // Invalid; cannot put underscores at the end of a number
 

Lets see one small example by using underscore in numeric literals.
 



public class LiteralsExample {
   public static void main(String[] arg){
       
       float x1 = 52.4_5F;              
       float x2 = 5_2.12F;            
       
       int x3 = 52_3;              
       int x4 = 5_______2;        
       
       System.out.println("FLOAT VALUE :"+(x1+x2));
       System.out.println("INT VALUE   :"+(x3+x4));    
   }
}



OUTPUT:


FLOAT VALUE :104.57
INT VALUE   :575





Java 7 - Switch case with non-primitive (String)

 
In last tutorial we have discussed about multi-catch feature in Java 7. Now lets see how Java 7 supports non-primitive datatype in switch case. Until Java 6 we had only switch cases support for primitive datatypes like int, char, short, and byte.  

      Below small example will gives you how switch case works until Java 6 with primitive datatype int.



public class MySwitch {
 public static void main(String[] args) {
  int days = Integer.parseInt(args[0]);
  switch(days){
   case 0: 
    System.out.println("Monday");
    break;
   case 1: 
    System.out.println("Tuesday");
    break;
   case 2: 
    System.out.println("Wednesday");
    break;
   case 3: 
    System.out.println("Thursday");
    break;
   case 4: 
    System.out.println("Friday");
    break;
   case 5: 
    System.out.println("Saturday");
    break;
   case 6: 
    System.out.println("Sunday");
    break;
   default: 
    System.out.println("Sorry Invalid Input!!!");    
  }
 }
}


      In above program we have taken the command line input value and checked for day of week by using switch case. Here we have used primitive datatype int for variable "days".

      Additionally in Java 7 we have got non-primitive datatype String also can be used in the Switch case. Below example will give the same code of Java 7 Switch case with String.



public class MySwitch {
 public static void main(String[] args) {
  String day = args[0];
  
  switch(day.toLowerCase()){
   case "monday": 
    System.out.println("Hai its weeks 1st day...");
    break;
   case "tuesday": 
    System.out.println("Hai its weeks 2nd day...");
    break;
   case "wednesday": 
    System.out.println("Hai its weeks 3rd day...");
    break;
   case "thursday": 
    System.out.println("Hai its weeks 4th day...");
    break;
   case "friday": 
    System.out.println("Hai its weeks 5th day...");
    break;
   case "saturday": 
    System.out.println("Hai its weeks 6th day...");
    break;
   case "sunday": 
    System.out.println("Hai its weeks 7th day...");
    break;
   default: 
    System.out.println("Sorry Invalid Input!!!");    
  }
 }
}



Hope you are clear on new switch case in Java 7 and lets see other Java 7 feature in next tutorial. 






    

Java 7 new Exception Handling using multi-catch

 
Good to hear that in Java 7 has packed with lot of new features and additional features in Exception Handling, Switch case, Collections etc., Today we will discuss about the additional features which we have got from JAVA 7 in Exception handling. 

      Lot of programmers will use single catch() block for handling all exception types by placing the common Exception as like below in Java 6 and earlier versions. 



public class MyClass {
 public static void main(String[] args) {
  try{
   /*
    * You code goes here where multiple
    * exceptions can occur 
    */    
  }catch (Exception e) {
   // Log the exception 
  }
 }
}



      By handling exceptions like above we may lead to lot of issues like handling exceptions efficiently and also its not good practice until Java 6. So in earlier version we used to have multiple catch statements to handle each and every exceptions which may occur in the block as like below. 





public class MyClass {
 public static void main(String[] args) {
  try{
   /*
    * You code goes here where multiple
    * exceptions can occur 
    */    
  }catch (NullPointerException ex) {
   // Log the exception 
  }catch (ClassCastException ex) {
   // Log the exception
  }catch (StackOverflowError err) {
   // Log the error message
  }catch (Exception e) {
   // Log the exception
  }
 }
}


       
      Buy using like this also code goes ugly and lot of huddles in handling each and every Exceptions independently in separate catch blocks. 

     To over come this issue in Java 7 have packed with multi-catch feature in Exception handling and it will be handy to use in a single catch or multiple catch as programmers wish. Lets see small example as how to use multi-catch in Java 7 



public class MyClass {
 public static void main(String[] args) {
  try{
   /*
    * You code goes here where multiple
    * exceptions can occur 
    */    
  }catch (NullPointerException | ClassCastException | StackOverflowError ex) {
   // Log the exception 
  }
 }
}



Hope you are clear and happy that Java 7 has given a good feature for programmers to handle exceptions in a new way. Lets discuss more new features added in Java 7 in our next tutorial.