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

Monday, 5 June 2017

Java Map

 

Java Map Interface

Java Map

Map is an interface in java which is available in java.util.* package. Collection map interface contains keys and values and each keys and values are called objects.

Map contains only unique key and can be contains duplicate values.

Each key and value pairs are known as entry.

There are four classes that implements Map interface in java collection.
  • HashMap class
  • LinkedHashMap class
  • HashTable class
  • TreeMap class

Methods of Java Map Interface

There are some useful methods of collection map interface. These are

1) void clear()

This method removes all of the mapping from this map.

2) Object put(Object key, Object value)

This method is used to insert an key and value i.e entry in this map.

3) void putAll(Map map)

This method is used to insert the specified map in this map.

4) boolean containsKey(Object key)

This method returns true if this map contains a mapping for the specified key.

5) boolean containsValue(Object value)

This method returns true if this map maps one or more keys to the specified value.

6) Object remove(Object key)

This is used to remove or delete the entry for the specified key.

7) Object get(Object key)

This method returns the value for the specified key.

8) Set keySet()

This method returns a Set view of the keys contained in this map.

9) Set entrySet()

This method returns the Set view containing all the key and values.

10) int hashCode()

This method returns the hash code value for this map. 

11) boolean isEmpty()

This method returns true if there is no key and value mapping.



Map.Entry Interface

Map.Entry interface is a child interface of Map interface and it provides method so that we easily get the key and get the value.

Methods of Map.Entry Interface

Map.Entry provides two method.

1) Object getKey()

It is used to get key.

2) Object getValue()

It is used to get the value.



Java Map Example

This is an example of Map interface.

