Java 8 Overview

Java version 8 was released on march 2014 with supports for functional programming, new nashorn javascript engine, stream apis, introducing lambdas, new date time apis and more.

Few of the features are :

  1. Lambda Expressions − a new language feature allowing treating actions as objects
  2. Method References − enable defining Lambda Expressions by referring to methods directly using their names
  3. Optional − special wrapper class used for expressing optionality
  4. Functional Interface – an interface with maximum one abstract method, implementation can be provided using a Lambda Expression
  5. Default methods − give us the ability to add full implementations in interfaces besides abstract methods
  6. Nashorn, JavaScript Engine − Java-based engine for executing and evaluating JavaScript code
  7. Stream API − a special iterator class that allows processing collections of objects in a functional manner
  8. Date API − an improved, immutable JodaTime-inspired Date API

Summary

In this article we saw an overview about the Java 8 features. In further articles we will have a detailed look into each feature.
Hope you liked the article !


final vs finally vs finalize

Difference between final, finally & finalize keywords in java is :

S.Nofinalfinallyfinalize
1Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed.Finally is used to place important code, it will be executed whether exception is handled or not.Finalize is used to perform clean up processing just before object is garbage collected.
2Final is a keyword.Finally is a block.Finalize is a method.

Examples :

1. Final keyword :

      
class FinalKeywordExample {
  public static void main(String[] args) {
    final int x = 10;
    x = 20;// Compile Time Error
  }
}
  

2. Finally block :

    
class FinallyKeywordExample {
  public static void main(String[] args) {
    try {
      int x = 30;
    } catch (Exception e) {
      System.out.println(e);
    } finally {
      System.out.println("finally block is executed"); // this gets printed
    }
  }
}

3. Finalize method :

    
class FinalizeKeywordExample {
  public void finalize() {
    System.out.println("finalize called");
  }

  public static void main(String[] args) {
    FinalizeKeywordExample f1 = new FinalizeKeywordExample();
    FinalizeKeywordExample f2 = new FinalizeKeywordExample();
    f1 = null;
    f2 = null;
    System.gc();
  }
}

Summary

So here we are, we hope now you got to know difference between final, finally and finalize keyword in java.

We tried our best to simplify the explanation, if you feel any difference or you need help in understanding any such thing, then feel free to contact us through email and subscribe to ProgrammerToday.


Throw vs Throws in Java

Difference between throw and throws keyword in java exception handling

S.Nothrowthrows
1Throw keyword is used to create a new Exception object and throw itThrows keyword is used in method definition, to declare that a method can throw this kind of exception.
2Using throw keyword you can declare only one Exception at a time.Using throws keyword you can declare multiple exception at a time.

Summary

So here we are, we hope now you got to know difference between throw and throws keyword in Exceptions in java.

We tried our best to simplify the explanation, if you feel any difference or you need help in understanding any such thing, then feel free to contact us through email and subscribe to ProgrammerToday.


Throws keyword in java with Example

Throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself. It is used to declare an exception, it tells the programmer that an exception may occur hence warning the programmer to also write exception handling mechanism to catch the exception.

It is usually used to throw checked exceptions and not unchecked ones. As unchecked exceptions can be controlled and exception handling mechanism can be used to catch it, so now the checked exceptions can be propagated/forwarded to another calling method.

You can throw multiple exceptions from a single method by seperating them using comma.

Example : Check exception propagation using throws keyword

    
import java.io.IOException;

public class ThrowsException {

  static void testMethod(int num) throws IOException, ClassNotFoundException {
    if (num == 1)
      throw new IOException("** IOException Occurred here **");
    else
      throw new ClassNotFoundException("** ClassNotFoundException **");
  }

  public static void main(String[] args) {

    try {
      testMethod(1);
    } catch (Exception ex) {
      System.out.println(ex);
    }

  }

}

OUTPUT

** IOException Occurred here **

Important : Why do we need throws ?

Why do we need throws when we can handle exceptions using try catch block ?

This is a valid question right ?

We need it for 2 important reasons :

  • In a scenarios where you have to handle multiple exceptions in various methods, it becomes very tedious to write try catch block in all the methods, so here comes throws into picture, we use throws in the method definition of various methods but catch them in one of the calling method.
  • Another advantage is that you will be forced to handle all the exceptions which is a good practice otherwise you will get compilation errors.

