WE PROVIDE ALL

DataTypes in Java

DataTypes:
Data types represent the different values to be stored in the variable. In java, there are two types of data types:
  • Primitive data types
  • Non-primitive data types
DataType
Default Value
Default size
boolean
false
1 bit
char
'\u0000'
2 Byte
Byte
0
1 Byte
Short
0
2 Byte
int
0
4 Bytes
long
0L
8Bytes
float
0.0f
4 Bytes
Double
0.0d
8 Bytes

byte
·        Byte data type is an 8-bit signed two's complement integer
·        Minimum value is -128 (-2^7)
·        Maximum value is 127 (inclusive)(2^7 -1)
·        Default value is 0
·        Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an integer.
·        Example: byte a = 100, byte b = -50
short
·        Short data type is a 16-bit signed two's complement integer
·        Minimum value is -32,768 (-2^15)
·        Maximum value is 32,767 (inclusive) (2^15 -1)
·        Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an integer
·        Default value is 0.
·        Example: short s = 10000, short r = -20000
int
·        Int data type is a 32-bit signed two's complement integer.
·        Minimum value is - 2,147,483,648 (-2^31)
·        Maximum value is 2,147,483,647(inclusive) (2^31 -1)
·        Integer is generally used as the default data type for integral values unless there is a concern about memory.
·        The default value is 0
·        Example: int a = 100000, int b = -200000

long
  • Long data type is a 64-bit signed two's complement integer
  • Minimum value is -9,223,372,036,854,775,808(-2^63)
  • Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
  • This type is used when a wider range than int is needed
  • Default value is 0L
  • Example: long a = 100000L, long b = -200000L
float
·        Float data type is a single-precision 32-bit IEEE 754 floating point
·        Float is mainly used to save memory in large arrays of floating point numbers
·        Default value is 0.0f
·        Float data type is never used for precise values such as currency
·        Example: float f1 = 234.5f
double
·        double data type is a double-precision 64-bit IEEE 754 floating point
·        This data type is generally used as the default data type for decimal values, generally the default choice
·        Double data type should never be used for precise values such as currency
·        Default value is 0.0d
·        Example: double d1 = 123.4
boolean
  • boolean data type represents one bit of information
  • There are only two possible values: true and false
  • This data type is used for simple flags that track true/false conditions
  • Default value is false
  • Example: boolean one = true


char
  • char data type is a single 16-bit Unicode character
  • Minimum value is '\u0000' (or 0)
  • Maximum value is '\uffff' (or 65,535 inclusive)
  • Char data type is used to store any character
  • Example: char letterA = 'A'

Local Variables

·        Local variables are declared in methods, constructors, or blocks.
·        Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
·        Access modifiers cannot be used for local variables.
·        Local variables are visible only within the declared method, constructor, or block.
·        Local variables are implemented at stack level internally.
·        There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.

Instance Variables

·        Instance variables are declared in a class, but outside a method, constructor or any block.
·        When a space is allocated for an object in the heap, a slot for each instance variable value is created.
·        Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
·        Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.
·        Instance variables can be declared in class level before or after use.
·        Access modifiers can be given for instance variables.

Access Control Modifiers

Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are −
  • Visible to the package, the default. No modifiers are needed.
  • Visible to the class only (private).
  • Visible to the world (public).
  • Visible to the package and all subclasses (protected).

Non-Access Modifiers

Java provides a number of non-access modifiers to achieve many other functionality.
·        The static modifier for creating class methods and variables.
·        The final modifier for finalizing the implementations of classes, methods, and variables.
·        The abstract modifier for creating abstract classes and methods.
·        The synchronized and volatile modifiers, which are used for threads.

Java String

In java, string is basically an object that represents sequence of char values. An array of characters works same as java string. For example:

1.    char[] ch={'j','a','v','a','t','p','o','i','n','t'};  
2.    String s=new String(ch);  
is same as:
1.    String s="javatpoint";  
Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.


Collections in Java

Collections :


         List is an interface and it contains Classes of ArrayList and Linked List.

Iterator interface

Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:
  1. public boolean hasNext() it returns true if iterator has more elements.
  2. public object next() it returns the element and moves the cursor pointer to the next element.
  3. public void remove() it removes the last elements returned by the iterator. It is rarely used.


