Boxing and Unboxing

Boxing and Unboxing

Boxing and Unboxing in java is nothing but conversion from Wrapper classes to primitive datatypes and vice-verse in Java. In our earlier tutorial we have seen about list of Wrapper classes and their corresponding primitive datatypes in Java
In that tutorial already we have seen about 8 wrapper classes and their class hierarchy also. So what is Boxing and Unboxing is when we convert an int to an Integer, a double to a Double etc., is called as Boxing and opposite conversion like Integer to int, Double to double is called as Unboxing. Now lets see simple example of both Boxing and Unboxing in java.



public class BoxingTest {

 public static void main(String[] args) {
 
  int _int = 1;
  byte _byte = 2;
  short _short = 3;
  long _long = 4;
  float _float = 5.5f;
  double _double = 6;
  char _char = 'a';
  boolean _boolean = true;
  
  
  // Boxing (Primitive datatype to Wrapper classes)
  Integer w_int = new Integer(_int); 
  Byte w_byte = new Byte(_byte);
  Short w_short = new Short(_short);
  Long w_long = new Long(_long);
  Float w_float = new Float(_float);
  Double w_double = new Double(_double);
  Character w_char = new Character(_char);
  Boolean w_boolean = new Boolean(_boolean);
 
  
  
  // Unboxing (Wrapper class to Primitive datatypes)
  int _int1 = w_int;
  byte _byte1 = w_byte;
  short _short1 = w_short;
  long _long1 = w_long;
  float _float1 = w_float;
  double _double1 = w_double;
  char _char1 = w_char;
  boolean _boolean1 = w_boolean;
 }
}


In above example we have seen how converting primitive datatype to Wrapper class values is called as Boxing and next same Wrapper class object are stored into Primitive datatype is called as unboxing in java. 


Thread join()

 
Basically Thread.join() method allows one thread to wait for the completion of another thread. Suppose if a Thread "A" is running and when we call A.join(), causes the current thread to halt its execution until A thread terminates or complete its process. By join we can make the current thread to wait for the time as same as sleep() method. Where as timing depends on the Operating System and its not on the time which we can specify. Apart from waiting time join can be interrupt by InterruptedException as same as in sleep in method. 

There are 3 types of join() methods in Java Thread class and they are 

void join()
- Waits for the current thread to terminate or to finish its process.
- Throws InterruptedException if another thread has interrupted the current thread.
- Returns nothing.

void join(long ms)
- Waits at most (ms) milliseconds for current thread to terminate or to finish its process.
- Throws InterruptedException if another thread has interrupted the current thread.
- Returns nothing.

void join(long ms, int ns)
- Waits at most (ms) milliseconds and (ms) nanoseconds for current thread to terminate or to finish its process.
- Throws InterruptedException if another thread has interrupted the current thread.
- Returns nothing.

Lets see simple example in Java Thread to use join() method and how its works.


public class ThreadJoinTest implements Runnable {
 
