Java 8 – Date Api

Java 8 introduced a new date-time API to overcome some of the drawbacks of old date-time API :

What were those drawbacks ?

  1. Thread Safety – The Date and Calendar classes are not thread safe, leaving developers to deal with the headache of hard to debug concurrency issues and to write additional code to handle thread safety. On the contrary the new Date and Time APIs introduced in Java 8 are immutable and thread safe, thus taking that concurrency headache away from developers.
  2. ZonedDate and Time – Developers had to write additional logic to handle timezone logic with the old APIs, whereas with the new APIs, handling of timezone can be done with Local and ZonedDate/Time APIs.
  3. APIs Design and Ease of Understanding – The Date and Calendar APIs are poorly designed with inadequate methods to perform day-to-day operations. The new Date/Time APIs is ISO centric and follows consistent domain models for date, time, duration and periods. There are a wide variety of utility methods that support the commonest operations.

Java 8 under the package java.time introduced a new date-time API, most important classes among them are :
1. Local : Simplified date-time API with no complexity of timezone handling.
2. Zoned : Specialized date-time API to deal with various timezones.

1. LocalDate/LocatTime and LocalDateTime API : Use it when time zones are NOT required.

      
// Java code for LocalDate 
// LocalTime Function 
import java.time.*; 
import java.time.format.DateTimeFormatter; 
 
public class Date { 

public static void LocalDateTimeApi() 
{ 
 
  // the current date 
  LocalDate date = LocalDate.now(); 
  System.out.println("the current date is "+ 
                      date); 
 
 
  // the current time 
  LocalTime time = LocalTime.now(); 
  System.out.println("the current time is "+ 
                      time); 
     
 
  // will give us the current time and date 
  LocalDateTime current = LocalDateTime.now(); 
  System.out.println("current date and time : "+ 
                      current); 
 
 
  // to print in a particular format 
  DateTimeFormatter format =  
    DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");   
  
  String formatedDateTime = current.format(format);   
   
  System.out.println("in foramatted manner "+ 
                      formatedDateTime); 
 
 
  // printing months days and seconds 
  Month month = current.getMonth(); 
  int day = current.getDayOfMonth(); 
  int seconds = current.getSecond(); 
  System.out.println("Month : "+month+" day : "+ 
                      day+" seconds : "+seconds); 
 
  // printing some specified date 
  LocalDate date2 = LocalDate.of(1950,1,26); 
  System.out.println("the repulic day :"+date2); 
 
  // printing date with current time. 
  LocalDateTime specificDate =  
      current.withDayOfMonth(24).withYear(2016); 

  System.out.println("specfic date with "+ 
                     "current time : "+specificDate); 
} 

  // Driver code 
  public static void main(String[] args)  
  { 
      LocalDateTimeApi(); 
  } 
} 

Output:

the current date is 2018-04-09
the current time is 06:21:10.409
current date and time : 2018-04-09T06:21:10.410
in foramatted manner 09-04-2018 06:21:10
Month : APRIL day : 9 seconds : 10
the repulic day :1950-01-26
specfic date with current time : 2016-04-24T06:21:10.410

2. Zoned date-time API : Use it when time zones are to be considered.

      
// Java code for Zoned date-time API 
import java.time.LocalDateTime; 
import java.time.ZoneId; 
import java.time.ZonedDateTime; 
import java.time.format.DateTimeFormatter; 

public class Zone { 

// Function to get Zoned Date and Time 
public static void ZonedTimeAndDate() 
{ 
  LocalDateTime date = LocalDateTime.now(); 
  DateTimeFormatter format1 =  
    DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");  
    
  String formattedCurrentDate = date.format(format1); 
    
  System.out.println("formatted current Date and"+ 
                    " Time : "+formattedCurrentDate);  

  // to get the current zone 
  ZonedDateTime currentZone = ZonedDateTime.now();  
  System.out.println("the current zone is "+ 
                      currentZone.getZone());  

  // getting time zone of specific place 
  // we use withZoneSameInstant(): it is 
  // used to return a copy of this date-time  
  // with a different time-zone,   
  // retaining the instant. 
  ZoneId tokyo = ZoneId.of("Asia/Tokyo"); 

  ZonedDateTime tokyoZone = 
          currentZone.withZoneSameInstant(tokyo); 
                  
  System.out.println("tokyo time zone is " +  
                      tokyoZone); 

  DateTimeFormatter format =  
      DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");  
    
  String formatedDateTime = tokyoZone.format(format);  

  System.out.println("formatted tokyo time zone "+ 
                      formatedDateTime); 
    
} 
    
  // Driver code 
  public static void main(String[] args)  
  { 
        
      ZonedTimeAndDate(); 
        
  } 
} 

Output:

formatted current Date and Time : 09-04-2018 06:21:13
the current zone is Etc/UTC
tokyo time zone is 2018-04-09T15:21:13.220+09:00[Asia/Tokyo]
formatted tokyo time zone 09-04-2018 15:21:13

Summary

In this article we learnt about the Java 8 Date Time Apis and its examples.
Hope you liked the article !


Java 8 – Stream Api

Stream Apis is used to process collections of objects, a stream is a sequence of objects that supports many methods which can be pipelined to get the desired result.

Difference between Java 8 Stream and same operations perfomed in old java sequential way.

This will help you understand the need of Java 8 stream and its usefulness.