import java.util.*;
class MapExample
{
public static void main(String args[])
{
//creating object of HashMap class
Map<Integer, String> m = new HashMap<Integer, String>();
m.put(1, "pink");//using put method to insert key and value
m.put(2, "red");
m.put(3, "yellow");
m.put(4, "orange");
m.put(5, "brown");
m.put(6, "pink");
//using Map.Entry interface
for(Map.Entry me : m.entrySet())
{
System.out.println(me.getKey()+" "+me.getValue());
}
}


output : 1 pink
              2 red
              3 yellow
              4 orange
              5 brown
              6 pink

In the above example, there is 1,2... is a key and pink, red... is value. In this program there is no duplicate key but there is duplicate value pink. In this above example we used HashMap class, we will learn in later this HashMap class.


Java Map Example 2

This is another example of java map where we will take duplicate elements and let's see what happens.

import java.util.*;
class MapExample2
{
public static void main(String args[])
{
//creating object of HashMap class
Map<Integer, String> m = new HashMap<Integer, String>();
m.put(1, "pink");//using put method to insert key and value
m.put(2, "red");
m.put(3, "yellow");
m.put(4, "orange");
m.put(5, "brown");
m.put(2, "black");//duplicate key
//using Map.Entry interface
for(Map.Entry me : m.entrySet())
{
System.out.println(me.getKey()+" "+me.getValue());
}
}

}

output : 1 pink
              2 black
              3 yellow
              4 orange
              5 brown




Share:

Sunday, 4 June 2017

Java Thread Join

 

Thread Join


Java Thread Join

In java, The join() method of thread class can be used to pause the current thread execution until the specified thread is dead or terminate.

Syntax :

The syntax of join method in java multi-threading(thread) concept.
  • public void join()throws InterruptedException 
  • public void join(long milliseconds)throws InterruptedException
Here above we defined some join methods which throw an exceptions

Let's discuss join method in java thread in detail with example

Java Thread Join Example

In this thread join example we are going to use join() method of thread class so that we can easily join one thread with another thread(after the thread execution is complete).Let's see example

class ThreadJoinExample extends Thread
{
public void run()
{
for(int i = 0; i<=5; i++)
{
try
{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
ThreadJoinExample t1 = new ThreadJoinExample();
ThreadJoinExample t2 = new ThreadJoinExample();
ThreadJoinExample t3 = new ThreadJoinExample();
ThreadJoinExample t4 = new ThreadJoinExample();

//Here starting first thread t1
t1.start();
try
{
t1.join();//apply join() method to the first thread t1
}
catch(Exception e)
{
System.out.println(e);
}
//now we starting remaining threads
t2.start();
t3.start();
t4.start();
}
}

output : 0
              1
              2
              3
              4
              5
              0
              0
              0
              1
              1
              1
              2
              2
              2
              3
              3
              3
              4
              4
              4
              5
              5
              5

As you can see in the above example, when t1 thread execution is finished then remaining thread t2, t3, t4 start executing. Here in this above example there are total 4 thread created.



Java Thread Join Example 2

This is another example of thread join(long milliseconds) method in java. In this example we will pass some value in join method. Let's start


class ThreadJoinExample2 extends Thread

{

public void run()

{

for(int i = 0; i<=5; i++)

{
try

{

Thread.sleep(500);

}

catch(Exception e)

{

System.out.println(e);

}

System.out.println(i);

}

}

public static void main(String args[])
{
ThreadJoinExample2 t1 = new ThreadJoinExample2();
ThreadJoinExample2 t2 = new ThreadJoinExample2();
ThreadJoinExample2 t3 = new ThreadJoinExample2();
ThreadJoinExample2 t4 = new ThreadJoinExample2();

//Here starting first thread t1
t1.start();
try
{
t1.join(1000);//apply join method to the first thread t1
}
catch(Exception e)
{
System.out.println(e);
}
//now we starting remaining threads
t2.start();
t3.start();
t4.start();
}
}

output : 0
              1
              2
              0   
              0 
              0
              1
              1
              1
              3
              2
              4
              2
              2
              3
              3
              5
              3
              4
              4
              4
              5
              5
              5

In the above example you can see when t1 thread completes its task for 1500 milliseconds(3 times) then remaining thread i.e t2, t3, t4 starts executing.


Java Thread Priority

Priority of a thread are a represented by a number between 1 to 10. In java thread, each thread have a priority.

Java thread schedular schedules  the thread according to their priorities.

There are 3 constants in Thread class, These are
  1. public static int MIN_PRIORITY
  2. public static int NORM_PRIORITY
  3. public static int MAX_PRIORITY
The value of Minimum priority of a thread is 1 
The value of Maximum priority of a thread is 10, 
Normal priority of a thread is 5.(default priority)


Example of Java Thread Priority

This is an example of thread priority, Where we will print the thread's name and thread's priority. We also set the priority of thread.

class ThreadPriorityExample extends Thread
{
public void run()
{
System.out.println(" running thread name "+Thread.currentThread().getName());
System.out.println("running thread priority "+Thread.currentThread().getPriority());
}

public static void main(String args[])
{
ThreadPriorityExample t1 = new ThreadPriorityExample();
ThreadPriorityExample t2 = new ThreadPriorityExample();

//Now we set the priority of thread
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}

output : running thread name thread-1
              running thread priority 10
              running thread name thread-0
              running thread priority 1



Share:

Friday, 2 June 2017

Command Line Arguments In Java

 Command Line Arguments

Command Line Arguments In Java

Java command line arguments is an arguments which is passed when we run or executes our java program after compilation.

Java command line arguments are passed from the console or command prompt when we run our java programs

When we passed the arguments from the console or command prompt then it can be received in the java program and it can be used as an input.

In java by default all the command line arguments will be treated as String value and these String values are stored in a String array of the main() method of java programs.

Syntax of Command Line Arguments

Suppose, We edited a simple java program and then we will compile it and run it.

compile by : javac Test.java
run by : java Test value1 value2 value3 value4 ....

Here value1 value2 value3 value4 is a command line arguments


Java Command Line Arguments Example

This is simple example of command line arguments  where we will pass arguments from the console at the time of running java program.

class CLAExample
{
public static void main(String args[])
{
System.out.println("Argument from cmd " +args[0]);
}
}

compile : javac CLAExample.java
run : java CLAExample  javatutorial

output : Argument from cmd javatutorial


Java Command Line Arguments Example 2

Now this is another example of java command line arguments where we will print all the arguments that we passed from the command line and for traverse all the values from the array we use loop.

class  CLAExample2
{
public static void main(String args[])
{
for(int i = 0; i<args.length; i++)
{
System.out.println(args[i]);
}
}
}

now compile it and run it and give arguments

compile : javac CLAExample2.java
run : java CLAExample2 java 1 2 3 programming

output : java
              1
              2
              3
              programming



Java Command Line Arguments Example 3

In this example we will print all the arguments and length of the arguments we passed from the command line.

class CLAExample3
{
public static void main(String s[])
{
System.out.println("Length of the arguments "+s.length);
for(int i = 0; i<s.length; i++)
{
System.out.println(s[i]);
}
}
}

now give the arguments at run time

compile : javac CLAExample3.java
run : java CLAExample3 red green blue

output : Length of the arguments 3
              red
              green
              blue


Java Command Line Arguments Example 4

In this example, We will not give any arguments from the command line or console. If we will not give any arguments from the command line it will throw compile time error.

class CLAExample4
{
public static void main(String args[])
{
System.out.println(args[0]);
}
}

compile : javac CLAExample4.java
run : java CLAExample4

output :  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException


Some Important Points About Command Line Arguments

There are some points about command line arg.
  • In java all the commands line arguments would be accepted by the JVM.
  • In java, Command line arguments accepted in the form of String object by the JVM.
  • JVM always executes main method by passing objects of an array of String.
  • JVM never execute main method in java by passing null values.

Read More:


Share:

Thursday, 1 June 2017

Java Instanceof

 Java Instanceof

Java instanceof

In java, instanceof is a binary operator, Which is used to test whether the object is an instance of the specified type(class or subclass or interface) or not.

If the object is an instance of a particular or specified type i.e class or subclass or interface, it returns true otherwise it returns false.

The java instanceof operator is also known as type comparison operator because it compares the instance with type.


Java Instanceof Example

There is single class Test and we will instance with type.

class Test
{
public static void main(String args[])
{
Test t = new Test();
System.out.println(t instanceof Test);//will print true
}


output : true

In the above example , The output is true because t is a type of Test class.


Java Instanceof Example 2

Java instanceof operator in case of inheritance i.e parent child relationship. An object of a child class type is also a type of its parent class.

class Vehicle
{}
class Bike extends Vehicle
{
public static void main(String args[])
{
Bike b = new Bike();
System.out.println("Bike is a type of Vehicle");
System.out.println(b instanceof Vehicle);//will print true
}
}

output : Bike is a type of Vehicle
              true

In the above example, The output is true because Bike extends Vehicle hence the object of Bike(child class) can be referred by either Bike or Vehicle class.


Java Instanceof Example 3

Another example of instanceof operator in java, In this example we will apply instanceof operator with a variable that have null value. If we apply instanceof with a variable that have null value then it will return false.

class Employee
{
public static void main(String args[])
{
Employee e = null;
System.out.println(e instanceof Employee);
}
}

output : false



Java Downcasting With Instanceof Operator

Now, There is a word downcasting in java.

What is Downcasting in java ?

Downcasting in java , When child class type refers to the object of the parent class is called downcasting in java.

If we perform downcasting directly it will give compile time or run time errors in java. Let's take a look 

Child c = new Parent();//compile time error

Child c =(Child)new Parent();//ClassCastException at run-time

But by using instanceof operator we can easily perform downcasting in java.


Java Downcasting Example

In this example, we will perform java downcasting with the help of instanceof operator in java.

class Vehicle
{}
class Bike extends Vehicle
{
public static void check(Vehicle v)
{
if(v instanceof Bike)
{
Bike b = (Bike)v;//downcasting perform
System.out.println("Downcasting perform");
}
}
public static void main(String args[])
{
Vehicle v = new Bike();
Bike.check(v);
}
}



output : Downcasting perform


Java Downcasting Example 2

In this example We will perform downcasting without the help of instanceof operator.


class Vehicle

{}

class Bike extends Vehicle

{

public static void check(Vehicle v)

{

Bike b = (Bike)v;//downcasting perform

System.out.println("Downcasting perform");

}

public static void main(String args[])

{

Vehicle v = new Bike();

Bike.check(v);

}

}

output : Downcasting perform


Now, Here we learned in detail about instanceof operator and what is downcasting , downcasting with instanceof and without instanceof.


Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate