Sunday, 29 September 2019

Generics in Java

There have been many new feature additions in Java over the year, with introduction of lambda expression in Java 8 it has even moved toward functional programming. But long before the lambda expressions and stream API there was one change which had a very big impact on the way you program and that was generics which was added in Java 5.

Generics in Java not only added a new way to declare classes, methods or interface but it also changed many of the classes in the API. Java collections API is an example.

Initially it took some time getting used to the parameters like T, K or V with the classes or methods but now its quite a familiar thing and very much a part of your daily programming.

Java Generics

Generics in Java enable you to specify type parameters when defining classes, interfaces and methods. Here type parameter is the type of data (class or interface) which these classes, interfaces and methods will operate upon.

As example, when you say List<T> that means a list which will store elements of type T. Since you have specified a type parameter so this List class is generic and T is the type parameter which specifies the type of element stored in the List.

Generic class format in Java

A generic class is defined using the following format:

class name<T1, T2, ..., Tn> { 
    /* ... */ 
}

The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1, T2, ..., and Tn.

Java Generics - Type Parameter Naming Conventions

By convention, generic type parameter names are single, upper case letters. That helps n distinguishing between type parameters and normal variables.

The most commonly used type parameter names are:

  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value
  • S,U,V etc. - 2nd, 3rd, 4th types

Benefits of Generics in Java

You might be thinking there is already an Object class which provides almost the same thing, as Object is super class of all the other classes so Object class can be used to make a class generic. Though that can be done but it may cause some unseen problems because there is no type safety.

As example-

Let’s say you have a list where you intended to store strings and you have not made it generic that means all its elements will be stored as objects of type Object -

List strList = new ArrayList();
strList.add("a");
strList.add("b");
strList.add(new Integer(4));
Iterator itr = strList.iterator();
while(itr.hasNext()){
 String str = (String)itr.next();
 System.out.println("" + str);
}

Since elements are stored as class Object type so there won’t be any compile time error if you store an integer too (as done in this line strList.add(new Integer(4));), even if you intended to store Strings.

Since the elements are stored as class Object type so you need to cast those elements to String while retrieving. At that time you will get a run time exception when the code will try to cast Integer to String.

So the code snippet shown above will throw run time exception -
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

That brings to the fore couple of benefits of using generics in Java-

  • Stronger type checks at compile time - In the above code if you use generics and specify the parametrized type of List as String you will get compile time error if an attempt is made to add element of any other type to the list. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

    As example -

    List<String> strList = new ArrayList<String>();
    strList.add("a");
    strList.add("b");
    strList.add(new Integer(4));
    

    With generics this code will throw following compile-time error if you try to add Integer to the list
    The method add(String) in the type List<String> is not applicable for the arguments (Integer)

  • Casting is not required - Another benefit you get with generics in Java is that cast is not required. Since you already specify the type with generics so explicit cast is not required.

    As example-

    List<String> strList = new ArrayList<String>();
    strList.add("a");
    strList.add("b");
    strList.add("c");
    
    Iterator<String> itr = strList.iterator();
    while(itr.hasNext()){
        String str = itr.next();
        System.out.println("" + str);
    }
    

    Here you see casting is not required when retrieving elements from the list.

  • Enabling programmers to implement generic algorithms – In many algorithms, logic remains same, irrespective of the data they are used with. On the other hand, generics make it possible to write classes, methods and interface that work with different kind of data that too in a type safe manner. Now combine these two facts and the result you can write generic algorithms that work with any type of data.

    As example-

    Let’s take a simple example to see how to create a generic class with parametrized type. While creating an object of the class you can specify the type, which in generics terminology is called generic type invocation, which replaces T with some concrete value.

    Generic class

    public class GenType<T> {
        T obj;
    
        public T getObj() {
            return obj;
        }
    
        public void setObj(T obj) {
            this.obj = obj;
        } 
    }
    

    Using Generic class

    public class GenericDemo {
    
        public static void main(String[] args) {
            // With Integer type
            GenType<Integer> genInt = new GenType<Integer>();
            genInt.setObj(21);
            int value = genInt.getObj();
            System.out.println("integer value " + value);
            
            // With String type
            GenType<String> genStr = new GenType<String>();
            genStr.setObj("Generic class test");
            String str = genStr.getObj();
            System.out.println("String value " + str);
            
            // With Double type
            GenType<Double> genDouble = new GenType<Double>();
            genDouble.setObj(34.56);
            double dblValue = genDouble.getObj();
            System.out.println("Double value " + dblValue);
        }
    }
    

    Output

    integer value 21
    String value Generic class test
    Double value 34.56
    

    Here you see that the same generic class is first invoked with Integer type, then String and then Double. And you get the added benefit of type safety and no chance of run time exception (which is a probability if you had used an Object class to make the class generic).

Points to remember

  1. Generics in Java provide type safety as there are stronger type checks at compile-time.
  2. Generics don’t work with primitive types, type arguments passed to the type parameters must be references.
  3. You can have generic classes, generic methods and generic interfaces.
  4. Type parameters are erased when generic classes are compiled.
  5. A generic class with type parameters can’t have static members using the type parameter. As example -
    public class GenType<T> {
        static T obj;
          .....
        .....
    }
    
    This code will have compile-time error - Cannot make a static reference to the non-static type T.
  6. In Java 7 and later you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, <>, is informally called the diamond.
    As example- List<Integer> ls = new ArrayList<>();

    You don’t need to write <Integer> again, empty set of type argument (<>) will do, type will be inferred automatically.

That's all for this topic Generics in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Generic Class, Interface And Generic Method
  2. Bounded Type Parameter in Java Generics
  3. Wildcard in Java Generics
  4. Type Erasure in Java Generics
  5. Covariant Return Type in Java

You may also like-

  1. interface default methods in Java 8
  2. effectively final in Java 8
  3. Method reference in Java 8
  4. ThreadLocal class in Java
  5. String and thread-safety in Java
  6. Dependency Injection using factory-method in Spring
  7. strictfp in Java
  8. Polymorphism in Java

Thursday, 26 September 2019

Python Program to Display Fibonacci Series

In this post we’ll see how to write a Python program to display Fibonacci series.

Fibonacci series is a series of natural numbers where next number is equivalent to the sum of previous two numbers. Equation for the same can be written as follows-

fn = fn-1 + fn-2

The first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, and each subsequent number is the sum of the previous two numbers. Python programs in this post we'll display the Fibonacci series as - 0 1 1 2 3 5 8 ...

Python program for Fibonacci series can be written using recursion apart from writing using its iterative counterpart.