Before Java 8 streamsIn Java 8 stream way
// Sum of number of a list greater than 20
private static int sumNumbers(List<Integer> list) {
Iterator<Integer> it = list.iterator();
int sum = 0; while (it.hasNext()) {
int num = it.next();
if (num > 20) {
sum += num;
}
}
return sum;
}
// Sum of number of a list greater than 20 private static int sumUsingStream(List<Integer> list) {
return list.stream().
filter(i -> i > 20).mapToInt(i -> i).sum();
}
This is also called external iteration because client program is handling the algorithm to iterate over the list.Java Stream API to implement internal iteration, that is better because java framework is in control of the iteration
The program is sequential in nature, there is no way we can do this in parallel easily and a lot of code to be written for a simple task.Internal iteration provides several features such as sequential and parallel execution, filtering based on the given criteria, mapping etc and at the same time very less lines of code.

Converting Java Stream to Collection or Array

  1. We can use java Stream collect() method to get List, Map or Set from stream.
    Example:
    List<Integer> intList = intStream.collect(Collectors.toList());
    Map<Integer,Integer> intMap = intStream.collect(Collectors.toMap(i -> i, i -> i+10));
  2. We can use stream toArray() method to create an array from the stream.
    Example:
    Streamt<Integert> intStream = Stream.of(1,2,3,4);
    Integer[] intArray = intStream.toArray(Integer[]::new);
  3. We can use Collection stream() to create sequential stream and parallelStream() to create parallel stream.
    Example:
    //sequential stream
    Stream<Integer> sequentialStream = myList.stream();
    //parallel stream
    Stream<Integer> parallelStream = myList.parallelStream();

Java Stream Intermediate Operations

  1. Stream filter() example: We can use filter() method to test stream elements for a condition and generate filtered list.
    List<Integer> myList = new ArrayList<>();
    for(int i=0; i<100; i++)
    myList.add(i);
    Stream<Integer> sequentialStream = myList.stream();
    Stream<Integer> highNums = sequentialStream.filter(p -> p > 90); //filter numbers greater than 90
    System.out.print(“High Nums greater than 90=”);
    highNums.forEach(p -> System.out.print(p+” “)); //prints “High Nums greater than 90=91 92 93 94 95 96 97 98 99 ”
  2. Stream map() example: We can use map() to apply functions to an stream. Let’s see how we can use it to apply upper case function to a list of Strings.
    Stream<String> names = Stream.of(“adc”, “f”, “kl”);
    System.out.println(names.map(s -> { return s.toUpperCase(); }).collect(Collectors.toList())); //prints [ADC, F, KL]
  3. Stream sorted() example: We can use sorted() to sort the stream elements by passing Comparator argument.
    Stream<String> names2 = Stream.of(“aBc”, “d”, “ef”, “123456”);
    List<String> reverseSorted = names2.sorted(Comparator.reverseOrder()).collect(Collectors.toList()); System.out.println(reverseSorted); // [ef, d, aBc, 123456]
    Stream<String> names3 = Stream.of(“aBc”, “d”, “ef”, “123456”);
    List<String> naturalSorted = names3.sorted().collect(Collectors.toList()); System.out.println(naturalSorted); //[123456, aBc, d, ef]
  4. Stream flatMap() example: We can use flatMap() to create a stream from the stream of list. Let’s see a simple example to clear this doubt.
    Stream<List<String>> namesOriginalList = Stream.of( Arrays.asList(“Pankaj”), Arrays.asList(“David”, “Lisa”), Arrays.asList(“Amit”)); //flat the stream from List<String> to String stream
    Stream<String> flatStream = namesOriginalList.flatMap(strList -> strList.stream()); flatStream.forEach(System.out::println);

Java Stream Terminal Operations

  1. Stream reduce() example: We can use reduce() to perform a reduction on the elements of the stream, using an associative accumulation function, and return an Optional. Let’s see how we can use it multiply the integers in a stream. Stream<Integer> numbers = Stream.of(1,2,3,4,5); Optional<Integer> intOptional = numbers.reduce((i,j) -> {return i*j;}); if(intOptional.isPresent()) System.out.println(“Multiplication = “+intOptional.get()); //120
  2. Stream count() example: We can use this terminal operation to count the number of items in the stream. Stream<Integer> numbers1 = Stream.of(1,2,3,4,5); System.out.println(“Number of elements in stream=”+numbers1.count()); //5
  3. Stream forEach() example: This can be used for iterating over the stream. We can use this in place of iterator. Let’s see how to use it for printing all the elements of the stream. Stream<Integer> numbers2 = Stream.of(1,2,3,4,5); numbers2.forEach(i -> System.out.print(i+”,”)); //1,2,3,4,5,
  4. Stream match() examples: Let’s see some of the examples for matching methods in Stream API. Stream<Integer> numbers3 = Stream.of(1,2,3,4,5); System.out.println(“Stream contains 4? “+numbers3.anyMatch(i -> i==4)); //Stream contains 4? true Stream<Integer> numbers4 = Stream.of(1,2,3,4,5); System.out.println(“Stream contains all elements less than 10? “+ numbers4.allMatch(i -> i<10)); //Stream contains all elements less than 10? true Stream<Integer> numbers5 = Stream.of(1,2,3,4,5); System.out.println(“Stream doesn’t contain 10? “+numbers5.noneMatch(i -> i==10)); //Stream doesn’t contain 10? true
  5. Stream findFirst() example: This is a short circuiting terminal operation, let’s see how we can use it to find the first string from a stream starting with D. Stream<String> names4 = Stream.of(“Pankaj”,”Amit”,”David”, “Lisa”); Optional<String> firstNameWithD = names4.filter(i -> i.startsWith(“D”)).findFirst(); if(firstNameWithD.isPresent()){ System.out.println(“First Name starting with D=”+firstNameWithD.get()); //David }

Summary

In this article we learnt about Java 8 Stream API, converting stream to various java collections , stream apis various other methods and its examples. We suggest you try it out.
Hope you liked the article !


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.