Summary

So here we are, we hope now you are confident and know how to use throws keyword in Exceptions in java.

We tried our best to simplify the explanation, if you feel any difference or you need help in understanding any such thing, then feel free to contact us through email and subscribe to ProgrammerToday.


Throw keyword in java with Example

It is used to create a new Exception object and throw it. Using throw keyword you can declare only one Exception at a time.

It is mainly used to throw custom exceptions.

One can also say Throw keyword is used to transfer control from try block to catch block.

Syntax :

throw new IOException("cannot open new connection");  

Example : To show throw Exception usage

    
public class TestThrowInException {

  static void validate(Integer salary) {
    
    int gross;
    if (salary == null)
      throw new NullPointerException("not valid");
    else {
      gross = salary + 1000;
    }
    System.out.println("gross salary is :" + gross);
  }

  public static void main(String[] args) {

    try {
      validate(null);
    } catch (Exception e) {
      System.out.println(e);
    }
  }

}

OUTPUT

java.lang.NullPointerException: not valid

Summary

So here we are, we hope now you are confident and know how to use throw keyword in Exceptions in java.

We tried our best to simplify the explanation, if you feel any difference or you need help in understanding any such thing, then feel free to contact us through email and subscribe to ProgrammerToday.


Java Threads | Multithreading in java

Life cycle of a Thread (Thread States)

NewRunnableRunningNon-Runnable (Blocked)Terminated

A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

  1. ) New The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
  2. ) Runnable The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
  3. ) Running The thread is in running state if the thread scheduler has selected it.
  4. ) Non-Runnable (Blocked) This is the state when the thread is still alive, but is currently not eligible to run.
  5. ) Terminated A thread is in terminated or dead state when its run() method exits.

How to create thread

There are two ways to create a thread:By extending Thread classBy implementing Runnable interface

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:Thread()Thread(String name)Thread(Runnable r)Thread(Runnable r,String name)

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().

public void run() : is used to perform action for a thread.

Starting a thread : start() method of Thread class is used to start a newly created thread.

It performs following tasks: A new thread starts(with new callstack). The thread moves from New state to the Runnable state. When the thread gets a chance to execute, its target run() method will run.
1) Java Thread Example – by extending Thread class

      
      class Multi extends Thread{ 
      public void run(){ 
      System.out.println("thread is running..."); 
      } 
      public static void main(String args[]){ 
      Multi t1=new Multi(); 
      t1.start(); 
       } 
      } 
      Output:thread is running...
      

2) Java Thread Example – by implementing Runnable interface

      
      class Multi3 implements Runnable{ 
      public void run(){ 
      System.out.println("thread is running..."); 
      } 

      public static void main(String args[]){ 
      Multi3 m1=new Multi3(); 
      Thread t1 =new Thread(m1); 
      t1.start(); 
       } 
      } 
      Output:thread is running...
      

If you are not extending the Thread class,your class object would not be treated as a thread object. So you need to explicitly create Thread class object. We are passing the object of your class that implements Runnable so that your class run() method may execute.

Thread Scheduler in Java

Thread scheduler in java is the part of the JVM that decides which thread should run. There is no guarantee that which runnable thread will be chosen to run by the thread scheduler. Only one thread at a time can run in a single process. The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.

Difference between preemptive scheduling and time slicing

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Deadlock in java

Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.

Can we start a thread twice ??

No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.

Let’s understand it by the example given below:

      
      public class TestThreadTwice1 extends Thread{ 
       public void run(){ 
         System.out.println("running..."); 
       } 
       public static void main(String args[]){ 
        TestThreadTwice1 t1=new TestThreadTwice1(); 
        t1.start(); 
        t1.start(); 
       } 
      } 
      Test it Now
             running
             Exception in thread "main" java.lang.IllegalThreadStateException
      

What if we call run() method directly instead start() method ?

Each thread starts in a separate call stack. Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack. It runs like a normal method, and does not calls the thread stack.

Multithreading in Java

Multithreading in java is a process of executing multiple threads simultaneously. Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than multiprocessing because threads share a common memory area. They don’t allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading

  1. ) It doesn’t block the user because threads are independent and you can perform multiple operations at same time.
  2. ) You can perform many operations together so it saves time.
  3. ) Threads are independent so it doesn’t affect other threads if exception occur in a single thread.

