Autoboxing and Unboxing in Java

As we know that primitive data types cannot participate in object-like activities, and java provides solution to this in form of wrapper classes. Each primitive type has a corresponding wrapper class that stores the values of that type, and they can act as objects. So, you wrap a primitive value into the corresponding wrapper object and then that value can act as an object type. This process is called boxing. When you need the primitive value back, you retrieve it from the wrapper by invoking an appropriate method on it. This is called unboxing

If there is a lot of boxing and unboxing going on, your program becomes cluttered and you are doing the same thing over and over again: boxing and unboxing. J2SE 5.0 presents a solution to this problem by automating boxing and unboxing, a feature known as autoboxing.

Autoboxing is the capability to assign a primitive value to a corresponding wrapper type; the conversion from primitive type to wrapper type is automated. Auto-unboxing is the reverse of autoboxing: that is, the capability to assign a wrapper type to the corresponding primitive type; the conversion from wrapper to primitive is automated. 

Autoboxing is also sometimes used, for short, to refer to both autoboxing and auto-unboxing.



Without autoboxing, you will need to do wrapping and un-wrapping manually. As an example, consider the following code fragment:


            public Double areaOfSquare(Double side) {
       double d = side.doubleValue();
       double a = d * d;
       return new Double(a);
     }


In this code fragment, you unwrap the double value, calculate area, and then wrap the result again before returning it. You had to do this boxing and unboxing manually before J2SE 5. But now in J2SE 5, you can simply replace the preceding code fragment with the following:
  

    public Double areaOfSquare(Double side){

       return side*side;

    }

Remember that, the boxing and unboxing is still done, but it’s done automatically; it’s hidden from you. Therefore, although it may seem as if you can treat wrappers just like primitives, you can make mistakes if you forget the fact that boxing and unboxing is still being done transparently.

Also remember that Autoboxing and unboxing will work only between corresponding primitives and wrappers, such as int and Integer, double and Double, and float and Float. If you cannot box a primitive type into a wrapper, you cannot autobox it either. 

 

How to split string literal using java regex

Some time we need to split a string literal based on some delimiters . Java regular expressions provides an easy way of doing it. Let see a sample java program used to split a string literal based on pre-defined delimiter.

MySplitter.java


import java.util.regex.*;

public class MySplitter {
       public static void main(String[] args) {
              String input = "www.naeemgik.blogspot.com";
              Pattern p = Pattern.compile("\\.");
              String pieces[] = p.split(input);
              for (int i = 0; i < pieces.length; i++) {
                     System.out.println(pieces[i]);
              }
       }
}




The output of above code would be:

   www
   naeemgik
   blogspot
   com

 

Validating Email using Java Regular Expressions

Java provides support for regular expressions and for matching the patterns (i.e. specific text in the string) by providing the following elements:
  • The java.util.regex.Pattern class 
  • The regular expression constructs 
  • The java.util.regex.Matcher class
The simplest form of a regular expression is a literal string search. For example, if you want to find out a specific word such as 'java' in the input text. You will build an expression construct for that. However, you can build very sophisticated expressions using java regular expression constructs. Consider the following expression:

   [A-Za-Z0-9]
This expression mean any character in the range of A through Z, a through z, or 0 through 9 (any letter or digit) will match this pattern. For all rest of the characters the following regular expression construct will match.

   [^A-Za-z0-9]

Where the character ^ is used for negate.



Now I a assume that you are familiar with basics of java regular expressions, So let explore it with a simple example of email validation using java regex.
EmailValidator.java 

import java.util.regex.*;


public class EmailValidator {
       public static void main(String[] args) {
              String email = "";
              if (args.length < 1) {
                     System.out.println("Command syntax: " +
                                  "java EmailValidator <emailAddress>");
                     System.exit(0);
              } else {
                     email = args[0];
              }
              // Look for for email addresses starting with
              // invalid symbols: dots or @ signs.
              Pattern p = Pattern.compile("^\\.+|^\\@+");
              Matcher m = p.matcher(email);
              if (m.find()) {
                     System.err.println("Invalid email address: " +
                                  "starts with a dot or an @ sign.");
                     System.exit(0);
              }
              // Look for email addresses that start with www.
              p = Pattern.compile("^www\\.");
              m = p.matcher(email);
              if (m.find()) {
                     System.out.println("Invalid email address: " +
                                  "starts with www.");
                     System.exit(0);
              }
              p = Pattern.compile("[^A-Za-z0-9\\@\\.\\_]");
              m = p.matcher(email);
              if (m.find()) {
                     System.out.println("Invalid email address: " +
                                  "contains invalid characters");
              } else {
                     System.out.println(args[0] +  
                             " is a valid email address.");
              }
       }
}

To execute the the above program, you need to give a string as a command-line argument, for example:

   java EmailValidator www.naeemgik.com@aol.com


This will produce the following output:

     Invalid email address: starts with www.

Similarly you can test the above code with different valid and invalid email addresses provided as command line. 

Reference(s): SCJP Exam for J2SE 5