ArrayList class


Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface.
The important points about Java ArrayList class are:
  • Java ArrayList class can contain duplicate elements.
  • Java ArrayList class maintains insertion order.
  • Java ArrayList class is non synchronized.
  • Java ArrayList allows random access because array works at the index basis.
  • In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.
Sample Program:
1.    import java.util.*;  
2.    class TestCollection1{  
3.     public static void main(String args[]){  
4.      ArrayList<String> list=new ArrayList<String>();//Creating arraylist  
5.      list.add("Ravi");//Adding object in arraylist  
6.      list.add("Vijay");  
7.      list.add("Ravi");  
8.      list.add("Ajay");  
9.      //Traversing list through Iterator  
10.   Iterator itr=list.iterator();  
11.   while(itr.hasNext()){  
12.    System.out.println(itr.next());  
13.   }  
14.  }  
15. }  

OutPut:
Ravi
Vijay
Ravi
Ajay

Two ways to iterate the elements of collection in java

There are two ways to traverse collection elements:
  1. By Iterator interface.
  2. By for-each loop.
In the above example, we have seen traversing ArrayList by Iterator. Let's see the example to traverse ArrayList elements using for-each loop.
1.    import java.util.*;  
2.    class TestCollection2{  
3.     public static void main(String args[]){  
4.      ArrayList<String> al=new ArrayList<String>();  
5.      al.add("Ravi");  
6.      al.add("Vijay");  
7.      al.add("Ravi");  
8.      al.add("Ajay");  
9.      for(String obj:al)  
10.     System.out.println(obj);  
11.  }  
12.
OutPut:
Ravi
Vijay
Ravi
Ajay

Example of addAll(Collection c) method:


1.    import java.util.*;  
2.    class TestCollection4{  
3.     public static void main(String args[]){  
4.      ArrayList<String> al=new ArrayList<String>();  
5.      al.add("Ravi");  
6.      al.add("Vijay");  
7.      al.add("Ajay");  
8.      ArrayList<String> al2=new ArrayList<String>();  
9.      al2.add("Sonoo");  
10.   al2.add("Hanumat");  
11.   al.addAll(al2);//adding second list in first list  
12.   Iterator itr=al.iterator();  
13.   while(itr.hasNext()){  
14.    System.out.println(itr.next());  
15.   }  
16.  }  
17. }  

Output:
Ravi
Vijay
Ajay
Sonoo
Hanumat


Example of removeAll() method:


1.    import java.util.*;  
2.    class TestCollection5{  
3.     public static void main(String args[]){  
4.      ArrayList<String> al=new ArrayList<String>();  
5.      al.add("Ravi");  
6.      al.add("Vijay");  
7.      al.add("Ajay");  
8.      ArrayList<String> al2=new ArrayList<String>();  
9.      al2.add("Ravi");  
10.   al2.add("Hanumat");  
11.   al.removeAll(al2);  
12.   System.out.println("iterating the elements after removing the elements of al2...");  
13.   Iterator itr=al.iterator();  
14.   while(itr.hasNext()){  
15.    System.out.println(itr.next());  
16.   }  
17.   
18.   }  
19. }  

Output:

iterating the elements after removing the elements of al2…
Vijay
Ajay

LinkedList class


The important points about Java LinkedList are:
  • Java LinkedList class can contain duplicate elements.
  • Java LinkedList class maintains insertion order.
  • Java LinkedList class is non synchronized.
  • In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
  • Java LinkedList class can be used as list, stack or queue.

 LinkedList Example


1.    import java.util.*;  
2.    public class TestCollection{  
3.     public static void main(String args[]){  
4.      
5.      LinkedList<String> al=new LinkedList<String>();  
6.      al.add("Ravi");  
7.      al.add("Vijay");  
8.      al.add("Ravi");  
9.      al.add("Ajay");  
10.   
11.   Iterator<String> itr=al.iterator();  
12.   while(itr.hasNext()){  
13.    System.out.println(itr.next());  
14.   }  
15.  }  
16. }  

Output:
Ravi
Vijay
Ravi
Ajay





Linked List Example:

package oops;

import java.util.LinkedList;

public class TestCollection {

      public static void main(String[] args) {
            LinkedList <String>li=new LinkedList<String>();
            li.add("Ajay");
            li.addLast("Hari");
            li.add("Bala");
            li.addFirst("Satish");
           
         String s1=li.getFirst();
      System.out.println("The First element is "+s1);
           
            for(String s: li)
            {
                  System.out.println("The elements in the list are  "+s);
            }
      }
}

Output:
The First element is Satish
The elements in the list are  Satish
The elements in the list are  Ajay
The elements in the list are  Hari
The elements in the list are  Bala

Queue:
Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element is removed first and last element is removed at last.

 Object poll():
It is used to retrieves and removes the head of this queue, or returns null if this queue is empty.

Queue Interface declaration:


public interface Queue<E> extends Collection<E>  
Example:
1.    import java.util.*;  
2.    class TestCollection12{  
3.    public static void main(String args[]){  
4.    PriorityQueue<String> queue=new PriorityQueue<String>();  
5.    queue.add("Amit");  
6.    queue.add("Vijay");  
7.    queue.add("Karan");  
8.    queue.add("Jai");  
9.    queue.add("Rahul");  
10. System.out.println("head:"+queue.element());  
11. System.out.println("head:"+queue.peek());  
12. System.out.println("iterating the queue elements:");  
13. Iterator itr=queue.iterator();  
14. while(itr.hasNext()){  
15. System.out.println(itr.next());  
16. }  
17. queue.remove();  
18. queue.poll();  
19. System.out.println("after removing two elements:");  
20. Iterator<String> itr2=queue.iterator();  
21. while(itr2.hasNext()){  
22. System.out.println(itr2.next());  
23. }  
24. }  
25. }  

Output:
Output:head:Amit
       head:Amit
       iterating the queue elements:
       Amit
       Jai
       Karan
       Vijay
       Rahul
       after removing two elements:
       Karan
       Rahul
       Vijay

Set:
    
Set is an interface,In set the classes are Hashset and  Treeset.

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
  • HashSet stores the elements by using a mechanism called hashing.
  • HashSet contains unique elements only.


1.    import java.util.*;  
2.    class TestCollection9{  
3.     public static void main(String args[]){  
4.      //Creating HashSet and adding elements  
5.      HashSet<String> set=new HashSet<String>();  
6.      set.add("Ravi");  
7.      set.add("Vijay");  
8.      set.add("Ravi");  
9.      set.add("Ajay");  
10.   //Traversing elements  
11.   Iterator<String> itr=set.iterator();  
12.   while(itr.hasNext()){  
13.    System.out.println(itr.next());  
14.   }  
15.  }  
16. }  

Output:

Ajay
Vijay
Ravi




 
TreeSet

Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements NavigableSet interface. The objects of TreeSet class are stored in ascending order.
The important points about Java TreeSet class are:
  • Contains unique elements only like HashSet.
  • Access and retrieval times are quiet fast.
  • Maintains ascending order.

import java.util.*;
class TestCollection9{ 
 public static void main(String args[]){ 
  //Creating HashSet and adding elements 
       
       TreeSet<Integer> al=new TreeSet<Integer>(); 
        al.add(100); 
        al.add(98); 
        al.add(67); 
        al.add(50); 
       
        //Traversing elements 
        Iterator<Integer> itr=al.iterator(); 
        while(itr.hasNext()){ 
         System.out.println(itr.next()); 
     } 
}
}

Output:
50
67
98
100




import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample {

   public static void main(String[] args) {
        System.out.println("Tree Set Example!\n");
        TreeSet<Integer> tree = new TreeSet<Integer>();
        tree.add(12);
        tree.add(63);
        tree.add(34);
        tree.add(45);

        // here it test it's sorted, 63 is the last element. see output below
        Iterator<Integer> iterator = tree.iterator();
        System.out.print("Tree set data: ");

        // Displaying the Tree set data
        while (iterator.hasNext()) {
               System.out.print(iterator.next() + " ");
        }
        System.out.println();

        // Check empty or not
        if (tree.isEmpty()) {
               System.out.print("Tree Set is empty.");
        } else {
               System.out.println("Tree Set size: " + tree.size());
        }

        // Retrieve first data from tree set
        System.out.println("First data: " + tree.first());

        // Retrieve last data from tree set
        System.out.println("Last data: " + tree.last());

        if (tree.remove(45)) { // remove element by value
               System.out.println("Data is removed from tree set");
        } else {
               System.out.println("Data doesn't exist!");
        }
        System.out.print("Now the tree set contain: ");
        iterator = tree.iterator();

        // Displaying the Tree set data
        while (iterator.hasNext()) {
               System.out.print(iterator.next() + " ");
        }
        System.out.println();
        System.out.println("Now the size of tree set: " + tree.size());

        // Remove all
        tree.clear();
        if (tree.isEmpty()) {
               System.out.print("Tree Set is empty.");
        } else {
               System.out.println("Tree Set size: " + tree.size());
        }
   }
}
Output:
Treeset  Example
Tree set Data :12 34 45 63
Tree set size : 4
First  Data: 12
Last Data: 63
Data is removed from the  Treeset
Now the  tree set contain : 12  34 63
Now the size of tree set : 3
Tree set is Empty.


HashMap:
Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap class and implements Map interface.
The important points about Java HashMap class are:
  • A HashMap contains values based on the key.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It maintains no order.

HashMap class Parameters

Let's see the Parameters for java.util.HashMap class.
  • K: It is the type of keys maintained by this map.
  • V: It is the type of mapped values.


Methods:
Set entrySet() : It is used to return a collection view of the mappings contained in this map.
Set keyset() : It is used to return a set view of the keys contained in this map.


1.    import java.util.*;  
2.    class TestCollection13{  
3.     public static void main(String args[]){  
4.      HashMap<Integer,String> hm=new HashMap<Integer,String>();  
5.      hm.put(100,"Amit");  
6.      hm.put(101,"Vijay");  
7.      hm.put(102,"Rahul");  
8.      for(Map.Entry m:hm.entrySet()){  
9.       System.out.println(m.getKey()+" "+m.getValue());  
10.   }  
11.  }  
12. }  

Output :
102 Rahul
100 Amit
101 Vijay




import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Details {

   public static void main(String args[]) {

      /* This is how to declare HashMap */
      HashMap<Integer, String> hmap = new HashMap<Integer, String>();

      /*Adding elements to HashMap*/
      hmap.put(12, "Chaitanya");
      hmap.put(2, "Rahul");
      hmap.put(7, "Singh");
      hmap.put(49, "Ajeet");
      hmap.put(3, "Anuj");

      /* Display content using Iterator*/
      Set set = hmap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry mentry = (Map.Entry)iterator.next();
         System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
         System.out.println(mentry.getValue());
      }

      /* Get values based on key*/
      String var= hmap.get(2);
      System.out.println("Value at index 2 is: "+var);

      /* Remove values based on key*/
      hmap.remove(3);
      System.out.println("Map key and values after removal:");
      Set set2 = hmap.entrySet();
      Iterator iterator2 = set2.iterator();
      while(iterator2.hasNext()) {
          Map.Entry mentry2 = (Map.Entry)iterator2.next();
          System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
          System.out.println(mentry2.getValue());
       }

   }
}
Output:
key is: 49 & Value is: Ajeet
key is: 2 & Value is: Rahul
key is: 3 & Value is: Anuj
key is: 7 & Value is: Singh
key is: 12 & Value is: Chaitanya
Value at index 2 is: Rahul
Map key and values after removal:
Key is: 49 & Value is: Ajeet
Key is: 2 & Value is: Rahul
Key is: 7 & Value is: Singh
Key is: 12 & Value is: Chaitanya

The Map.Entry interface enables you to work with a map entry.
The entrySet( ) method declared by the Map interface returns a Set containing the map entries. Each of these set elements is a Map.Entry object.


TreeMap:
Java TreeMap class implements the Map interface by using a tree. It provides an efficient means of storing key/value pairs in sorted order.
The important points about Java TreeMap class are:
  • A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • It contains only unique elements.
  • It cannot have null key but can have multiple null values.
  • It is same as HashMap instead maintains ascending order.
Example:
1.    import java.util.*;  
2.    public class TreeMapExample {  
3.       public static void main(String args[]) {  
4.       // Create and populate tree map  
5.       Map<Integer, String> map = new TreeMap<Integer, String>();           
6.       map.put(102,"Let us C");  
7.       map.put(103"Operating System");  
8.       map.put(101"Data Communication and Networking");  
9.       System.out.println("Values before remove: "+ map);    
10.    // Remove value for key 102  
11.    map.remove(102);  
12.    System.out.println("Values after remove: "+ map);  
13.    }      
14. }  

Output:
Values before remove: {101=Data Communication and Networking, 102=Let us C, 103=Operating System}
Values after remove: {101=Data Communication and Networking, 103=Operating System}