Java Executor Framework for Multithreading

Java executor framework exist from JDK 5 in concurrent package(java.uti.concurrent.Executor). It is used to run the Runnable objects without creating a new thread every time rather it reuses the already created threads from the thread pool. Since creating a thread in java is a very expensive process as there is a memory overhead.

Executors is a utility class that also provides useful methods to work with ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes through various factory methods.

Example: Java executor framework

A Runnable class, named WorkerThread.java:

      
package com.test.threadpool;

public class WorkerThread implements Runnable {
  
    private String command;
    
    public WorkerThread(String s){
        this.command=s;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+
                          " Start. Command = "+command);
        processCommand();
        System.out.println(Thread.currentThread().getName()+
                          " End.");
    }

    private void processCommand() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString(){
        return this.command;
    }
}
        

Below is the main class with Thread pool created using Executors Framework

In the above program, we are creating a fixed size thread pool of 5 worker threads. Then we are submitting 10 jobs to this pool, since the pool size is 5, it will start working on 5 jobs and other jobs will be in wait state, as soon as one of the job is finished, another job from the wait queue will be picked up by worker thread and get’s executed.

package com.programmertoday.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleThreadPool {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);
          }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}

OUTPUT :

pool-1-thread-2 Start. Command = 1
pool-1-thread-4 Start. Command = 3
pool-1-thread-1 Start. Command = 0
pool-1-thread-3 Start. Command = 2
pool-1-thread-5 Start. Command = 4
pool-1-thread-4 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
pool-1-thread-3 End.
pool-1-thread-3 Start. Command = 8
pool-1-thread-2 End.
pool-1-thread-2 Start. Command = 9
pool-1-thread-1 Start. Command = 7
pool-1-thread-5 Start. Command = 6
pool-1-thread-4 Start. Command = 5
pool-1-thread-2 End.
pool-1-thread-4 End.
pool-1-thread-3 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
Finished all threads
       

Summary

In this article we learnt about Java Multithreading, life cycle of a thread, how to create a thread, thread schedulers, executor framework and more.
Hope you liked the article !


Java collection Sorting Interfaces

These sorting interfaces are found in java.lang package

Sorting of Collections: using

  1. Comparable Interface : used for sorting
    1. String objects
    2. Wrapper class objects
    3. User-defined class objects
  2. Comparator Interface : used for sorting
    1. User-defined class objects

Comparable Interface


Java Comparable interface is used to sort or order the objects of the user-defined class. This interface contains only one method named compareTo(Object). It provides a single sorting sequence only i.e. you can sort the elements on the basis of single data member only. For example, it may be rollno, name, age or anything else.

public int compareTo(Object obj): It is used to compare the current object with the specified object. It returns

  1. positive integer, if the current object is greater than the specified object.
  2. negative integer, if the current object is less than the specified object.
  3. zero, if the current object is equal to the specified object.

Note : String class and Wrapper classes implement the Comparable interface by default. So if you store the objects of string or wrapper classes in a list, set or map, it will be Comparable by default.Example :

Of the Comparable interface that sorts the list elements on the basis of age.

                  
class Student implements Comparable<Student>{  
  int rollno;  
  String name;  
  int age;  
  Student(int rollno,String name,int age){  
  this.rollno=rollno;  
  this.name=name;  
  this.age=age;  
}  
  
public int compareTo(Student st){  
  if(age==st.age)  
    return 0;  
    else if(age>st.age)  
    return 1;  
    else  
    return -1;  
  }  
}  

import java.util.*;  
public class TestSort1{  
public static void main(String args[]){  
  ArrayList<Student> al=new ArrayList<Student>();  
  al.add(new Student(101,"Vijay",23));  
  al.add(new Student(106,"Ajay",27));  
  al.add(new Student(105,"Jai",21));  
  
Collections.sort(al);  
for(Student st:al){  
    System.out.println(st.rollno+" "+st.name+" "+st.age);  
    }  
  }  
} 

Comparator Interface


This interface contains 2 methods compare(Object obj1,Object obj2) and equals(Object element). It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data member, for example, rollno, name, age or anything else.

public void sort(List list, Comparator c): is used to sort the elements of List by the given Comparator.

  1. positive integer, if the current object is greater than the specified object.
  2. negative integer, if the current object is less than the specified object.
  3. zero, if the current object is equal to the specified object.