1. Fibonacci series using recursion. In a recursive function you should have a base case to exit the repeated calling of the same function. In case of Fibonacci series program that base case is when num is 0 and 1.

def fibonacci(num):
    if num < 0:
        print('Please enter non-negative integer')
    # For first two numbers
    if num == 0:
        return 0
    if num == 1:
        return 1
    return fibonacci(num - 1) + fibonacci(num - 2)
 

# running function after takking user input
num = int(input('Enter how many numbers needed in Fibonacci series- '))
for i in range(num):
    print(fibonacci(i), end=' ')

Output

Enter how many numbers needed in Fibonacci series- 10
0 1 1 2 3 5 8 13 21 34 

2. Fibonacci series program using iteration. Here for loop is used to iterate the passed number and in each iteration two previous numbers are added to get a new number in the series.

def fibonacci(num):
    num1 = 0
    num2 = 1
    series = 0
    for i in range(num):
        print(series, end=' ');
        num1 = num2;
        num2 = series;
        series = num1 + num2;


# running function after takking user input
num = int(input('Enter how many numbers needed in Fibonacci series- '))
fibonacci(num)

Output

Enter how many numbers needed in Fibonacci series- 8
0 1 1 2 3 5 8 13

That's all for this topic Python Program to Display Fibonacci Series. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Find Factorial of a Number
  2. Python Program to Count Number of Words in a String
  3. Python Conditional Statement - if, elif, else Statements
  4. Getting Substring in Python String
  5. Python String isnumeric() Method

You may also like -

  1. Python Exception Handling - try,except,finally
  2. Encapsulation in Python
  3. Python Installation on Windows
  4. Factorial Program in Java
  5. Array in Java With Examples
  6. StringJoiner Class in Java With Examples
  7. Covariant Return Type in Java
  8. Spring MVC Form Example With Bean Validation

Wednesday, 25 September 2019

Python Program to Find Factorial of a Number

In this post we’ll see how to write a Python program to find factorial of a number.

Factorial of a non-negative integer n is product of all positive integers from 1 to n.

As example factorial of 4 can be calculated as-

4! = 4 X 3 X 2 X 1 = 24

Factorial program is one of the first program you'll write to understand recursive function so naturally in this post you'll see python program for factorial using recursion apart from writing using its iterative counterpart.

There is also an inbuilt function in Python for calculating factorial.

1. Recursive program to find factorial. In a recursive function you should have a base case to exit the repeated calling of the same function. In case of factorial program that base case is when num is 1.

def factorial(num):
    # base case(exit recursion)
    if num == 0 or num == 1:
        return 1
    else:
        return num * factorial(num - 1);


num = int(input('Enter a number- '))
print(factorial(num))

Output

Enter a number- 6
720

2. Iterative program to find factorial. Here for loop is used to iterate the passed number until it becomes 1, decrementing by 1 in each pass.

def factorial(num):
    fact = 1
    if num < 0:
        print('Please enter non-negative number')
    else:
        for i in range(num, 1, -1):
            fact = fact * i
        print('Factorial is- ', fact)


num = int(input('Enter a number- '))
factorial(num)

Output

Enter a number- -4
Please enter non-negative number

Enter a number- 0
Factorial is-  1

Enter a number- 4
Factorial is-  24

3. Using factorial function of the math module in Python. Import math module and use math.factorial() function to find factorial of a number.

import math


def factorial(num):
    print('Factorial is- ', math.factorial(num))


num = int(input('Enter a number- '))
factorial(num)

Output

Enter a number- 7
Factorial is-  5040

That's all for this topic Python Program to Find Factorial of a Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Display Fibonacci Series
  2. Python Program to Count Occurrences of Each Character in a String
  3. Python Conditional Statement - if, elif, else Statements
  4. Python return Statement With Examples
  5. String Slicing in Python

You may also like -

  1. Python Exception Handling Tutorial
  2. Class And Object in Python
  3. Removing Spaces From String in Python
  4. Fibonacci Series Program in Java
  5. Buffered Streams in Java IO
  6. DatabaseMetaData Interface in Java-JDBC
  7. Array in Java With Examples
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

Tuesday, 24 September 2019

Python Program to Count Occurrences of Each Character in a String

In this post we’ll see how to write a Python program to count occurrences of each character or to count frequency of character in a String.

1. If you have to write the Python program to count frequency of each character without using any String method then you can write it using an outer and inner for loop. In the outer loop take the character at index 0 and in the inner loop check if such character is found again in the string, if yes then increment count.

replace() method of the str class is used to remove all the occurrences of the character for which count is done so that same character is not picked again.

def count_char(text):
    for i in range(len(text)):
        if len(text) == 0:
            break;
        ch = text[0]
        # don't count frequency of spaces
        if ch == ' ' or ch == '\t':
            continue
        count = 1
        for j in range(1, len(text)):
            if ch == text[j]:
                count += 1
        # replace all other occurrences of the character
        # whose count is done, strip() is required for 
        # scenario where first char is replaced and there is 
        # space after that
        text = text.replace(ch, '').strip()
        print(ch + " - ", count)


count_char('netjs blog for Python')

Output

n -  2
e -  1
t -  2
j -  1
s -  1
b -  1
l -  1
o -  3
g -  1
f -  1
r -  1
P -  1
y -  1
h -  1

2. You can use count() method in Python which is used to count the number of occurrences of a specific substring.

def count_char(text):
    for i in range(len(text)):
        if len(text) == 0:
            break;
        ch = text[0]
        if ch == ' ' or ch == '\t':
            continue
        print(ch + " - ", text.count(ch))
        text = text.replace(ch, '').strip()


count_char('netjs java spring python')

Output

n -  3
e -  1
t -  2
j -  2
s -  2
a -  2
v -  1
p -  2
r -  1
i -  1
g -  1
y -  1
h -  1
o -  1

3. You can also use Dictionary to count occurrences of each character in the String. Character is stored as a key in dictionary and for each character it is checked if that character already exists as a key in dictionary or not. If it exists then increment the value associated with that key by 1, if such a key doesn’t exist then add it to the dictionary with value as 1.

def count_char(text):
    count = {}
    for ch in text:
        # don't count frequency of spaces
        if ch == ' ' or ch == '\t':
            continue
        # If char already in dictionary increment count
        # otherwise add char as key and 1 as value
        if ch in count:
            count[ch] += 1
        else:
            count[ch] = 1
    for k, v in count.items():
        print('Charcater {} occurs {} times'.format(k,v))


count_char('netjs java spring python')

Output

