Map Entry Collection Framework in JAVA


Map Entry is a nested interface of map implimentation of which is provided by all the map implimenting classes.

This interface provides following methods:-

=> getKey() : is used to obtain reference of key from entry object.
Syntax : public Object getkey();

=> getValue() : is used to otain the reference of the value object from entry object.
Syntax : public Object getValue();

HashMap and TreeMap classes provides implementation of map interface through abstract Map class. The difference between HashMap and TreeMap is in their underline data structure.
HasMap usese HashTable and the TreeMap uses BinarySearch tree for storing elements.

Example: Map.Entry and HashMap

import java.util.*;
class TreeMapTest
{
public static void main(String args[])
{
  Map.Entry m;
  HashMap map = new HashMap();
  map.put("India","New Delhi");
  map.put("Pakistan","Islamabad");
  map.put("Nepal","Kathmandu");
  map.put("Japan","Tokyo");
  System.out.println("Totla no's of entries in map are : "+map.size());
  Set s = map.entrySet();
  Iterator itr = s.iterator();
  while(itr.hasNext())
  {
    m = (Map.Entry)itr.next();
    System.out.println(m.getKey()+"t"+m.getValue());
  }
  System.out.println("Press Ctrl+C to terminate...");
  Scanner in = new Scanner(System.in);
  System.out.println("Enter country name to find out capital : ");
  while(true)
  {
    String key = in.nextLine();
    System.out.println("Captial is : "+map.get(key));
  }
}
}

Output:


Collection Framework in Java - Set Interface


Set : This interface doesn't difine any additional methods after extending collection. All the implementation of set defines add methods in such a way that duplicat element are not added i.e. a set in a named index collection of unique element.

Hash Set and Tree Set clases produce implementation of set interface through abstract class. Basic difference between hash set and tree set is in their undefined data structure.

Hash set uses a has table for string element and tree set uses binary search tree.

Example : TreeSet Or Hash Set

Map : A map is a collection of paired element in a map values are stored by associating them to a key which act as an index.
Map interface describe the functionality of a map. IT contains follwing methods.

=> Put() : used to store keyvalue pair in a map.
Syntax : public boolean put(object key);

=> get() : used to obtain a value of a map.
Syntax : public Object get(Objec key);

=> remove() : is used to remove a key value paired from a map.
Syntax : public Object remove(Object key);

=> containKey() : is used to search a key from a map.
Syntax : public boolean containKey(Object key);

=> catains() : is used to search a value from a map.
Syntax : public Object contains(Object key);

=> size() : used to find out a number of entries in a map.
Syntax : public int size();

=> clear() : used to remove all the entries from the map.
Syntax : public Map clear();

=> keySet() : returns a set valur for all the key of map.
Syntax : public set keySet();




=> entrySet() : returns a set view for all the entries of map.
Syntax : public Set entryeSet();


TreeSet Example in JAVA

Example of TreeSet in Collection Framework