Note : String class and Wrapper classes implement the Comparable interface by default. So if you store the objects of string or wrapper classes in a list, set or map, it will be Comparable by default.Example :

Of the Comparable interface that sorts the list elements on the basis of age.

                  
class Student{  
  int rollno;  
  String name;  
  int age;  
  Student(int rollno,String name,int age){  
  this.rollno=rollno;  
  this.name=name;  
  this.age=age;  
  }  
}  

import java.util.*;  
class AgeComparator implements Comparator<Student>{  
  public int compare(Student s1,Student s2){  
    if(s1.age==s2.age)  
    return 0;  
    else if(s1.age>s2.age)  
    return 1;  
    else  
    return -1;  
  }  
}  

import java.util.*;  
import java.io.*;  
class Simple{  
public static void main(String args[]){  
  
ArrayList<Student> al=new ArrayList<Student>();  
al.add(new Student(101,"Vijay",23));  
al.add(new Student(106,"Ajay",27));  
al.add(new Student(105,"Jai",21));  
  
System.out.println("Sorting by Name");  
  
Collections.sort(al,new NameComparator());  
for(Student st: al){  
System.out.println(st.rollno+" "+st.name+" "+st.age);  
}  
  
System.out.println("Sorting by age");  
  
Collections.sort(al,new AgeComparator());  
for(Student st: al){  
System.out.println(st.rollno+" "+st.name+" "+st.age);  
}  
}  

}  

Summary

In this article we learnt about Java collections sorting and its various types. We learnt about Comparable and Comparator interface.
Hope you liked the article !


Java – Custom Exceptions in java

In java you have already seen some predefined classes such as NullPointerException, ArithmeticException these exceptions get triggered on certain defined conditions within their class. Meaning ? when there is a null value being computed or being used java throws an exception at run time and these can be caught using catch block.

Similarly in java you can create custom exceptions also called user defined exceptions.

You can create your own custom exceptions which can be triggered on your defined conditions using throw keyword.

Usage : Why to create Custom Exception at all ?

Sometimes you need an exception to be handled based on your set of conditions and rules in the code, in such cases you create your own custom exceptions.

Simple ! So How to create Custom Exception ?

Below we will create a custom exception class called MyCustomException

    
public class TestException{

public static void main(String args[]){
    try{
      int a=11;
      if (a>10) {
            throw new MyCustomException(a); //used throw keyword to throw Exception
      }
    }
    catch(MyCustomException e){
      System.out.println(e) ;
    }
  }

}
class MyCustomException extends Exception{

    int b;

    public MyCustomException(int a) {
      b=a;
    }

    public String toString() {
      return "The number "+b+" is out of range";
    }
}       

OUTPUT

The number 11 is out of range

Summary

So here we are, we hope now you are confident and know how to create custom Exceptions in java.

We tried our best to simplify the explanation, if you feel any difference or you need help in understanding any such thing, then feel free to contact us through email and subscribe to ProgrammerToday.


Java – Exception Handling

It is a resizable array or a dynamic array. It uses this dynamic array mechanism to store its elements. ArrayList class is found in the java.util package in java.

There are two types of errors:

  1. Compile time errors
  2. Runtime errors

Compile time errors : Often categorized as syntax(when syntax is not correct) and semantic(when syntax is correct but the usage is not) errors.

Example –

syntax error : when you write floa a; instead of float a; or

semantic error : when you declare a variable float a; again after few lines, float a;

Runtime errors : Also called as Exception errors. Exception is an unexpected event that disrupts the normal flow of execution of a program.

Example – ArithmeticException, NullPointerException, NumberFormatException, ArrayIndexOutOfBoundsException

Arising of exceptions is something which is not in developers control.

Why do we need to Handle Exceptions ?

In Real world life scenario consider a case when you have made an application which has a User Interface and it connects to a database and database goes down because of maintenance or is locked because of some failure.

How will a user/customer come to know that there is an issue with the database, will you throw an error on there face ? or catch this database exception and handle it gracefully showing proper message to the user.

So if you don’t wanna let your user/customer run away from your application by seeing the technical errors which they do not understand we handle the exceptions gracefully by catching these exceptions and return meaningful messages to the user/customer of the downtime or anything like that OR a better way for this example is to switch to a backup database in case the main database is not responding/throwing error.