Charcater n occurs 3 times
Charcater e occurs 1 times
Charcater t occurs 2 times
Charcater j occurs 2 times
Charcater s occurs 2 times
Charcater a occurs 2 times
Charcater v occurs 1 times
Charcater p occurs 2 times
Charcater r occurs 1 times
Charcater i occurs 1 times
Charcater g occurs 1 times
Charcater y occurs 1 times
Charcater h occurs 1 times
Charcater o occurs 1 times

That's all for this topic Python Program to Count Occurrences of Each Character in a String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Count Number of Words in a String
  2. Removing Spaces From String in Python
  3. Check String Empty or Not in Python
  4. Python String isdigit() Method
  5. pass Statement in Python

You may also like -

  1. raise Statement in Python Exception Handling
  2. Magic Methods in Python With Examples
  3. self in Python
  4. Check if Given String or Number is a Palindrome - Java Program
  5. instanceof Operator in Java
  6. Optional Class in Java With Examples
  7. Spring depends-on Attribute
  8. @Import Annotation in Spring JavaConfig

Monday, 23 September 2019

Python Program to Count Number of Words in a String

In this post we’ll see how to write a Python program to count number of words in a String. This program can be written in various ways and this post shows some of the ways.

1. If you can’t use any of the methods of the String class then Python program for counting number of words can be written by iterating each character of the string using for loop and check if the character is space (‘ ‘), tab(‘\t’) or linefeed (‘\n’). If such a character is found that means a new word is starting so the count is incremented by 1.

def number_words(text):
    print('String-', text)
    no_of_words = 1
    for ch in text:
        if (ch == ' ' or ch == '\t' or ch == '\n'):
            no_of_words += 1
    print('Total number of words in String', no_of_words)


number_words('This is a test string')
s = 'This Python program counts\tnumber of words in a String.'
number_words(s)

Output

String- This is a test string
Total number of words in String 5
String- This Python program counts number of words in a String.
Total number of words in String 10

2. Using split() method in Python you can count words in a String. Whitespaces are used as a separator by default in split() method and the method returns a list of the words in the string. By using len() function you can get the length of that list which gives the number of words in a String.

def number_words(text):
    print('Total number of words in String', len(text.split()))


number_words('This is a test string')
s = 'This Python program counts\tnumber of words in a String.'
number_words(s)

Output

Total number of words in String 5
Total number of words in String 10

3. You can also write Python program to count number of words in a String using regular expressions in Python. In the program two methods split() and findall() are used.

The split() method splits the string as per the passed regular expression and the split words are returned as a list.

The findall() method returns all occurrences of the matching string as a list.

\s sequence character represents white space, \s+ means 1 or more white spaces.

\W sequence character represents non-alphanumeric, \W+ means 1 or more non-alphanumeric characters.

import re


def number_words(text):
    print('Total number of words in String', len(re.findall(r'\W+', text)))
    print('Total number of words in String', len(re.split(r'\s+', text)))


number_words('This is a Python program')
s = 'This Python program\'s job is to find number of words in a String'
number_words(s)

Output

Total number of words in String 4
Total number of words in String 5
Total number of words in String 13
Total number of words in String 13

That's all for this topic Python Program to Count Number of Words in a String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Count Occurrences of Each Character in a String
  2. Changing String Case in Python
  3. Python String split() Method
  4. Python count() method - Counting Substrings
  5. Python while Loop With Examples

You may also like -

  1. User-defined Exceptions in Python
  2. Namespace And Variable Scope in Python
  3. Multiple Inheritance in Python
  4. ListIterator in Java
  5. TreeMap in Java With Examples
  6. Count Number of Words in a String - Java Program
  7. Spring Component Scan Example
  8. Benefits, Disadvantages And Limitations of Autowiring in Spring

Friday, 20 September 2019

Reflection in Java - Array

Array in Java is also a class so many of the methods in java.lang.Class may be used with the array.

Reflection in Java also provides a specific class java.lang.reflect.Array for arrays.

How to identify array using reflection

If you want to determine if a class member is a field of array type that can be done by invoking Class.isArray() method.

For example let’s say we have a class TestClass which has one array field numArray. In another class ReflectArray using the class.isArray() method it is determined if there is any array in the TestClass.

TestClass

public class TestClass {
 private int value;
 private int[] numArray;
 public int getValue() {
  return value;
 }
 public void setValue(int value) {
  this.value = value;
 }
 public int[] getNumArray() {
  return numArray;
 }
 public void setNumArray(int[] numArray) {
  this.numArray = numArray;
 }
}

ReflectArray

import java.lang.reflect.Field;

public class ReflectArray {