import java.util.*;
class TestTreeSet
{
public static void main(String args[])
{
    TreeSet set = new TreeSet();
  set.add("JAVA");
  set.add("J2EE");
  System.out.print("Result of adding J2ME fro first lin : "+set.add("J2ME"));
  set.add("Spring');
  set.add("Android");
  System.out.println("Size of the set is "+set.size());
  System.out.print("Result of adding J2ME for second time : "+set.add("J2ME"));
  Iterator itr = set.iterator();
  while(itr.hasNext())
  {
    System.out.println(itr.next());
  }
}
}

br />

Example of HasSet in Collection Framework


import java.util.*;
class TestHashSet
{
public static void main(String args[])
{
    HashSet set = new HashSet();
  set.add("JAVA");
  set.add("J2EE");
  System.out.print("Result of adding J2ME fro first lin : "+set.add("J2ME"));
  set.add("Spring');
  set.add("Android");
  System.out.println("Size of the set is "+set.size());
  System.out.print("Result of adding J2ME for second time : "+set.add("J2ME"));
  Iterator itr = set.iterator();
  while(itr.hasNext())
  {
    System.out.println(itr.next());
  }
}

Array List Example in java

import java.util.*;
class TestList
{
public static void main(String args[])
  {
  ArrayList list = new ArrayList();
  list.add("Mon");
  list.add("Wed");
  list.add("Thu");
  list.add("Fri");
  list.add("Sat");
  list.add("Sun");
  list.add(1,"Tue");
  System.out.println("Total no's of element in list is : '"+list.size());
  System.out.println("Contents of list are : ");
  Iterator itr = list.iterator();
  while(itr.hasNext())
  {
    System.out.println(itr.next());
  }
  System.out.println("Removing Sun from list.");
  list.remove("Sun");
  System.out.println("No's of elements after removal is : '"+list.size());
  System.out.println("Searching results of Fri : "+list.contains("Fri"));
}
}



Output :


Java collections framework

Collection Framework is the set of classes and interfaces provided by sun microsystem which provides a unified module for working with collection of objects.

java.util package contain classes and interfaces of collection framework. At the core of collection framework it is named java.util.Collection
This interface difines functionality common to all collection.

=> add() : is used to add an element to a collection.
syntax : public boolean add(Object o);

=> addAll() : is used to add all the elements of one collection into another.
syntax : public boolean addAll(Collection C);

=> remove() : is used to remove an element from a collection.
syntax : public boolean remove(Object o);

=> removeAll() : is used to remove all the elements of one collection from another.
syntax : public boolean removeAll(Collection c);




List : This interface extends collection and adds the functionality of indexing to it.

Methods added by list interface:-
=> add() : is used to insert an element to a list.
Syntax : public boolean add(int index, Object element);

=> addAll() : is used to insert all the elements of one collection into a list.
Syntax : public booleanaddAll(int index, Collection c);

=> remove() : is used to remove an element stored at the given position int the list.
Syntax : public boolean remove(int index);

=> get() : is used to obtain element stored at the given position in the list.
Syntax : public Object get(int index);

=> indexOf() : is used to find out index of first occurance of the given element in the list.
Syntax : public int indexOf(Object o);

=> lastIndexOf() : is used to find out the inded of last occurance of the given element in the list.
Syntax : public int lastIndexOf(Object element);

Some other methods of collection interface:


=> retainAll() : is used to remove all the elements of the invoking collection which are not path of the given collection.
Syntax : public boolean retainAll(Collection c);

Difference between remove() and retainAll().





=> contans() : is used to search an element in a collection.
Syntax : public boolean contains(Object element);

=> containAlll() : is used to search all the element of one collection into another.
Syntax : public boolean containAll(Collection c);

=> size() : used to find out number of element in a collection.
Syntax : public int size();

=> clear() : is used to clear or remove all the elements of the collection.
Syntax : public void clear();

=> iterator() : returns an itreator for traversing the element of the collection.
Syntax : public Iterator iterator();

Iterator is an interface of collection framework which provides an implements independent method of traversing the element of collection

Methods of iterator interface are:

=> hasNext() : is used to find out whether there is an element to be travers or not.
Syntax : public boolean hasNext();

=> next() : is used to obtain the reference of next element from the collection.
Syntax : public Object next();

=> remove() : is used to remove last traversed element from the collection.
Syntax : public void remove();



ListIterator

=> listIterator() : method of List interface returns a list itreator for traversing the element of a list.
Syntax : public ListIterator listIterator();
public ListIterator listIterator(int index);

=> ListIterator : it is an extension of iterator which supports by directional traversing.

Following methods are added to this interface:
=> hasPrevious() : is used to find out whether there is an element behind current index or not.
Syntax : public boolean hasPrevious();

=> previous() : is used to obtain the reference of the previous element of list.
Syntax : public Object previous();

ArrayList : this class provides the implementation of list interface through abstract List class. An array list object represents the dynamic array.

Classes Objects and Members

Defining Our Class : The journal syntax of class definition is as follows :

class ClassName extends SuperClassName
{
           [Fields declaration]
           [Method declaration]
}
Everything inside the square bracket is optional.
class Empty
{
}
C++ Programmers may note that there is no semicolon(:) at the end of the class.

Field Declaration : The fields that is declared inside a class is called instance variable because they are created whenever an object of the class is instantiated.
           Instance variable are also known as member variables.

Example :
Class Rectagle
{
           int length;
           int breadth;
}

           Instance member represent attributes and behaviour of individual objects by default all the members of the class and instance member.

Labelled Loop

Labelled Loop : In java we can give a label to block of statements. To give a label to a loop, place it before the loop the loop with a colon(:) at the end.

Syntax : Label : for(.... ; .... ; .... )
                        {
                                 -----------------
                                 -----------------
                        }

class TestLabel
{
            public static void main(String args[])
            {
                        int i , j;
                        x: for(i = 0; i<2; i++)
                        {
                                    for(j=0; j<3; j++)
                                    {
                                                if(i == j)
                                                            continue x;
                                                System.out.println("Loop");
                                    }
                        }
            }
}

For Loop

Given below is example of For Loop. To print a series of Asteric (*) symbol in right angle triangle shape. We can make all other type of triangles using for loop or other loops(While or Do While). This is very interesting program for beginners :-)

class Triangle
{
           public static void main(String args[])
           {
                      int i, j;
                      for(i = 0; i <= 5; i++)
                      {
                                 for(j = 0; j <= i; j++)
                                 {
                                            System.out.println(" * ");
                                 }
                                 System.out.println();
                      }
           }
}


Output :

*
*  *
*  *  *
*  *  *  *
*  *  *  *  *


Exercise programs with for loop:

WAP to print the table of a number in a proper format.
WAP to find out all even number between 1 to 50.
WAP to find all odd number between 1 to 40.
WAP to find out factorial of a no.
WAP to print the reverse of a number.
WAP to find out all Armstrong number between 1 to 1000.
WAP to check whether a number is palindrome or not.
WAP to print all palindrome number between 1 to 100.
WAP to check whether a number is prime or not.
WAP  to print all prim numbr between 1 to 50.
WAP to print first 25 Fibonacci series.

Exercise questions of If else and switch case


1.        WAP to check whether a number is even or odd.
2.        WAP to check whether character is vowel or consonant.
3.        WAP to check whether the age of a user is eligible for vote or not.
4.        WAP to check whether the student passed with distinction without distinction or failed.
5.        WAP to check character and display the corresponding name of the color(RGB).
6.        WAP to display the name of the day according to the number of days(By using Else if ladder
           and switch).
7.        WAP to print name of the month according to the number of the month(using else if ladder
           and switch).
8.        WAP to display the grade of student according to marks.

Operators


Operators are special symbols that tells the computer to preform certain mathematical and logical manipulation.

Arithmetic Operators
Operator         Meaning
      +               Addition
      -               Subtraction
      *               Multiplication
      %              Modulo Division(Used to returns Remainder)
      /               Division

Note : Unlike C and C++ in java modulo operator can be applied to the floating point data as well.

Relational Operator : These operators is used to compose two or more quantities.
Type Operator     Meaning
         <                Less then
         <=              Less then equals to
         >                Greater then
         >=              Greater then equals to
         ==              Equals to
         !=               Not Equals to

Switch Statement And If Else Ladder

Java has a builin multiway decision statement known as switch. The switch statement test the value of a given variable(Expression against a list of case values and when a match is found, a block of statement associated with the case is executed. The journal syntax of switch is:

switch(Expression)
{
            case value1:
                        block1;
                        break;
            case value2:
                        block2;
                        break;
            -----------------------
            -----------------------
            -----------------------
            default:
                        default block;
                        break;
}

The expression is an integer expression of characters value1, value2 are constant or constant expression and are know as case labels. Each of these values should be unique with in a switch statement.

class SwitchTest
{
            public static void main(String args[])
            {
                        int x = 2;
                        switch(x)
                        {
                                    case 1:
                                                System.out.println("One");
                                                break;
                                    case 2:
                                                System.out.println("Two");
                                                break;
                                    case 3:
                                                System.out.println("Three");
                                                break;
                                    default:
                                                System.out.println("Invalid");
                                                break;
                        }
            }
}


Else If Ladder : The general syntax of else if ladder is as follow:

if(condition)
{
          statement1;
}
else if(condition)
{
          statement2;
}
else if(condition)
{
          statement3;
}
else
{
          statement4;
}

Example:

class IfElseTest
{
          public static void main(String args[])
          {
                    int i = 0;
                    if(i == 0)
                              System.out.println("Zero bit");
                    else if(i == 1)
                              System.out.println("One bit");
                    else
                              System.out.println("Invalid Bit");
          }
}

Output : 

Case And Wildcards

The case statement matches an expression with multiple alternatives. This is similar to the switch-case construct to of C/C++. The general from of the case construct is:

case "$variable" in
            condition 1) commands;;
            condition 2) commands;;
            -----------------------
            -----------------------
            -----------------------
condition n) commands
esac

