Let's learn java programming language with easy steps. This Java tutorial provides you complete knowledge about java technology.

Sunday, 21 May 2017

Java LinkedHashSet

 

Java LinkedHashSet Class

Java LinkedHashSet is a class in java collection. LinkedHashSet class implements set interface like HashSet class in Java. LinkedHashSet extends(inherit) HashSet class.


Some Important Points About LinkedHashSet Class

  • LinkedHashSet class doesn't contains duplicate values. It contains only unique values like HashSet class in java.
  • LinkedHashSet class maintains insertion order.
  • LinkedHashSet class in not synchronized.
  • LinkedHashSet class allows null values.
  • By using foreach loop and Iterator interface, We can retrieve an elements from LinkedHashSet class.

Hierarchy of LinkedHashSet Class

LinkedHashSet


Here in the above diagram, class LinkedHashSet extends HashSet class and HashSet class extends Abstract set class and AbstractSet class implements set interface.

Constructors of LinkedHashSet Class

There are some constructors of linkedhashset class in java. These are:

1) HashSet()

It makes a default HashSet.

2) HashSet(Collection c)

This constructor is used to initialize the hash set by using the elements of collection c.

3) LinkedHashSet(int capacity)

This constructor is used to initialize the hash set to the given integer value capacity.

4) LinkedHashSet(int capacity, float fillRatio)

This constructor is used to initialize both integer and float values.


Java LinkedHashSet Example

This is simple example of LinkedHashSet class in java collection framework.

import java.util.*;
class LinkedHashSetExample
{
public static void main(String args[])
{
//creating LinkedHashSet
LinkedHashSet<String> lhs = new LinkedHashSet<String>();
lhs.add("java");
lhs.add("python");
lhs.add("c++");
lhs.add("java");//duplicate value
lhs.add("html");

//Iterate all the elements from LinkedHashSet
Iterator itr = lhs.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}


output : java
              python
              c++
              html

In the above example we can see it is not containing duplicate values. It maintains insertion order.

Java LinkedHashSet Example 2

This is another example of linked hash set. In this example we will print String values and Integer values. Let's start

import java.util.LinkedHashSet;
class Example2
{
public static void main(String args[])
{
//print String values
LinkedHashSet<String> lhs = new LinkedHashSet<String>();
lhs.add("amit");
lhs.add("karan");
lhs.add("amit");
lhs.add("varun");
lhs.add("arjun");

System.out.println(lhs);

//print Integer values
LinkedHashSet<Integer> lhs1 = new LinkedHashSet<Integer>();
lhs1.add(100);//Integer values
lhs1.add(101);
lhs1.add(102);
lhs1.add(100);
lhs1.add(103);

System.out.println(lhs1);
}
}

output : [amit, karan, varun, arjun]
              [100, 101, 102, 103]



Java LinkedHashSet ForEach Example

In this linked hash set example, we are going  to use for each loop for retrieve all the elements.


import java.util.LinkedHashSet;

class Example2
{
public static void main(String args[])
{
//print String values
LinkedHashSet<String> lhs = new LinkedHashSet<String>();
lhs.add("amit");
lhs.add("karan");
lhs.add("amit");
lhs.add("varun");
lhs.add("arjun");

System.out.println("String Values");

//using for each loop
for(String s : lhs)
{
System.out.println(lhs);
}

//print Integer values
LinkedHashSet<Integer> lhs1 = new LinkedHashSet<Integer>();
lhs1.add(100);//Integer values
lhs1.add(101);
lhs1.add(102);
lhs1.add(100);
lhs1.add(103);

System.out.println("Integer Values");


//using for each loop

for(Integer i : lhs1)
{
System.out.println(lhs1);
}
}

}

output : String Values
              amit
              karan
              varun
              arjun


             Integer Values

             100
             101
             102
             103 


Difference Between HashSet and LinkedHashSet Class

HashSet : Java HashSet class doesn't maintains insertion order of an elements.

LinkedHashSet : Java LinkedHashSet class maintains insertion order of an elements.

Difference Between HashSet and ArrayList Class

HashSet : Java HashSet class does not allow duplicate elements. HashSet does not maintains insertion order.

ArrayList : Java ArrayList class take duplicate elements. ArrayList maintains insertion order of an elements.


Share:

Wednesday, 17 May 2017

Java Throw Keyword In Exception Handling