    public static void main(String[] args) {
        try {
            Class<?> c = Class.forName("org.netjs.prog.TestClass");
            Field[] fields = c.getDeclaredFields();
            for (Field f : fields) {
                Class<?> type = f.getType();
                // Looking for array
                if(type.isArray()){
                    System.out.println("Array found " + f.getName());
                }
            }
            
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Output

Array found numArray

Creating new array using Java reflection

Using reflection API in Java you can dynamically create arrays of arbitrary type and dimensions using java.lang.reflect.Array.newInstance() method.

int[] testArray = (int[])Array.newInstance(int.class, 5);
System.out.println("length of array " + testArray.length);

Output

length of array 5

Getting and setting array using reflection

Using Java reflection API you can get or set an entire array. You can set an entire array using Field.set(Object obj, Object value) method. To retrieve an entire array use Field.get(Object obj) method.

If you want to get or set an array individual element by element, Array class has methods for that also. In order to set or get an int array you can use setInt(Object array, int index, int i) and getInt(Object array, int index) methods. Same way if you have a float array you can use setFloat(Object array, int index, float f) and getFloat(Object array, int index) methods.

There is also a method which takes Object for value as parameter that can be used with any type - set(Object array, int index, Object value) and get(Object array, int index) methods.

int[] testArray = (int[])Array.newInstance(int.class, 5);
System.out.println("length of array " + testArray.length);
// Setting values using setInt and set methods
Array.setInt(testArray, 0, 1);
Array.set(testArray, 1, 2);
Array.setInt(testArray, 2, 3);

// Getting values using getInt and get methods
System.out.println("First element " + Array.get(testArray, 0));
System.out.println("Second element " + Array.getInt(testArray, 1));
System.out.println("Third element " + Array.getInt(testArray, 2));

Output

length of array 5
First element 1
Second element 2
Third element 3

That's all for this topic Reflection in Java - Array. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Reflection in Java - Field
  2. Reflection in Java - Method
  3. Reflection in Java - Constructor
  4. Generating getters and setters using Reflection - Java Program
  5. Invoking getters and setters using Reflection - Java Program

You may also like-

  1. How to pass command line arguments in Eclipse
  2. Nested class and Inner class in Java
  3. BigDecimal in Java
  4. serialVersionUID and versioning in Java Serialization
  5. Type erasure in Java Generics
  6. AutoBoxing and UnBoxing in Java
  7. String and thread-safety in Java
  8. CopyOnWriteArrayList in Java

User-defined Exceptions in Python

In this Python Exception Handling Tutorial series we'll see how to write user defined exceptions in Python.

Though Python has many built-in exception covering a lot of error scenarios but sometimes you as a user would want to create your own exception for a specific scenario in order to make error messages more relevant to the context. Such exceptions are called user-defined exceptions or custom exceptions.

User-defined exception in Python

To create a custom exception in Python you need to create a new exception class. That custom exception class should typically be derived from the Exception class (built in Exception class), either directly or indirectly.

Since your exception class is a class it can theoretically be defined to do anything any other class can do, but usually user-defined exception classes are kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception.

As a convention your custom exception should be defined with name that end in “Error”, similar to the naming of the standard exceptions.

User-defined exception Python example

Suppose you have a Python function that take age as a parameter and tells whether a person is eligible to vote or not. Voting age is 18 or more.

If person is not eligible to vote you want to raise an exception using raise statement, for this scenario you want to write a custom exception named “InvalidAgeError”.

# Custom exception
class InvalidAgeError(Exception):
    def __init__(self, arg):
        self.msg = arg


def vote_eligibility(age):
    if age < 18:
        raise InvalidAgeError("Person not eligible to vote, age is " + str(age))
    else:
        print('Person can vote, age is', age)


try:
    vote_eligibility(22)
    vote_eligibility(14)
except InvalidAgeError as error:
    print(error)

Output

Person can vote, age is 22
Person not eligible to vote, age is 14

Hierarchical custom exceptions

When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:

class Error(Exception):
    """Base class for exceptions in this module."""
    pass

class InputError(Error):
    """Exception raised for errors in the input.

    Attributes:
        expression -- input expression in which the error occurred
        message -- explanation of the error
    """

    def __init__(self, expression, message):
        self.expression = expression
        self.message = message

That's all for this topic User-defined Exceptions in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Exception Handling - try,except,finally
  2. Python assert Statement
  3. Passing Object of The Class as Parameter in Python
  4. Name Mangling in Python
  5. Strings in Python With Method Examples

You may also like-

  1. Magic Methods in Python With Examples
  2. Getting Substring in Python String
  3. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  4. Python Program to Display Prime Numbers
  5. HashSet in Java With Examples
  6. Java Multithreading Interview Questions And Answers
  7. Switch-Case Statement in Java
  8. Spring Email Scheduling Example Using Quartz Scheduler

Thursday, 19 September 2019

raise Statement in Python Exception Handling

In Python Exception Handling - try,except,finally we saw some examples of exception handling in Python but exceptions in all the examples there were thrown automatically. You can throw an exception manually too using raise statement in Python.

Python raise statement

For throwing an exception using raise there are the following options-

1. You can simply use raise without any other expression. If no expressions are present, raise re-raises the last exception that was active in the current scope. If no exception is active in the current scope, a RuntimeError exception is raised indicating that this is an error.

def divide_num(num1, num2):
    try:
        print('Result-',num1/num2)
    except ZeroDivisionError as error:
        print('Zero is not a valid argument here')
        #raise with no expression
        raise
  

divide_num(10, 0)

Output

Zero is not a valid argument here
Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 10, in <module>
    divide_num(10, 0)
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 3, in divide_num
    print('Result-',num1/num2)
ZeroDivisionError: division by zero

As you can see raise statement re-raises the last exception again.

2. If raise is used with an expression then raise evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException. If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.

def divide_num(num1, num2):
    try:
        print('Result-',num1/num2)
    except ZeroDivisionError as error:
        print('Zero is not a valid argument here')
        raise RuntimeError("An error occurred")


divide_num(10, 0)

Output

Zero is not a valid argument here
Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 3, in divide_num
    print('Result-',num1/num2)
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 9, in <module>
    divide_num(10, 0)
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 6, in divide_num
    raise RuntimeError("An error occurred")
RuntimeError: An error occurred

As you can see in this case previous exception is attached as the new exception’s __context__ attribute.

3. raise can also be used with from clause for exception chaining. With from another exception class or instance is given, which will then be attached to the raised exception as the __cause__ attribute.

In the example there are two functions, from function func() there is a call to function divide_num with arguments that cause ZeroDivisionError.

def divide_num(num1, num2):
    try:
        print('Result-',num1/num2)
    except ZeroDivisionError as error:
        print('Zero is not a valid argument here')
        raise RuntimeError("An error occurred") from error


def func():
    try:
        divide_num(10, 0)
    except RuntimeError as obj:
        print(obj)
        print(obj.__cause__)

func()

Output

Zero is not a valid argument here
An error occurred
division by zero

As you can see using __cause__ attribute you can get the attached exception.

That's all for this topic raise Statement in Python Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. User-defined Exceptions in Python
  2. Passing Object of The Class as Parameter in Python
  3. Encapsulation in Python
  4. Interface in Python
  5. Python break Statement With Examples

You may also like -

  1. Magic Methods in Python With Examples
  2. Check if String Present in Another String in Python
  3. Default Arguments in Python
  4. Python Program to Display Armstrong Numbers
  5. HashMap in Java With Examples
  6. this Keyword in Java With Examples
  7. Introduction to Hadoop Framework
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

Python Exception Handling - try,except,finally

In this article we’ll see how to handle exceptions in Python using try, except and finally statements.

Python exception handling

To handle exception in Python you can use the following procedure-

  1. Use try block to enclose code that might throw an exception.
  2. Use except block to handle the raised exceptions.
  3. Use finally clause to perform clean up like closing the opened file.

General form of exception handling in Python using try, except finally is as follows.

try: 
 try suite
               
except Exception1:
 handler suite
except Exception2:
 handler suite
else:
 else suite
finally: 
 finally suite

Some important points to note here are-

  1. If no exception is raised then the statements in the else block are executed.
  2. Else and finally blocks are not mandatory.
  3. You can have multiple except blocks to handle multiple exceptions.
  4. try block must be followed either by except or finally.
  5. If finally block is there it is always executed whether an exception is raised or not.

Using try, except for exception handling

Let’s try to understand how exception handling in Python using try and except helps in writing robust code. Here is an example where a list is passed to a function and every element in the list is used to divide a number. Just notice what happens if one of the number in the list is zero.

def divide_num(num_list):
    for num in num_list:
        print(10/num)

num_list = [5, 6, 0, 7]
divide_num(num_list)

Output

2.0
1.6666666666666667
Traceback (most recent call last):

  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 6, in <module>
    divide_num(num_list)
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 3, in divide_num
    print(10/num)
ZeroDivisionError: division by zero

As you can see dividing by zero raises ZeroDivisionError, since code doesn’t provide any exception handling code of its own so default exception handling is used. Default behavior for handling such exceptions in Python is for the interpreter to print the full stack traceback, that includes the exception type (at least in case of built-in exception) and error message, and then terminate the program.

As you can see program is terminated and only the exception message is displayed by the default exception handling which is not that user friendly.

Python exception handling with try, except

Now let’s write that same code by providing exception handling with in the code using try and except.

def divide_num(num_list):
    for num in num_list:
        try:
            print(10/num)
        except ZeroDivisionError as error:
            print(error)
            print('Zero is not a valid argument here')
        else:
            print('in else block')

num_list = [5, 6, 0, 7]
divide_num(num_list)

Output

2.0
in else block
1.6666666666666667
in else block
division by zero
Zero is not a valid argument here
1.4285714285714286
in else block

As you can see now the code that may throw an exception is enclosed with in a try block. When the exception is raised in the try block exception handler looks for the except block that can handle the exception of that type. In the code ZeroDivisionError is raised and there is an except block that handles ZeroDivisionError so that except block handles the raised exception. Program is not terminated now when the exception is raised because of the exception handling in the code.

except block in Python

There are various ways to write except block while writing exception handling code in Python.

  1. You can catch the exception as an object that gives description about the raised exception.
     except ZeroDivisionError as error:
     
  2. You can write except block with the exception class name only.
     except Exception_Class_Name:
     
  3. You can handle multiple exceptions by using multiple except blocks or you can use a single except block and write multiple exceptions as a tuple.

    For example multiple except blocks-

      except ZeroDivisionError as error:
        print(error)
        print('Zero is not a valid argument here')
    except TypeError:
        print('Argument is not of valid type') 
      

    Single except block with multiple exceptions

      except (ZeroDivisionError, TypeError):
      
  4. You can write except with out specifying exception class. That way except block catches any type of exception. Though that is not considered good practice as it is too broad exception clause and you won’t be able to determine specifically which exception has been raised.
      except:
        print('An exception has occurred')
      

Multiple except block Python example

def divide_num(num_list):
    for num in num_list:
        try:
            print(10/num)
        except ZeroDivisionError as error:
            print(error)
            print('Zero is not a valid argument here')
        except TypeError as error:
            print(error)
            print('Argument is not of valid type-', num)



num_list = [5, 6, 'a', 7]
divide_num(num_list)

Output

2.0
1.6666666666666667
unsupported operand type(s) for /: 'int' and 'str'
Argument is not of valid type- a
1.4285714285714286

finally in Python exception handling

If finally is present, it specifies a ‘cleanup’ handler. The finally clause is always executed whether an exception is raised in the try block or not. That ensures that all the resources are properly cleaned up.

def divide_num(num):
    try:
        f = open("testfile", "a")
        r = 10/num
        f.write("Result 10/%d is %d" %(num,r))
    except ZeroDivisionError as error:
            print(error)
            print('Zero is not a valid argument here')
    except FileNotFoundError as error:
            print(error)
            print('Passed file does not exist')

    finally:
            print('closing file')
            f.close()

divide_num(0)

Output

division by zero
Zero is not a valid argument here
closing file

If function is called with a valid argument and no exception is raised even then finally block is executed. For example calling function as given here.

divide_num(2)

Output

closing file

If there is a return, break or continue statement in try block even then finally clause is executed.

def divide_num():
    try:
       return 'try'
    finally:
            print('In finally clause')

a = divide_num()
print(a)

Output

In finally clause
try

If there is a return statement in finally too then that becomes the last return statement to be executed. Since the return value of a function is determined by the last return statement executed so value returned by finally clause is the value returned by the function.

def divide_num():
    try:
       return 'try'
    finally:
            print('In finally clause')
            return 'finally'

a = divide_num()
print(a)

Output

In finally clause
finally

That's all for this topic Python Exception Handling - try,except,finally. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. raise Statement in Python Exception Handling
  2. Passing Object of The Class as Parameter in Python
  3. Encapsulation in Python
  4. Abstract Class in Python
  5. Strings in Python With Method Examples

You may also like-

  1. Magic Methods in Python With Examples
  2. Check if String Present in Another String in Python
  3. Keyword Arguments in Python
  4. Python Program to Display Fibonacci Series
  5. Java Collections Interview Questions And Answers
  6. this Keyword in Java With Examples
  7. What is Hadoop Distributed File System (HDFS)
  8. Spring Object XML Mapping (OXM) JAXB Example

Wednesday, 18 September 2019

Python Exception Handling Tutorial

This Python exception handling tutorial gives an overview of Python exceptions and how to handle exceptions using Python exception handling.

Types of errors

Errors in your Python programs can be categorized into atleast two types-

  • Syntax errors
  • Exceptions

Syntax error

Syntax errors or compile time errors are the errors due to which your program fails to compile. Such errors are detected at the compile time itself, file name, line number and error description is displayed so you know where to look for the error and how to correct it.

For example if you don’t write colon after if statement-

def check_equality(str1, str2):
    if str1 > str2
        print(str1, 'is greater than', str2)

Then you get the compile time error as shown here-

Output

  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 2
    if str1 > str2
                 ^
SyntaxError: invalid syntax

Exceptions

Even if a statement or expression is syntactically correct it may result in an error at run time. Errors detected during runtime are called exceptions and they disrupt the normal execution flow of the program.

For example in the following program there is an attempt to divide by zero which results in ZeroDivisionError at runtime.

def divide_num(num1, num2):
    return num1/num2

divide_num(10, 0)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 4, in <module>
    divide_num(10, 0)
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 2, in divide_num
    return num1/num2
ZeroDivisionError: division by zero

When these types of runtime errors occur in Python code, an exception object is created and raised. If there is no exception handling code to handle it then the error message is displayed that shows the context where the exception happened, in the form of a stack traceback. The exception type (at least in case of built-in exception) is printed as part of the message.

Python 3 exception hierarchy

In Python all exceptions are represented as classes and derive from BaseException class. The class hierarchy for built-in exceptions in Python is as follows.

Python 3 exception hierarchy

As you can see from the Python Exception hierarchy all built-in, non-system-exiting exceptions are derived from Exception class. All user-defined exceptions should also be derived from this class.

Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant raising an exception and terminating the program.

Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program. Warnings unlike exceptions are not fatal and don't terminate the program. Warning is the base class for warning categories.

Python exception handling

While writing robust code we should provide checks for the eventuality where program may fail at run time because of some condition like zero division, file not found, type error.

Default behavior for handling such exceptions in Python is for the interpreter to print the full stack traceback, that includes the exception type (at least in case of built-in exception) and error message, and then terminate the program.

By providing your own exception handling you can display an appropriate message and then continue with the program rather than terminating the program.

To handle exception in Python you can use the following procedure-

  1. Use try block to enclose code that might throw an exception.
  2. Use except block to handle the raised exceptions.
  3. Use finally clause to perform clean up like closing the opened file.

Together these three keywords constitute the Python exception handling. General form of exception handling in Python is as follows.

try: 
 try suite
               
except Exception1:
 handler suite
except Exception2:
 handler suite
else:
 else suite
finally: 
 finally suite

There can be more than one except block, based on the type of the exception raised appropriate except block is executed. Read more in this post- Python Exception Handling - try,except,finally

If no exception is raised then the statements in the else block are executed.

Statements inside the finally block are always executed whether an exception is raised or not.

Python exception handling example

def divide_num(num1, num2):
    try:
        print('Result-',num1/num2)
    except ZeroDivisionError:
        print('Division by zero')
        print('Zero is not a valid argument here')
    else:
        print('in else block')

divide_num(10, 0)
divide_num(10, 2)

Output

Division by zero
Zero is not a valid argument here
Result- 5.0
in else block

As you can see in the first call to function 0 is passed as divisor which results in ‘ZeroDivisionError’ so the except block handles that exception. Since the exception handling is done so the program doesn’t terminate and the second function is also executed. This time there is no error so an optional else block is executed.

Apart from try, except and finally other keywords used in Python exception handling are-

  • raise- Allows you to force a specified exception to occur.
  • assert- The assert statement enables you to verify if a certain condition is true or not. If it not true then it raises AssertionError.

Python built-in exceptions

Python language has several built-in exceptions, some of the important one are listed below.

Exception Class Description
ArithmeticError The base class for those built-in exceptions that are raised for various arithmetic errors: OverflowError, ZeroDivisionError, FloatingPointError.
AssertionError Raised when an assert statement fails.
EOFError Raised when the input() function hits an end-of-file condition (EOF) without reading any data.
ImportError Raised when the import statement has troubles trying to load a module.
IndexError Raised when a sequence subscript is out of range.
KeyError Raised when a mapping (dictionary) key is not found in the set of existing keys.
OverflowError Raised when the result of an arithmetic operation is too large to be represented.
RuntimeError Raised when an error is detected that doesn’t fall in any of the other categories.
SyntaxError Raised when the parser encounters a syntax error.
IndentationError Base class for syntax errors related to incorrect indentation. This is a subclass of SyntaxError.
SystemError Raised when the interpreter finds an internal error, but the situation does not look so serious to cause it to abandon all hope.
TypeError Raised when an operation or function is applied to an object of inappropriate type.
ZeroDivisionError Raised when the second argument of a division or modulo operation is zero.
FileNotFoundError Raised when a file or directory is requested but doesn’t exist.

That's all for this topic Python Exception Handling Tutorial. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. User-defined Exceptions in Python
  2. self in Python
  3. Python return Statement With Examples
  4. Constructor in Python - __init__() function
  5. Nonlocal Keyword in Python With Examples

You may also like -

  1. Changing String Case in Python
  2. Class And Object in Python
  3. Python Generator, Generator Expression, Yield Statement
  4. Convert String to int in Python
  5. What Are JVM, JRE And JDK in Java
  6. Java Concurrency Interview Questions And Answers
  7. ApplicationContextAware And BeanNameAware Interfaces in Spring Framework
  8. How to Handle Missing And Under Replicated Blocks in HDFS

Tuesday, 17 September 2019

New Date and Time API in Java With Examples

In Java 8 along with some new features like lambda expressions and stream API there is one more very important addition– A new Date and Time API which addresses the shortcomings of the old java.util.Date and java.util.Calendar classes.

The classes for the new Java date and time API resides in java.time package and use the calendar system defined in ISO-8601 (based on the Gregorian calendar system) as the default calendar. Other non-ISO calendar systems can be represented using the java.time.chrono package.


Features of the new Date and Time API in Java

As already mentioned the new Date and Time API does address the shortcomings of the old APIs, so let’s see what are some of the most important features of the new API.

  1. Immutable classes– In the new API all the core classes are immutable thus thread safe. That is an improvement over the old API where thread safety was an issue. For example if you were providing a format using the SimpleDateFormat class, then you had to ensure thread safety using synchronization or ThreadLocal class as SimpleDateFormat class is not thread safe.
  2. More intuitive and comprehensive- The classes in the new API relates closely with the different Date and Time use cases. There are many more utility methods provided.
  3. Better support for time zones– If you have worked in an application where you had to deal with dates and times in different time zones and day light savings then you would really appreciate the support provided for these operations in the new Date and Time API in Java.

One trivia here- The project to design new Date and Time API has been led jointly by the author of Joda-Time (Stephen Colebourne) and Oracle, under JSR 310.

LocalDate, LocalTime and LocalDateTime are the classes which you will use most of the time when working with new Date and Time API in Java. These classes represent the date, time or both of the day, based on the class used. Note that these classes won’t have associated time zone information. These classes cannot represent an instant on the time-line without additional information such as an offset or time-zone.

Some of the examples where you will use these classes are birthdays, holidays.

LocalDate in Java

LocalDate is a date in the ISO-8601 format, yyyy-MM-dd. LocalDate does not store or represent a time or time-zone. Instead, it is just a description of the date.

LocalDate class in Java Examples

Let’s have a look at some of the methods provided by the LocalDate class.

  1. If you want to obtain an instance of the current date from the system clock in the default time-zone.
    LocalDate curDate = LocalDate.now();
    System.out.println("Current Date - " + curDate); //Current Date – 2017-08-20
    
  2. If you want to obtain an instance of LocalDate from a year, month and day.
    LocalDate date = LocalDate.of(2016, 04, 3);
    System.out.println("Date - " + date); // Date – 2016-04-03
    
    Month value can be provided using Month enum which resides in java.time package.
    LocalDate date = LocalDate.of(2016, Month.APRIL, 3);
    

    Providing wrong value like LocalDate date = LocalDate.of(2016, Month.APRIL, 32); will result in DateTimeException.

    Exception in thread "main" java.time.DateTimeException: Invalid value for DayOfMonth (valid values 1 - 28/31): 32
    
  3. If you want to know whether the year is a leap year or not-
    System.out.println("Leap year - " + date.isLeapYear()); // Leap year – true
    
  4. Many a times you need to go back/forward by a few days, months or years, there are utility methods for that like minusDays, minusMonths, plusYears, plusWeeks.
    • If you want to go back by 50 days from the given LocalDate.
      LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
      System.out.println("Date - " + date);
        
      System.out.println("New Date - " + date.minusDays(50)); 
      //New Date – 2016-03-09
      
    • If you want to go back by 2 weeks-
      LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
      System.out.println("Date - " + date);
        
      System.out.println("New Date - " + date.minusWeeks(2))
      //New Date – 2016-04-14
      
    • If you want to add 1 year to the date-
      LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
      System.out.println("Date - " + date);
        
      System.out.println("New Date - " + date.plusYears(1));
      //New Date – 2017-04-28
      
    • If you want to add 3 months to the date-
      LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
      System.out.println("Date - " + date);
        
      System.out.println("New Date - " + date.plusMonths(3));
      //New Date – 2016-07-28
      
  5. There are methods like getDayOfWeek, getMonth, getDayOfYear to give you the value you are looking for.

    Example using getMonth()-

    LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
    System.out.println("Date - " + date);
      
    Month month = date.getMonth();
    if(month.equals(Month.APRIL)){
     System.out.println("It's April");
    }//It's April
    

LocalTime in Java

LocalTime is a time in the ISO-8601 format, like HH:mm:ss.SSS.

LocalTime class does not store or represent a date or time-zone. It is a description of the local time as seen on a wall clock. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.

Time is represented to nanosecond precision. For example, the value "14:32.30.123456789" can be stored in a LocalTime.

LocalTime class in Java Examples

  1. If you want to Obtain an instance of the current time from the system clock in the default time-zone.
    LocalTime curTime = LocalTime.now();
    System.out.println("Current Time - " + curTime); //Current Time – 18:46:11.659
    
  2. If you want to obtain an instance of LocalTime from an hour and minute or from an hour, minute and second or from an hour, minute, second and nanosecond you can use the correct of method to do that -

    While giving values for these parameters keep in mind the ranges for the same -

    • hour- the hour-of-day to represent, from 0 to 23
    • minute- the minute-of-hour to represent, from 0 to 59
    • second- the second-of-minute to represent, from 0 to 59
    • nanoOfSecond- the nano-of-second to represent, from 0 to 999,999,999
    LocalTime time = LocalTime.of(16, 45, 34);
    System.out.println("Time - " + time);//Time - 16:45:34
    
  3. If you want to subtract from the given time or add to the given time you can use methods minusHours(), minuMinutes(), plusNanos(), plusSeconds().
    • If you want to subtract 40 minutes from the given time.
      LocalTime time = LocalTime.of(16, 45, 34);
      System.out.println("Time - " + time);
        
      System.out.println("New Time - " + time.minusMinutes(40));
      //New Time – 16:05:34
      
    • If you want to add 12 Hours to the given time
      LocalTime time = LocalTime.of(16, 45, 34);
      System.out.println("Time - " + time);
        
      System.out.println("New Time - " + time.plusHours(12));
      //New Time – 04:45:34
      
  4. There are methods like getHour(), getMinute(), getNano(), getSecond() to give you the value you are looking for.

    If you want to get hour value of the given LocalTime-

    LocalTime time = LocalTime.of(16, 45, 34);
    System.out.println("Time - " + time.getHour());
    //Hour – 16
    

LocalDateTime in Java

LocalDateTime is a date-time in the ISO-8601 calendar format, such as yyyy-MM-ddTHH:mm:ss.SSS. LocalDateTime class does not store or represent a time-zone. It is a description of the date combined with the local time. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.

LocalDateTime class in Java Examples

Since LocalDateTime represents both date and time so most of the methods in this class are similar to what you have already seen for LocalDate and LocalTime.

  1. If you want to obtain an instance of the current date-time from the system clock in the default time-zone.
    LocalDateTime curDateTime = LocalDateTime.now();
    System.out.println("Current Date Time - " + curDateTime);
    // Current Date Time – 2017-08-20T19:31:55.001
    
  2. If you want to obtain an instance of LocalDateTime from year, month, day, hour and minute you can use of method. There are overloaded of methods where you can also provide second and nanosecond.
    LocalDateTime dateTime = LocalDateTime.of(2017, 8, 15, 14, 15, 56);
    System.out.println("Date Time - " + dateTime);
    // Date Time – 2017-08-15T14:15:56
    
  3. If you want to get the LocalTime part of this date-time.
    LocalDateTime curDateTime = LocalDateTime.now();
    System.out.println("Current Date Time - " + curDateTime);//Current Date Time - 2017-08-25T11:41:49.570
        
    LocalTime localTime = curDateTime.toLocalTime(); 
    System.out.println("localTime - " + localTime);//localTime - 11:41:49.570
    
  4. If you want to get the LocalDate part of this date-time.
    LocalDate localDate = curDateTime.toLocalDate(); 
    System.out.println("localDate - " + localDate); //localDate – 2017-08-25
    

TemporalAdjusters class in Java

TemporalAdjusters class provides static methods for common adjustments of date and time. For using TemporalAdjusters convenient way is to use the Temporal.with(TemporalAdjuster); method. Here note that Temporal is an interface which is implemented by LocalDate/Time classes.

TemporalAdjusters class in Java Example

  1. Finding the first or last day of the month
    LocalDateTime curDateTime = LocalDateTime.now();
    System.out.println("Last day of the month - " + curDateTime.with(TemporalAdjusters.lastDayOfMonth())); 
    //Last day of the month – 2017-08-31T12:01:03.207
    
  2. Finding the first or last day-of-week within a month.

    As example if you want to find the first Sunday of the given month -

    LocalDate curDate = LocalDate.now();
    System.out.println("Current Date - " + curDate);//Current Date - 2017-08-25
      
    System.out.println("First Sunday of the month - " + curDate.with(TemporalAdjusters.dayOfWeekInMonth(1, DayOfWeek.SUNDAY)));
    //First Sunday of the month – 2017-08-06
    

Instant class in Java

Instant class as the name suggests models a point on the time-line. This class can be used to provide time-stamps in an application. Instant class even has methods like equals, compareTo, isAfter, isBefore to compare two instants that helps when Instant is used as a timestamp.

Instant class in Java Examples

  1. If you want to obtain the current instant from the system clock.
    Instant ist = Instant.now();
    System.out.println("instant " + ist); 
    // instant 2017-08-25T13:58:13.286Z
    
  2. if you want to add/subtract mili seconds, nano seconds or seconds to a given instant there are plus and minus methods to do that. As example if you add 20 seconds to an instant.
    Instant ist = Instant.now();
    System.out.println("instant " + ist); // instant 2017-08-25T14:22:26.592Z
    System.out.println("instant + 20 -  " + ist.plusSeconds(20));] 
    // instant + 20 -  2017-08-25T14:22:46.592Z
    

Duration and Period in new Java Date & Time API

Duration measures an amount of time using time-based values like seconds, nanoseconds.

A Period measures an amount of time using date-based values like years, months, days.

Note that a Duration is not connected to the timeline. Adding a Duration equivalent to 1 day to a ZonedDateTime results in exactly 24 hours being added, regardless of daylight saving time or other time differences that might result.

Where as when you add a Period to a ZonedDateTime, the time differences are observed.

Duration class in Java Examples

  1. If you want to find duration between two LocalTime objects
    LocalTime t1 = LocalTime.of(5, 30, 56);
    LocalTime t2 = LocalTime.now();
    System.out.println("From time - " + t1 +  " To time - " + t2);
      
    // Duration
    Duration dr = Duration.between(t1, t2);
    System.out.println("Hours between " + dr.toHours());
    System.out.println("Minutes between " + dr.toMinutes());
    

    Output

    From time - 05:30:56 To time - 20:07:31.713
    Hours between 14
    Minutes between 876
    
  2. If you want to add/subtract hours, minutes or seconds to the given time. As example if you want to subtract 10 minutes from the given time.
    LocalTime t2 = LocalTime.now();
    System.out.println("t2-10mins " + t2.minus(Duration.ofMinutes(10)));
    

Period class in Java Examples

  1. If you want to find difference between two LocalDate objects.
    LocalDate dt1 = LocalDate.of(2016, 4, 23);
    LocalDate dt2 = LocalDate.now();
    System.out.println("From Date - " + dt1 +  " To Date - " + dt2);
    // Period
    Period pr = Period.between(dt1, dt2);
    System.out.println("Difference - " + pr.getYears() + " Year(s) " + pr.getMonths()+ " Month(s) " + pr.getDays() + " Day(s)");
    

    Output

    Output
    From Date - 2016-04-23 To Date – 2017-08-25
    Difference - 1 Year(s) 4 Month(s) 2 Day(s)
    
  2. If you want to add/subtract days, weeks, months or year to the given date. As example if you want to subtract 2 months from the given date.
    LocalDate dt2 = LocalDate.now(); // 2017-08-25
    System.out.println("dt2-2 Months " + dt2.minus(Period.ofMonths(2))); 
    //dt2-2 Months 2017-06-25
    

ChronoUnit.between method in Java

The ChronoUnit enum defines the units used to measure time. The ChronoUnit.between method is useful when you want to measure difference in a single unit of time only, such as days or seconds. The between method works with all temporal-based objects, but it returns the amount in a single unit only.

Java Examples using ChronoUnit.between

  1. To get hours or minutes between two LocalTime objects.
    LocalTime t1 = LocalTime.of(5, 30, 56);
    LocalTime t2 = LocalTime.now();
    long hrs = ChronoUnit.HOURS.between(t1, t2);
    System.out.println("Hours between " + hrs); //Hours between 14
      
    long mins = ChronoUnit.MINUTES.between(t1, t2);
    System.out.println("Minutes between " + mins);//Minutes between 897
    
  2. To get days between two LocalDate objects.
    LocalDate dt1 = LocalDate.of(2016, 4, 23);
    LocalDate dt2 = LocalDate.now(); //2017-08-25
    
    // ChronoUnit.between
    long days = ChronoUnit.DAYS.between(dt1, dt2);
    System.out.println("Days between " + days);//Days between 489
    

ZonedDateTime in Java

ZonedDateTime represents date-time with a time-zone in the ISO-8601 calendar system, such as 2017-08-26T10:15:04.035+05:30[Asia/Calcutta].

ZonedDateTime is an immutable representation of a date-time with a time-zone. ZonedDateTime class stores all date and time fields, to a precision of nanoseconds, and a time-zone, with a zone offset.

ZonedDateTime class in Java Examples

  1. If you want to obtain the current date-time from the system clock in the default time-zone.
    ZonedDateTime zdt = ZonedDateTime.now();
    System.out.println("Zoned time - " + zdt); 
    // Zoned time – 2017-08-26T10:42:36.796+05:30[Asia/Calcutta]
    
  2. If you want to obtain the current date-time from the system clock in the specified time-zone.
    ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/New_York"));
    System.out.println("Zoned time - " + zdt);
    //Zoned time – 2017-08-26T01:14:39.538-04:00[America/New_York]
    
  3. If you want to obtain an instance of ZonedDateTime using LocalDate, LocalDateTime, Instant or providing year, month, day, hour, minute, second yourself you can use one of the of() method. As example if you want to obtain an instance of ZonedDateTime using LocalDateTime and ZoneID as Paris.
    ZonedDateTime zdt1 = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("Europe/Paris"));
    System.out.println("Zoned time - " + zdt1); 
    // Zoned time - 2017-08-26T10:50:09.528+02:00[Europe/Paris]
    
  4. Just like LocalDatetime there are methods to add/subtract year, month, week, day, hour, minute, second, nanosecond. As example if you want to add 3 months to the given ZonedDateTime object.
    ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/New_York"));
    System.out.println("Zoned time - " + zdt); 
    //Zoned time - 2017-08-26T01:31:23.901-04:00[America/New_York]
     
    System.out.println("Zoned time + 3 Months - " + zdt.plusMonths(3));
    //Zoned time + 3 Months – 2017-11-26T01:31:23.901-05:00[America/New_York]
    
    Notice the difference in offset (changed from -4 to -5) it is because of the daylight saving.
  5. There are also get methods to get the year, month, week, day, hour, minute, second, nanosecond, offset part of the given ZonedDateTime. As example if you want to get the offset part -
    ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/New_York"));
    System.out.println("Zoned time - " + zdt); // Zoned time - 2017-08-26T01:36:37.930-04:00[America/New_York]
    System.out.println("Zoned time offset : " + zdt.getOffset()); // Zoned time offset : -04:00
    

Formatting and Conversion in new Date & Time API

That's all for this topic New Date and Time API in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. How to Format Date in Java Using SimpleDateFormat
  2. How to Convert Date And Time Between Different Time-Zones in Java
  3. Method Reference in Java
  4. Optional Class in Java 8
  5. Effectively Final in Java 8

You may also like-

  1. Difference Between Two Dates - Java Program
  2. forEach Statement in Java 8
  3. Stream API in Java 8
  4. How to sort ArrayList of custom objects in Java
  5. Difference between HashMap and ConcurrentHashMap in Java
  6. How HashSet works internally in Java
  7. Volatile in Java
  8. What is Dependency Injection in Spring