Note : That each alternative ends with a) and each condition block with two semicolons (;;). The last condition block need not be terminated with ;;. The case block ends with esac (case spelled backwards).

Example of case statement:

#stored in file case.sh
echo "Press any key"
read key
echo "You have typed a"
case "$key" in
            [a-z]) echo "lowercase letter";;
            [A-Z]) echo "uppercase letter";;
            [0-9]) echo "digit";;
            *) echo "punctuation, space or any other key"
esac

Output:



This shell script matches the character typed by the user with the specified alternatives and performs the actions (commands) corresponding to the matched argument.


Note: The * has got double meaning if used int the case construct. When used as part of a pattern it functions as a wild-card and when used as the last option it matches a value not matched by the previous options. If no match is found, the command following this option (*) is executed.

#stored in file case1.sh
read i
echo "$i is "
case $i in
            [1-9]*) echo "a positive value";;
            [-]*) echo "a negative value";;
            [0]) echo "zero";;
            *) echo "not a number"
esac

Output:

Simple calculation programs


Program to calculate the celcius if given f is 20. Given program will calcuate the celcius if the Fahrenheit is given. Fahrenheit is initialized already.

class Celsius
{
public static void main(String args[])
{
int f = 20;
float c;
System.out.println("F is : "+f);
c = (f - 32)/1.8f;
System.out.println("Celcius is : "+c);
}
}



Program to display the reverse of 125 without loop.


class ReverseDigit
{
public static void main(String args[])
{
int n,r;
n = 125;
r = n%10;
System.out.print(r);
n = n / 10;
r = n % 10;
System.out.print(r);
n = n / 10;
r = n % 10;
System.out.print(r);
}
}

Test Statement



The test statement tests a given condition.It returns 1 if the condidion is false and returns 0 if the condition is true. IT uses certain operators, known as test operations, for comparison. For example, -eq is used for "equal to", -gt for "greater than" etc. Some of thes test operators are listed given below.

Let us study the following command sequence:

a = 10;
b = 20;
test $b  -gt $a
echo $?
#20 is greater than 10
test $a -eq $b
echo $?
#20 is not equal equal to 10

Note the use of test in the above sequesnce. These should be spaces on either side of the test operators. We have used $? to find out the result of the test command and its values conveyed whether the previous command returned tru (0) or false (1).
The test word can be replaced by used of [ ] enclosing the condidion within brackerts as follows:

a = 10;
b = 20;
[ $b -gt $a ]
echo $?
# 20 is greater than 10
[ $a -eq $b ]
echo $?
# 20 is not equal to 10

Note that there must be spaces on either side of [ and ].

Operator                               Implies
-eq                                        equal to
-ne                                        not equal to
-gt                                        greater than
-lt                                         less than
-ge                                       greater than or equal to
-le                                        less than or equal to
-n str                                    string str is not a null string
str                                        same as above
-z str                                    string str is a null string
str1= str2                             string str1 is equal to str2
str1 ! = str2                          string str1 is not equal to str2

if construct often uses test statements as condition. For example, the following script-segment:

a =10;
b = 20;
if test $b -gt $a
then
echo "b is greater than a"
else
echo "b is not greater than a"
fi

Nested if-else-fi

The if-else construct can be nested. For example, the following is a nested if conditional that displays the corresponding of a day:


echo -n "Enter value in range of 1 to 7 : "
read a
if [ $a -eq 1 ];
then
         echo "Sunday"
else if [ $a -eq 2 ];
then
         echo "Monday"
else if [ $a -eq 3 ];
then
         echo "Tuesday"
else if [ $a -eq 4 ];
then
         echo "Wednesday"
else if [ $a -eq 5 ];
then
         echo "Thursday"
else if [ $a -eq 6 ];
then
         echo "Friday"
else if [ $a -eq 7 ];
then
         echo "Saturday"
else
         echo "You entered an invalid number"
fi fi fi fi fi fi fi



The else if can be replaced by elif, i.e. elif is a constructor of else if. Therefore above sequence can be written as:


echo -n "Enter value in range of 1 to 7 : "
read a
if [ $a -eq 1 ];
then
         echo "Sunday"
elif[ $a -eq 2 ];
then
         echo "Monday"
elif[ $a -eq 3 ];
then
         echo "Tuesday"
elif[ $a -eq 4 ];
then
         echo "Wednesday"
elif[ $a -eq 5 ];
then
         echo "Thursday"
elif[ $a -eq 6 ];
then
         echo "Friday"
elif[ $a -eq 7 ];
then
         echo "Saturday"
else
         echo "You entered an invalid number"
fi


 Note : that elif did not require a corresponding terminating fi statment.

Swap two variables without using third variable

Write a program to swap the data of two variables A and B without using third variable in java.
There is no input taken at runtime by user. The A and B is declared and initialized in the program.

class swap
{
          public static void main(String ars[])
          {
                    int A = 10;
                    int B = 20;

                    System.out.println("A Before Swap = "+A);
                    System.out.println("B Before Swap = "+B);

                    A = A + B;

                    B = A - B;
                    A = A - B;


                    System.out.println("A After Swap = "+A);
                    System.out.println("B After Swap = "+B);
          }

}


Sum of two numbers

Here is the simple program to add two numbers and store output in third variable. Given below it the program to add two number which doesn't take input from user. The variables are declared and initialized.

class sum
{
         public static void main(String args[])
         {
                  int a, b, c;
                  a = 10;
                  b = 20;
                  c = 30;
                  System.out.print("Sum of the given number is : "+c);
         }
}


Data Types and Type Casting

There are following types of data type in java as follows:-
Type of Variable                                  Default Value
         byte                                                   0
         short                                                  0
         int                                                      0
         long                                                   0L
         float                                                   0.0f
         double                                                0.0d
         char                                                   null character
         boolean                                              false(0)
         reference                                            null

The concept of default values is applicable on the variables that is declared in a class not in a method.

Casting:
         The process of converting one dataype to another is called casting.

Example:
         float a:
         a = (int)125.45+25;


Explanation of a simple java program


1).   Class declaration:- As strored erlier, Java isa true object oriented language and therefore everything must be placed inside a class, class is the keyword and declares that a new definition follows:

2). Mainline:-
a. public : The keyword public is an access spefieds that declares the main methods as
           uprtotected and therefore making it accessable to all other classes.
b. static : Static keyword declares this method as one that belongs to the entire class not a part
           of any object of class. The main text always be declares as static.
  In a java program metod as well as variables can be of static type.
c. void main : When a funciton directly does not return any value the it is called as void main.
d. String args[] : This statement declares a parameter named args[[, which contains an array
           of object of the class type string.

First simple program in java

First simple program in java for beginners.


class FirstProgram
{
         public static void main(String args[])
         {
                  System.out.print("This is my first simple program in java.");
         }
}

How to compile the simple program of java.

  • Save the above program with name FirstProgram.java the program should save with the same name as the class name where the public static void main method is defined.
  • Then open the command prompt go to the directory where you saved the file on your pc.
  • Then write the command to compile the program as javac FirstProgram.java hit enter key.
  • Then write the command to run the program as java FirstProgram and hit enter to execute the command or program.
The output will be as follows :-



 Keep following these steps and have happy coding and programming with java.