 Throw

throw

Java throw is a keyword in java, Which is used to throw an exception explicitly and used with the mostly custom exception.

In java, We have many predefined exceptions like ArithmeticException, ArrayIndexOutOfBoundsException but programmers can create a new exception and throw it explicitly. These exceptions are called user-defined exception. By the help of throw keyword in exception handling we can throw user defined exception in java.

By the help of throw keyword, we can throw both checked and unchecked exception in java. Java throw keyword is mainly used to throw custom exceptions.

Syntax of throw keyword 

throw exception;


Java throw Keyword Example

This is a very simple example of java throw keyword. In this example we will check the candidate's age is 18 or not, if he will less than 18 we will throw an ArithmeticException otherwise welcome to vote.

class ThrowKeywordExample
{
public void check(int age)
{
if(age<18)
{
throw new ArithmeticException("Age is not valid");
}
else
{
System.out.println("Your welcome to vote");
}
}
public static void main(String args[])
{
ThrowKeywordExample t = new ThrowKeywordExample();
t.check(11);
}
}

output : Exception in thread "main" java.lang.ArithmeticException : Age is not valid.

Note : throw keyword is always used within a method body.


Another throw Example 

class AnotherExampleOfThrow
{
static int sum(int num1, int num2)
{
if(num1 == 0)
{
throw new ArithmeticException("parameter first is not valid");
}
else
{
System.out.println("both parameter are correct");
return num1 + num2;
}
}
public static void main(String args[])
{
int result = sum(0,10);
System.out.println(result);
System.out.println("continue next statements");
}
}

output : Exception in thread "main" java.lang.ArithmeticException : parameter first is not valid.



Exception Propagation 

In exception propagation, An exception thrown from the top of the stack and if it is not caught, its drops down the call stack to the previous method, and again if not caught there , the exception again drops down to the previous method and so on until they are caught.

Example of Exception Propagation in Java

class ExampleOfEP
{
void a()
{
int i = 30/0;//Exception Occurred
}
void b()
{
a();
}
void c()
{
try
{
b();
}
catch(Exception e)
{
System.out.println("Exception Handled");
}
}
public static void main(String args[])
{
ExampleOfEP ee = new ExampleOfEP();
ee.c();
}


output : Exception Handled

In the above example, Exception are occurred in method a() and it is not handled here so it is propagated to method b() and here it not handled, so it is propagated to  method c where this exception is handled easily.

Exception can be handled in any method even in main method.

Note : Unchecked Exceptions are forwarded in calling chain by default.


By default checked Exception are not forwarded in calling chain

By default checked exceptions are not forwarded in calling chain but we can forward checked exception in calling chain through throws keyword. We will learn throws keyword in later.

This below example, give compilation error because checked exception cannot be forwarded in calling chain.


class Test
{
void a()
{
throw new java.io.IOException("device error");//Checked Exception
}
void b()
{
a();
}
void c()
{
try
{
b();
}
catch(Exception e)
{
System.out.println("Exception Handled");
}
}
public static void main(String args[])
{
Test ee = new Test();
ee.c();
}

Share:

Monday, 15 May 2017

Java HashSet

 

Java HashSet Class

HashSet is a class in java collection framework. Java HashSet  class implements Set interface and extends AbstractSet class in java.


Points About HashSet Class in Java

  • HashSet class implements Set interface and extends AbstractSet class.
  • HashSet class doesn't contains duplicate elements.
  • HashSet doesn't maintains the insertion order.
  • HashSet class in non-synchronized.
  • HashSet allow null values.
  • HashSet using hash table for storing the elements in collection.
  • HashSet class implements Serializable and Cloneable interfaces.

Hierarchy of HashSet Class

Java HashSet


In the above hierarchy, HashSet extends AbstractSet class and AbstractSet class implements Set interface.


Constructor of HashSet Class

1) HashSet()

Creates an empty HashSet in Java.

2) HashSet(Collection c)

This constructor is used to initialize the hash set by using the elements of the collection c.

3) HashSet(int capacity)

This constructor is used to initialized the hash set to the given integer value capacity.

4) HashSet(int capacity, float fillRatio)

This constructor is used to initialize both integer and float values. fillRatio also called load capacity).


Methods of Java HashSet Class

There are some useful methods of java hash set class.

1) boolean add(Object o)

This method is used to add the elements to the set.

2) void clear()

This method removes all the elements from the set.

3) boolean contains(Object o)

This method checks the specified elements in the set if specified elements found in the set its return true otherwise false.

4) boolean isEmpty()

If there is no elements in the set , it returns true otherwise return false.

5) Object clone()

This method returns a shallow copy of the HashSet .

6) int size()

This method tells the number of elements in the set.



Difference Between Set and List Interface

Set : Set interface does not contains duplicate elements.

List : List interface contains duplicate elements.


Java HashSet Example