How to Handle Exceptions ?

To handle a situation like in above scenario, we try to write a code which can handle this kind of exception. In this example of database failure we write a code to switch to another backup database so that our application is up and running without any interuption.

It can be written in an “if else block” as well BUT what if there is some other database exception which you did not forsee or cover in your code, what do you do then ? For this reason we need an Exception Handler.

Java and many other languages provides Exception Handling classes/frameworks which can handle it gracefully.

Try Catch finally Block

Try block : Program statements that you think can raise exceptions are contained within a try block.

Catch block : Write the code to handle exception in graceful manner.

Finally block : Write the code which you want should execute at any cost no matter exception is raised or not.
Example : closing session/database/file connection after execution of program.

Syntax of writing try-catch-finally block

try{
    //Code where you expect an exception would occur
  }
catch (exceptiontype name){
    //Code to handle the exception if it occurs
  }
finally{
    // example : connection.close();
  }

Actual Example :

public static void main(String[] args) {
    int a=0;
    int b=10;
    System.out.println("before dividing");
    try {
      System.out.println(b/a);
    }
    catch(ArithmeticException e) {
      e.printStackTrace();
    }
    System.out.println("after dividing");
}

OUTPUT

    
before dividing
java.lang.ArithmeticException: / by zero
  at com.test.exceptions.TestExceptions.main(TestExceptions.java:10)
after dividing    

Example : with finally block

public static void main(String[] args) {
    int a=0;
    int b=10;
    System.out.println("before dividing");
    try {
    System.out.println(b/a);
    }
    catch(ArithmeticException e) {
      e.printStackTrace();
    }
    finally {
      System.out.println("after dividing finally block");
    }
}

OUTPUT

before dividing
java.lang.ArithmeticException: / by zero
at com.test.exceptions.TestExceptions.main(TestExceptions.java:10)
after dividing finally block   

Hierarchy of ArrayList class

Diagram comes here

Java Exception Keywords

Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.

System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause.

Difference between Checked and Unchecked Exceptions

In java there are 2 types of exceptions.

  • Checked Exceptions
  • Unchecked Exceptions
S.NoCheckedUnchecked
1Checked exceptions are the exceptions which are checked at compile time.Unchecked are the exceptions that are not checked at compiled time.
2IOExceptions class is compile time.In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.

Summary

So here we are, we hope now you are confident and know how to use Exceptions in java.

We tried our best to simplify the explanation, if you feel any difference or you need help in understanding any such thing, then feel free to contact us through email and subscribe to ProgrammerToday.


Priority Queue Data Structure

Priority queue data structure in java is an implementation of queue interface.

Unlike other queue implementation classes(Like linkedlist) , priority queue does not orders elements based on insertion order (first in first out) but instead orders the elements according to their priorities. Element with the least priority is the head of the queue and is always removed first. Element with highest priority is always removed last.

Priority of the element is decided based on their natural ordering or using a comparator if provided in the constructor while creating the priority queue. In case no comparator is specified in the constructor, priority queue orders the elements based on their natural ordering.

  • Head is always the element with least priority.
  • Priority queue does not allow insertion of null element.
  • To insert objects of user defined class, priority queue expects the objects to belong to a class implementing comparable interface.
  • Priority queue does not allow insertion of non-comparable objects. This is because to decide the priority of any element which is inserted it has to be compared with existing elements in the queue.

Example : Priority Queue Data Structure

1.) creating priority queue

PriorityQueue<String> pq = new PriorityQueue<String>();
// Add elements to piority queue
pq.add("Marie");
pq.add("Jasmine");
pq.add("Rose");

System.out.println("priority queue : " + pq);
            

OUTPUT

priority queue: [Jasmine, Marie, Rose]
            

2.) remove elements from priority queue

System.out.println("priority queue: " + pq);

// check head element of the queue
String head = pq.peek();
System.out.println("head of the queue:" + head);

// remove element from the queue
pq.poll();
System.out.println("queue after removing an element: " + pq);
            

OUTPUT

priority queue: [Jasmine, Marie, Rose]
head of the queue: Jasmine
queue after removing an element: [Marie, Rose]
            

Summary

In this article we learnt about the Priority Queue Data Structure using Java. For better understanding we looked into some code snippets of queues add, peek & poll operations.
Hope you liked the article !