 @Override
 public void run() {
  try {
   System.out.println(Thread.currentThread().getName());
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args) {
  ThreadJoinTest obj = new ThreadJoinTest();
  for(int i=0;i<10;i++){
   Thread t = new Thread(obj);
   t.start();
   try {
    t.join();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}


OUTPUT:


Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
Thread-5
Thread-6
Thread-7
Thread-8
Thread-9


If we seen above program we have used t.join() for each Thread which we have created. Since join we have used it makes other thread to wait until current thread to complete. This program will work similar to normal java code without multi-threading implementation. Please try with same code by removing t.join() where we can see normal multi-threading implementation on same Object.

OUTPUT: ( By removing t.join() )


Thread-1
Thread-3
Thread-5
Thread-7
Thread-9
Thread-0
Thread-2
Thread-4
Thread-6
Thread-8




Eclipse shortcuts

Eclipse shortcuts

In this tutorial we will see about few important Eclipse shortcut keys and their uses. In practice most of the time using mouse to choice our operations  will cause more time and it may reduce productivity. Not only in Eclipse using shortcuts in any application or OS level will be preferable which will save time and to perform task more faster. 
In Windows most common shortcuts which we are familiar like Select All ( Ctrl + A ), Cut ( Ctrl + X), Copy ( Ctrl + C) and Paste ( Ctrl + V ).  Even in Eclipse they have followed same shortcuts for Select All, Cut, Copy and Paste. Apart from these shortcuts there are lot of keys which will be useful when we programming. Lets see those shortcuts with their usage, 

File Operation Shortcuts:

Create New File Ctrl+N
New Popup Menu Alt+Shift+N
Open Properties Window Alt+Enter
File Refresh F5
File Rename (First Select file) F2
Print Current File/Program Ctrl+P
Save File Ctrl+S
Save All File Ctrl+Shift+S
Close Current Tab Ctrl+W or Ctrl+F4
Close All Open Tab Ctrl+Shift+W or Ctrl+Shift+F4
Exit Eclipse Alt+F4

Program Window Operation Shortcuts:

Maximize Active Tab/Window Ctrl+M
Select Next Tab/Window Ctrl+F6
Reset Perspective Ctrl+F8
Open Views window Ctrl+F7
Open Editor Drop Down Window Ctrl+E
Previous Edited Window Ctrl+Shift+F6
Previous Perspective Ctrl+Shift+F8
Previous View Ctrl+Shift+F7
Show Ruler Context Menu Ctrl+F10
Show System Menu Alt+-
Show View Menu Ctrl+F10
Open Switch to Editor Window Ctrl+Shift+E

File Edit Operation Shortcuts:

Select All Ctrl+A
Select Enclosing Element Alt+Shift+Up
Select Next Element Alt+Shift+Right
Select Previous Element Alt+Shift+Left
Cut Ctrl+X
Copy Ctrl+C
Paste Ctrl+V
Delete Delete
Delete Line Ctrl+D
Delete Next Word Ctrl+Delete
Delete Previous Word Ctrl+Backspace
Find and Replace Ctrl+F
Find Next Ctrl+K
Find Previous Ctrl+Shift+K
Context Information Ctrl+Shift+Space
Incremental Find Ctrl+J
Incremental Find Reverse Ctrl+Shift+J
Quick Diff Toggle Ctrl+Shift+Q
Quick Fix Ctrl+1
Restore Last Selection Alt+Shift+Down
Toggle Insert Mode Ctrl+Shift+Insert
Content Assist Ctrl+Space
Duplicate Lines Ctrl+Alt+Up
Insert Line Above Current Line Ctrl+Shift+Enter
Insert Line Below Current Line Shift+Enter
Move Lines Down Alt+Down
Move Lines Up Alt+Up
Next Word Ctrl+Right
Previous Word Ctrl+Left
Scroll Line Down Ctrl+Down
Scroll Line Up Ctrl+Up
Select Next Word Ctrl+Shift+Right
Select Previous Word Ctrl+Shift+Left
To Lower Case Ctrl+Shift+Y
To Upper Case Ctrl+Shift+X
Undo Ctrl+Z
Redo Ctrl+Y

Build & Run Operation Shortcuts:

Build All Ctrl+B
Run Ctrl+F11
Debug F11
Display Ctrl+Shift+D
Execute Ctrl+U
Inspect Ctrl+Shift+I
Resume F8
Run Last Launched Ctrl+F11
Run to Line Ctrl+R
Toggle Breakpoint Ctrl+Shift+B
Use Step Filters Shift+F5

TreeSet

 
In our earlier tutorials we have seen about LinkedHashMap and LinkedHashSet with simple examples. Now lets see about TreeSet and its difference between HashSet and also how its works. First lets discuss about the main properties of TreeSet class.

  • TreeSet always holds unique values as same as HashSet.
  • TreeSet implements NavigableSet interface which extends the SortedSet interface. 
  • Values stored in TreeSet will be in ascending order by default, hence its won't maintain insertion order as like LinkedHashSet. 
  • If we need to order the values in descending order then we need to use Collections.reverseOrder() as like in below example. 

Now lets see simple example code which shows how it use TreeSet.


import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetTest {

 public static void main(String[] args) {
  
  // By default value will be sorted in ascending order
  Set<String> tsAsc = new TreeSet<String>();

  // To sort values in descending order 
  Set<String> tsDesc = new TreeSet<String>(Collections.reverseOrder());
  
  tsAsc.add("Daniel");
  tsAsc.add("Chris");
  tsAsc.add("Amit");
  tsAsc.add("Bob");
  
  tsDesc.add("Daniel");
  tsDesc.add("Chris");
  tsDesc.add("Amit");
  tsDesc.add("Bob");
  
  // Printing TreeSet values in Ascending order .
  System.out.println("TreeSet values in Ascending order :::::::::::::::");
  Iterator<String> itr1 = tsAsc.iterator();
  while(itr1.hasNext()){
   System.out.println(itr1.next());
  }
  
  // Printing TreeSet values in Descending order .
  System.out.println("TreeSet values in Descending order :::::::::::::::");
  Iterator<String> itr2 = tsDesc.iterator();
  while(itr2.hasNext()){
   System.out.println(itr2.next());
  }
 }
}


OUTPUT:


TreeSet values in Ascending order :::::::::::::::
Amit
Bob
Chris
Daniel

TreeSet values in Descending order :::::::::::::::
Daniel
Chris
Bob
Amit






LinkedHashSet

In our previous tutorial we have discussed about LinkedHashMap and how its works. In this tutorial we will see about LinkedHashSet and what is the difference between HashMap and how its works. Lets list out the properites of LinkedHashSet

  • LinkedHashSet contains only unique values.
  • LinkedHashSet implements Set interface and extends HashSet class. So it acquires all properites of HashSet class.
  • The only difference between HashSet and LinkedHashSet is insertion order. HashSet won't maintain insertion order, were as LinkedHashSet always maintains the insertion order. 

Now lets see simple example which show how to use LinkedHashSet and difference between HashSet.


import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetTest {
 
 public static void main(String[] args) {
  
  Set<String> hs = new HashSet<String>();
  Set<String> lhs = new LinkedHashSet<String>();
  
  hs.add("one");
  hs.add("two");
  hs.add("three");
  hs.add("three");
  hs.add("four");
  
  lhs.add("one");
  lhs.add("two");
  lhs.add("three");
  lhs.add("three");
  lhs.add("four");
  
  // Printing HashSet values.
  System.out.println("HashSet values :::::::::::::::");
  Iterator<String> itr = hs.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
  
  // Printing LinkedHashSet values.
  System.out.println("LinkedHashSet values :::::::::::::::");
  Iterator<String> itr1 = lhs.iterator();
  while(itr1.hasNext()){
   System.out.println(itr1.next());
  }
 }
}

OUTPUT:


HashSet values :::::::::::::::
two
one
three
four

LinkedHashSet values :::::::::::::::
one
two
three
four


In above program we have added 5 values in HashSet and LinkedHashSet with 1 duplicate value "three". Since Set won't allow duplicate value we can see only once "three" has printed. Next if we see the difference between HashSet and LinkedHashSet, insertion order has not followed in HashSet. But LinkedHashSet maintains the insertion order. 




LinkedHashMap

LinkedHashMap is under Java Collection API and it implements Map interface. LinkedHashMap also works as same as HashMap with only 1 difference. Lets see the properties of LinkedHashMap class in Java

  • It works based on key and value as same as HashMap.
  • It implements Map interface and extends HashMap class, so that it acquires all properties of HashMap class. 
  • It can hold 1 null key and multiple null values. 
  • Only difference between HashMap and LinkedHashMap is interstion order. LinkedHashMap maintains the insertion order where as in HashMap its not. 

Now lets see simple example for LinkedHashMap and how to use it and also lets test the insertion order in both collection classes.


import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class LinkedHashMapTest {

 public static void main(String[] args) {
  
  Map<String, String> hm = new HashMap<String, String>();
  Map<String, String> lhm = new LinkedHashMap<String, String>();
  
  hm.put("1", "one"); 
  hm.put("2", "two");
  hm.put("3", "three");
  hm.put("4", "four");
  
  lhm.put("1", "one"); 
  lhm.put("2", "two");
  lhm.put("3", "three");
  lhm.put("4", "four");
  
  // Printing HashMap values.
  System.out.println("HasnMap Key and Value :::::::::::::::");
  Set<Entry<String, String>> set = hm.entrySet();
  Iterator<Entry<String, String>> itr = set.iterator();
  while(itr.hasNext()){
   Map.Entry<String, String> map = itr.next();
   System.out.println(map.getKey() +" : "+map.getValue());
  }
  
  // Printing LinkedHashMap values.
  System.out.println("HasnMap Key and Value :::::::::::::::");
  Set<Entry<String, String>> set1 = lhm.entrySet();
  Iterator<Entry<String, String>> itr1 = set1.iterator();
  while(itr1.hasNext()){
   Map.Entry<String, String> map1 = itr1.next();
   System.out.println(map1.getKey() +" : "+map1.getValue());
  }
 }
}


OUTPUT:


HasnMap Key and Value :::::::::::::::
3 : three
2 : two
1 : one
4 : four

HasnMap Key and Value :::::::::::::::
1 : one
2 : two
3 : three
4 : four


In above program we have added 4 values in HashMap and LinkedHashMap. Next when we print those key and value we can see the difference between both like HashMap insertion order not maintained while printing. Where as in LinkedHashMap its same as insertion order. 

Array in Java

Array in Java

Array is a simple Data Structure as same as which we have read in C, C++. If we need to describe then, "Array is a container which holds fixed no. of values of 1 data type (ie., If its Integer array then we can't store Character or String in it)". Size of the array must be defined at the time of array creation and its fixed until and unless if we try to re-create same array with different size. Lets see simple String array creation example in java.


public class ArrayTest {
 
 public static void main(String[] args) {
  
  // Creating Array with size 5
  String[] array = new String[5];
  
  array[0] = "java";
  array[1] = "J2EE";
  array[2] = "Servlet";
  array[3] = "JSP";
  array[4] = "Web Services";
  
  // Which gives runtime exception
  // ArrayIndexOutOfBoundsException
  //array[5] = "java";
  
  System.out.println("array[0] - "+array[0]);
  System.out.println("array[1] - "+array[1]);
  System.out.println("array[2] - "+array[2]);
  System.out.println("array[3] - "+array[3]);
  System.out.println("array[4] - "+array[4]);
 }
}


OUTPUT: 


array[0] - java
array[1] - J2EE
array[2] - Servlet
array[3] - JSP
array[4] - Web Services


As we seen in above example we can't assign values to "array[5]", since we have created array with the size of 5 and we are trying to store value beyond its size. So we will get run-time exception call ArrayIndexOutOfBoundsException.


Multi-Dimensional Array:

Above we have seen about single dimensional array creation with example. In Java we can use Multi-Dimensional array also as like below.


public class ArrayTest {
 
 public static void main(String[] args) {
  
  String names[][] = { {"thread", "array", "collection"}, 
        {"jsp", "servlet"}, 
        {"SOAP", "RESTFull"} 
          };
  
  System.out.println("names[0][0] - "+ names[0][0]);
  System.out.println("names[1][1] - "+ names[1][1]);
  System.out.println("names[2][0] - "+ names[2][0]);
  System.out.println("names[0][3] - "+ names[0][2]);
  
 } 
}


OUTPUT:


names[0][0] - thread
names[1][1] - servlet
names[2][0] - SOAP
names[0][3] - collection



Array Types:

Not only String we can create array with all primitve and non-primitive data types in Java as like below. 


int[] _int = new int[5];
char[] _char = new char[2];
float[] _flat = new float[4];
Integer[] _Integer = new Integer[5];
Boolean[] _Boolean = new Boolean[4];




Copying array values to another array:

System class method arraycopy() is used to copy array values from 1 array (source) to another array (destination). Both source and destination array must be same data type. arraycopy() method contains 5 parameters like
src - Source array
srcPos - Source array position to copy
dest - Destination array
destPos - Destination array position to be copied 
length - Length of array to copy 

Below is a simple example to copy array value from 1 array to another array.


public class ArrayTest {
 
 public static void main(String[] args) {
  
  int[] _intSrc = new int[]{0,11,12,13,14,15,16,17,18,19};
  
  int[] _intDes = new int[5];
  
  _intDes[0] = 99;
  
  // Copying values from 11 to 14
  System.arraycopy(_intSrc, 1, _intDes, 1, 4);
  
  for (int val : _intDes) {
   System.out.println(val);
  }
 } 
}


OUTPUT:


99
11
12
13
14



Another way of copying values from 1 array to another array using java.util.Arrays() class. Method called copyOfRange() used to copy specific array elements to another array same like below example code.


import java.util.Arrays;

public class ArrayTest {
 
 public static void main(String[] args) {
  
  int[] _intSrc = new int[]{0,11,12,13,14,15,16,17,18,19};
  
  // Copying from _intSrc (Range index 2 to 7)
  int[] _intDes = Arrays.copyOfRange(_intSrc, 2, 7);
  
  for (int val : _intDes) {
   System.out.println(val);
  }
 } 
}


OUTPUT:


12
13
14
15
16










Split() in Java

 
Split in Java

In our earlier tutorial we have seen about String Tokenizer class in Java. And we have given Split method from String class which will be an alternate since String Tokenizer is legacy class. So its recommended to use split method from String class instead of StringTokenizer. So lets see whats the use if split method and how we can use in Java by using simple example. 

Split method used to search for the match as specified in the argument and splits the string and stores into an String array. There are 2 types of split methods in String class,

String str = "Hello how are you";
String arr[] = str.split(" ");

will give output as below, since we are splitting by space " "
Hello
how
are
you



String str = "Hello how are you";
String arr[] = str.split(" ", 2);

will give output as below, here we are requesting to split the string with the array size as 2. so remaining complete string will be stored in last array as below
Hello
how are you


Lets see simple java example with their output.


public class SplitTest {
 
 public static void main(String[] args) {
  String str = "Hello how are you";
  
  String arr[] = str.split(" ");
  for (String string : arr) {
   System.out.println(string);
  }
  
  System.out.println("-------------------------------");
  
  String arr1[] = str.split(" ",3);
  for (String string : arr1) {
   System.out.println(string);
  }
 }
}


OUTPUT:


Hello
how
are
you
-------------------------------
Hello
how
are you