Here are simple program of java hash set class in collection.

import java.util.*;
class HashSetExample
{
public static void main(String args[])
{
//creating HashSet
HashSet<String> hs = new HashSet<String>();
hs.add("red");//adding elements in the set
hs.add("yellow");
hs.add("red");
hs.add("pink");
hs.add("blue");

//Iterate the elements
Iterator i = hs.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}

output : red
              pink
              blue
              yellow

Note : As we know HashSet doesn't contains duplicate elements and doesn't maintains insertion order of elements.


Java HashSet Example 1

This is another example of hash set class with null values. Let's take a look at below example


import java.util.*;

class HashSetExample
{
public static void main(String args[])
{
//creating HashSet
HashSet<String> hs = new HashSet<String>();
hs.add("red");//adding elements in the set
hs.add("yellow");
hs.add("red");
hs.add("pink");
hs.add("blue");


//adding null values

hs.add(null);
hs.add(null);

//printing hash set

System.out.println(hs);



}

}

output : [ red, null, pink, blue, yellow]

Note : In the above example there is no duplicate values in this list including null values.

Q. We can display the duplicate values in HashSet class ?

Ans. No, We can't display the duplicate values in hash set class in java.

Q. HashSet maintains insertion order, yes or not ?

Ans. HashSet does not maintains insertion order of an elements.



Share:

Monday, 8 May 2017

Array Programs In Java

Here we will learn about some most important java array programs. Which is mostly asked in interviews. In the previous chapter, we learned some basic programs in java and String programs in java. Now we will array programs in java programming.


Array Programs In Java



1) Single Dimensional Array In Java

This is very simple program in java array. This is starting point of java array.

class Simple
{
public static void main(String args[])
{
int a[] = new int[5];//declaration and instantiation of array
a[0] = 1;//initialization of an array
a[1] = 2;
a[2] = 3;
a[3] = 4;
a[4] = 5;

//print array
for(int i = 0; i<a.length; i++)
{
System.out.println(a[i]);
}
}


output : 1
              2
              3
              4
              5


2) Multidimensional Array In Java

This is a multidimensional program in java array.

class SimplePrograms
{
public static void main(String args[])
{

//declaration, instantiation, initialization of array
int a[][] = { {1,2,3}, {4,5,6}, {7,8,9}};

//print 2d array
for(int i = 0; i<3; i++)
{
for(int j = 0; j<3; j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}

output: 1 2 3
             4 5 6
             7 8 9


3) Sum of Array Elements 

In this program, we are going to add all the elements of an array.

class SumOfArrayElements
{
public static void main(String args[])
{
int sum = 0;
int e[] = {100, 500, 600, 100};
//for each loop
for(int elements : e)
{
sum = sum+elements;
}
System.out.println("array elements sum "+sum);
}
}

output : array elements sum 1300



4) Find Minimum and Maximum Value In Array Java

In this array program we will find the largest and smallest number in an array.

class MinAndMaxInArray
{
public static void main(String args[])
{
int n[] = {1,2,5,10,33,47,4,21,81,37,91,102};

//assign first element of an array to largest and smallest 
int smallest = n[0];
int largest = n[0];
for(int i = 1; i<n.length; i++)
{
if(n[i]>largest)
largest = n[i];
else if(n[i]<smallest)
smallest = n[i];
}

System.out.println(" Largest Number is "+largest);
System.out.println(" Smallest Number is "+smallest);

}
}

output : Largest Number is 102
              Smallest Number is 1


5) Find Duplicates In Array

There are many methods we can use for finding duplicates elements in an java array such as Brute force, HashSet etc. But in this program we we will find the duplicates in an array by using HashSet concept of collection.

import java.util.*;
class DuplicatesElementsInArray
{
public static void main(String args[])
{
//taking String array 
String d[] = {"eye", "leg", "eye", "ear", "hair"};
HashSet<String> hs = new HashSet<String>();
for(String elements : d)
{
if(!hs.add(elements))
{
System.out.println(elements);
}
}
}
}

output : eye


6) Find Common Elements Between Two Arrays In Java

In this java array program we display the common elements between two arrays. Lets take a look below example

import java.util.*;
class CommonElements
{
public static void main(String args[])
{
String s[] = {"red", "yellow", "brown", "orange"};
String s2[] = {"pink", "black", "orange", "red"};
HashSet<String> hs = new HashSet<String>();

for(int i = 0; i<s.length; i++)
{
for(int j = 0; j<s2.length; j++)
{
if(s[i].equals(s2[j]))
{
hs.add(s[i]);
}
}
}
System.out.println("common elements is " + hs);
}
}

Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate