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

Wednesday 31 May 2017

Java TreeSet

 

Java TreeSet Class

Java TreeSet is a class in java collection framework. TreeSet class extends AbstractSet class and implements NavigableSet interface. Java TreeSet class also implements Cloneable and Serializable interfaces.

Java TreeSet class provides implementation for Set interface in java and it is uses tree for storage.

TreeSet class maintains the elements in ascending and sorted order.


Some Important Points About TreeSet Class

  • TreeSet class contains unique elements, In other words it doesn't contains duplicate elements.
  • TreeSet class maintains ascending order of an elements in a set.
  • Treeset class are good choice for storing large amounts of sorted information because its provides fast access and retrieval time.

Hierarchy of TreeSet Class

Java TreeSet

In this above diagram, TreeSet class implements NavigableSet interface and NavigableSet interface extends SortedSet interface and SortedSet inteface extends Set interface and Set extends Collection extends Iterable interface.


Constructors of Java TreeSet Class

There are some constructors of TreeSet  class , these are

1) TreeSet()

It is used to constructs a new and empty tree set that will be sorted in and ascending order according to the natural ordering of its elements.

2) TreeSet(Collection c)

It is used to constructs a new tree set containing the elements in the specified collection.

3) TreeSet(Comparator comp)

It is used to constructs a new and empty tree set that will be sorted according to the specified or given comparator.

4) TreeSet(SortedSet)

It is used to constructs a new tree set containing the same elements and using the same ordering as the specified or given sortedset.


Methods of TreeSet Class

There are some useful methods of tree set class.

1) boolean addAll(Collection c)

This method is used to adds all of the elements in the specified collection to this set.

2) void clear()

This method is used to  remove all of the elements from this set.

3) boolean contains(Object o)

This method return true if this set contains the given or specified elements.

4) boolean isEmpty()

If there is no elements in this set , this return true. 

5) boolean add(E e)

This method adds the specified elements to this set if it is not already present.


6) Object clone()

This method returns a shallow copy of this tree set instance.

7) int size()

This method returns the number of elements in this set.

8) Iterator iterator()

This method returns an iterator over the elements in this set in ascending order.

9) Iterator descendingIterator()

This method returns an iterator over the elements in this set in descending order.

10) Object first()

This method returns the first(lowest) elements currently in this sorted set.

11) Object last()

This method returns the last(highest) elements currently in this sorted set.

12) Spliterator spliterator()

This method creates a late-binding and fail-fast Spliterator over the element in this set. 


Java TreeSet Example 

This is simple example of tree set.

import java.util.*;
class TreeSetExample
{
public static void main(String args[])
{
//creating TreeSet of String type
TreeSet<String> ts = new TreeSet<String>();
ts.add("mango");
ts.add("mango");//will not print because it is duplicate element
ts.add("banana");
ts.add("orange");
ts.add("apple");

//traversing elements
Iterator<String> itr = ts.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

output : apple
              banana
              mango
              orange

In this above example, There is no duplicate elements in tree set and the elements are displayed in ascending order.


Java TreeSet Example 2



This is another example of tree set , In this example we will take String and Integer type of elements and  then print these elements.

import java.util.*;
class TreeSetExample2
{
public static void main(String args[])
{
//creating TreeSet of String type
TreeSet<String> ts = new TreeSet<String>();
ts.add("baman");
ts.add("daram");
ts.add("suraj");
ts.add("karan");
ts.add("ram");
ts.add("aman");//will print first because start with 'a' i.e aman

System.out.println(ts);

//creating TreeSet of Integer type
TreeSet<Integer> ts1 = new TreeSet<Integer>();
ts1.add(100);
ts1.add(99);
ts1.add(2);
ts1.add(1);

System.out.println(ts1);
}
}

output : [aman, baman, daram, karan, ram, suraj]
              [1, 2, 99, 100]







Share:

Monday 29 May 2017

Java Enum

 Enum In Java

Java Enum

Enum in java is a special type of data type. Enum is a collection of constants and these constants are by default static and final in java. 

Enum java can be used for a days of week(SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY), can be used for direction(EAST, WEST, NORTH, SOUTH) and can be used for month.

Java enum are available from JDK 1.5.

Java enum is an abstract class in java API, Which is implements Serializable  and Cloneable interfaces in java but it cannot extend any class because it internally extends Enum class.


How to define Enum in Java

public enum Direction
{
EAST,
WEST,
NORTH,
SOUTH
}

In the above declaration, Direction is the variable of enum type and it contains four constants EAST, WEST, NORTH, SOUTH.

Note : Java enum can be used within the class and outside of a class. You will understand better in given below java enum examples.


How to assign value to a enum type ?

Let's see how to assign value to enum type in java.

Direction d = Direction.SOUTH;

Here d is a variable of type Direction and Direction is a type of enum. This variable can take any value from the list(EAST, WEST, NORTH AND SOUTH). But in this case the value is set SOUTH.


Java Enum Example

The java enum can be defined within the class and outside of a class. In this example we are going to use java enum outside of the class.

enum Directions
{
EAST,
WEST,
NORTH,
SOUTH
}
class EnumExample1
{
public static void main(String args[])
{
Directions d = Directions.WEST;
System.out.println(d);
}
}

output : WEST


Java Enum Example 2



This is another java enum example, Where we will use java enum within the class.

public class EnumExample2
{
enum Days
{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
}
public static void main(String args[])
{
Days dd = Days.WEDNESDAY;
System.out.println(dd);
}


output : WEDNESDAY


Java Enum Example 3

In this example we are going to use values() method which returns an array of all enum values.

enum Directions
{
EAST,
WEST,
NORTH,
SOUTH
}
class EnumExample3
{
public static void main(String args[])
{
for(
Directions d : Directions.values());
{
System.out.println(d);
}
}
}

output : EAST
              WEST
              NORTH
              SOUTH



Java Enum Example With if-else Statements

We can use enum with if-else conditions in java programming.

enum Directions
{
EAST,
WEST,
NORTH,
SOUTH
}
class EnumWithIfElse
{
public static void main(String args[])
{
Directions d = Directions.SOUTH;
if(d == Directions.EAST)
{
System.out.println("EAST Direction");
}
else if(d == Directions.WEST)
{
System.out.println("WEST Direction");
}
else if(d == Directions.NORTH)
{
System.out.println("NORTH Direction");
}
else
{
System.out.println("SOUTH Direction");
}
}
}

output : SOUTH Direction

Java Enum Example With switch Statements

In this example we are going to use switch-case statements with java enum.

enum Directions
{
EAST,
WEST,
NORTH,
SOUTH;//here semicolon is optional 
}
class EnumWithSwitchCase
{
public static void main(String args[])
{
Directions d = Directions.NORTH;

//using switch-case statements
switch(d)
{
case EAST :
System.out.println("this is EAST");
break;
case WEST :
System.out.println("this is WEST");
break;
case NORTH :
System.out.println("this is NORTH");
break;
case SOUTH :
System.out.println("this is SOUTH");
break;
default:
System.out.println("Day Not Matched");
}
}
}

output : this is NORTH


Java Enum Example with Initialization, Field, Constructor and Method 

We can use field, constructor and methods in java enum program and we can give specific values to all the constants of java enum. The java enum constants have initial values start from 0,1,2,3 and so on.

enum Directions
{
EAST("E"),
WEST("W"),
NORTH("N"),
SOUTH("S");//here semicolon is required otherwise give c. error

//declaration of field
private final String field;

//declaration of constructor
Directions(String s)
{
field = s;
}

public String directionInformation()
{
return field;
}
}
class EnumAll
{
public static void main(String args[])
{
Directions d = Directions.EAST;
System.out.println(d.directionInformation());
Directions d1 = Directions.WEST;
System.out.println(d1.directionInformation());
}
}

output : E
Share:

Thursday 25 May 2017

Java Object Class

 

Object Class

Java Object Class

Object class in java is a super class or parent class or topmost class in java. Every class in java extends or inherit Object class by default. There is no need to use 'extends keyword' to extends or inherit the Object class because Object class are inherited by default in java.

Object class are available in java.lang package.

Object class is the root of the class hierarchy. All objects including arrays implements the method of this class.


Object Class Declaration

Declaration of java.lang.Object class is given below.

public class Object

As we know Object class are inherited by default but if we want to inherit other user defined class then we have to use extends keyword to inherit that class in java.

Every class in java extends Object class directly or indirectly.


Constructor of Object Class

1) Object()

This is empty constructor of Object class.


Java Object Class Methods

There are 11 methods in Object class in java programming language.

These are very useful method, Which is used in java thread, java String and other java programs.

1) protected Object clone()

This method creates and returns a copy of this object.

2) boolean equals(Object obj)

This method is used to compare the given object to this object.

3) protected void finalize()

The finalize method is called by the garbage collector. The finalize method is called just before an object is garbage collected. This method is called by the garbage collector on an object when garbage collector determines that there are no more reference to the object.

4) int hashCode()

This method returns a hashcode value for the object.

HashCode : In java for every objects, JVM generates a unique number which is called hashCode in java. JVM generates a different-different hashCode for differenet-different objects in java.

5)  void notify()

This method wakes up single thread that is waiting on this object's monitor.

6) void notifyAll()

This method wakes up all the thread that are waiting on this object's monitor.

7) toString()

The toString() method provides String representation of an object and this method is also used to convert an object to String.

8) wait()

Causes the current thread to wait until another thread invokes the notify() method or notifyAll() method for this object.

9) wait(long timeout)

Causes the current thread to wait until another thread invokes the notify() method or notifyAll() method for this object or a specified amount of time has elapsed.

10) wait(ling timeout, int nanos)

Causes the current thread to wait until another thread invokes the notify() method or notifyAll() method for this object or some other thread interrupts the current thread or a certain amount of real time has elapsed.

11) public final Class getClass()

This method returns the Class class object of this object. The Class class can further be used to  get metadata of this class.The returned Class object is the object that is locked by static synchronized methods of the represented class. 


Now Here we learned in detail, What is Object class in java and Constructor of Object class and Object class's methods


Share:

Wednesday 24 May 2017

Encapsulation In Java

 Encapsulation

encapsulation in java

Java encapsulation is used for wrapping the data and method together into a single unit, its known as encapsulation in java.

In other words, By the help of encapsulation we can combine the state(data member) and behavior(method) into a single unit.

Encapsulation can be achieved only class concept.

The best example of encapsulation is Java Bean class.

We can create encapsulated class in java, if we make all the data member(state) as private and use setter and getter method to set and get the data in it.

Encapsulation is also known as data hiding in java.

The real life example of encapsulation is medicine capsule  because capsule contains several other medicine.


Advantage of Encapsulation in Java

  1. The first advantage of using encapsulation in java is to secure the data from other methods because when we make the data(state) private then these data only use within the same class , these data cannot be accessible outside of a class.
  2. The second advantage of using encapsulation in java is to hide the internal details from the user so that user would not predict what's happening behind the program.
  3. It can be maintain and reuse easily.
  4. It provides abstraction between objects and its client.


Example of Encapsulation in Java

This is simple example of java encapsulation, Here in this example we will take three field of employee class like salary, age, name and its setter and getter methods. First we will set value and then get value of employee class field.

public class EncapsulationExample
{

//Declaring private field
private String name;
private int age;
private int salary;

//Declaring setter and getter methods
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}

public int getAge()

{

return age;

}

public void setAge(int age)

{

this.age = age;

}


public int getSalary()
{
return salary;
}
public void setSalary(int salary)
{

this.salary = salary;

}

}

class SetAndGetValue

{

public static void main(String args[])

{

EncapsulationExample e = new EncapsulationExample();



//set the value
e.setName("siya");
e.setAge(28);
e.setSalary(12000);

//get the value
System.out.println("Employee name "+e.getName());
System.out.println("Employee age "+e.getAge());
System.out.println("Employee salary "+e.getSalary());
}
}

Save : EncapsulationExample
Compile : EncapsulationExample
Run : SetAndGetValue  

output : Employee name siya
              Employee age 28
              Employee salary 12000


Differences Between Abstraction and Encapsulation inJava


There are some differences between abstraction and encapsulation in java.

Abstraction
  • You can use abstraction using java interface and abstract class.
  • In design level, abstraction solves the problem.
  • Abstraction means hiding implementation details or complexity by the help of abstract class or interface.
  • Abstraction basically used to hide the internal working .
Encapsulation
  • You can implement encapsulation by using access modifiers(private, protected, public).
  • In implementation level, encapsulation solves the problem.
  • Encapsulation means data hiding or information hiding, Which is used to secure the data from outside world.
  • Encapsulation basically used to secure the data from outside access .In encapsulation, we can bind the data and method in single unit and make private all the data for security reason. 

Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate