Tuesday, May 3, 2022

Java for Loop With Examples

In Java programming language there are three types of loops- for loop, while loop and do while loop. In this post we’ll learn about for loop in Java along with usage examples.

for loop in Java

In Java there are two forms of for loop.

  1. Traditional for loop– Available from the beginning.
  2. Enhanced for loop (for-each loop)- Added in Java 5.

Syntax for traditional for loop in Java

Syntax of the traditional for loop is as follows-

 
for(initialization; condition; increment\decrement) {
  // loop body
}

Statements that are part of loop body are enclosed with in curly braces. If there is only one statement with in a for loop then curly braces are optional.

It is not mandatory to do initialization and increment\decrement with in the for loop statement.

There are three parts in a for loop-

  1. Initialization– Initialization step is used to set the initial value of the variable which controls the for loop. Initialization is the first step in for loop execution and it is executed only once. The initilized variable is later incremented or decremented in the increment\decrement step of the loop.
  2. Condition– Condition is a boolean expression that is evaluated in each iteration. If condition is true then the loop body is executed, if condition is false then the loop terminates.
  3. Increment\decrement– The variable that controls the loop is incremented or decremented in this step.

Java for loop execution flow

Flow of the for loop can be explained using the following flow chart.

Java for loop

Java for loop examples

1- Using for loop to print numbers 1..5.

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

Output

 
1
2
3
4
5
  1. In the initialization part of for loop statement, variable i is declared and initialized to 1.
  2. Condition part (i <= 5) is evaluated in each iteration, returning true if value of i is less than or equal to 5 and returning false when value of i becomes greater than 5 and the condition evaluates to false which terminates the for loop.
  3. Third part of the for loop increments the variable i.

2- Using for loop in Java to print table of 7.

 
public class ForLoopDemo {
  public static void main(String[] args) {
    int number = 7;
    for(int i = 1; i <=10; i++){
      System.out.println(number + " X " +i + " = " + (i*7));
    }
  }
}

Output

 
7 X 1 = 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70

3- Using for loop to print numbers in reverse order 5..1

 
public class ForLoopDemo {
  public static void main(String[] args) {
    for(int i = 5; i > 0; i--){
      System.out.println(i);
    }
  }
}

Output

 
5
4
3
2
1

In this example value of i is decremented in the increment\decrement part.

4- As already stated it is not mandatory to do initialization and increment\decrement as part of for loop statement. Previous example of printing number in reverse order can also be written as follows.

 
public class ForLoopDemo {
  public static void main(String[] args) {
    int i = 5;
    for(; i > 0;){
      System.out.println(i);
       i--;
    }
  }
}

Output

 
5
4
3
2
1

As you can see in this example initialization and increment/decrement part is done outside the for loop statement but you still need semicolons with in the for loop statement.

Java for-each loop (Enhanced for loop)

for-each loop or enhanced for loop is available Java 5 onward. This version of for loop is used to iterate a collection of objects like an array, list or set sequentially.

Java for-each loop syntax

 
for(type var : collection){
  //loop body
}
  • type specifies the type of the elements in the collection.
  • var is assigned the next element from the collection in each iteration.
  • collection is the Collection that is iterated.

Java for-each loop examples

1- Using for-each loop to iterate an ArrayList and displaying its elements.

 
public class ForLoopDemo {
  public static void main(String[] args) {
    List<String> avengers = new ArrayList<String>();
    avengers.add("Iron Man");
    avengers.add("Captain America");
    avengers.add("Hulk");
    avengers.add("Thor");
    avengers.add("Black Widow");
    avengers.add("Hawkeye");        
    for(String avenger : avengers){
      System.out.println(avenger);
    }
  }
}

Output

 
Iron Man
Captain America
Hulk
Thor
Black Widow
Hawkeye

2- Iterating an array using for-each loop and finding the max element in the array.

 
public class ForLoopDemo {
  public static void main(String[] args) {
    int arr[] = {6, 7, 34, -23, 45, 48, 9, 4, 10, 21};
    int max = 0;
    for(int number: arr) {
      if(number > max)
        max = number;
    }
    System.out.println("Max elements in the array- " + max);        
  }
}

Output

 
Max elements in the array- 48

Nested for loop in Java

You can have a for loop (or any other loop) inside another for loop, such loops are known as nested loops.

In a nested for loop, for each iteration of the outer for loop, inner for loop is iterated until the condition in the inner for loop evaluates to false.

Java Nested for loop example

If you want to display the following pyramid pattern in Java.

 
     1
    1 2
   1 2 3
  1 2 3 4
 1 2 3 4 5
1 2 3 4 5 6
 
import java.util.Scanner;
public class PatternsDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - "); 
    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    // Outer for loop
    for(int i = 1; i <= num; i++){
      // this nested loop prints the spaces after which the
      // number has to be printed
      for(int j = 0; j < num - i; j++){
        System.out.print(" ");
      }
      // this loop prints the number
      for(int k = 1; k < i; k++){
        System.out.print(k + " ");
      }
      System.out.println();
    }            
  }
}

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

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Switch Case Statement in Java With Examples
  2. Conditional Operators in Java
  3. Object Creation Using new Operator in Java
  4. Java Pass by Value or Pass by Reference
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Ternary Operator in Java With Examples
  2. Constructor in Java
  3. How to Format Date in Java Using SimpleDateFormat
  4. Linked List Implementation Java Program
  5. How to Loop Through HashSet in Java
  6. Creating a Thread in Java
  7. Python Conditional Statement - if, elif, else Statements
  8. Dependency Injection in Spring Framework

Monday, May 2, 2022

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. For 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 With Examples
  5. Effectively Final in Java 8

You may also like-

  1. Difference Between Two Dates in Java
  2. forEach Statement in Java 8
  3. Java Stream API Tutorial
  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 Keyword in Java With Examples
  8. Dependency Injection in Spring Framework

Sunday, May 1, 2022

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

Saturday, April 30, 2022

java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java

In this article we’ll see what is java.lang.UnsupportedClassVersionError and how to resolve UnsupportedClassVersionError in Java.

UnsupportedClassVersionError in Java

UnsupportedClassVersionError is thrown when the Java Virtual Machine attempts to read a class file whose major and minor version numbers are not supported by the current JVM version. In simpler terms you can say that this error is thrown when Java file is compiled by a higher version of Java compiler and you are trying to run the class file using a lower version of Java.

For example to show UnsupportedClassVersionError I have compiled a Java file using Java 12 and then tried to run it using Java 10 (lower version).

C:\Program Files\Java\jdk-10.0.1\bin>java -classpath F:\Anshu\NetJs\NetJS\src\  org.netjs.programs.FileByteRW
Error: LinkageError occurred while loading main class org.netjs.programs.FileByteRW
        java.lang.UnsupportedClassVersionError: org/netjs/programs/FileByteRW has been compiled by a more recent version of the Java Runtime 
  (class file version 56.0), this version of the Java Runtime only recognizes class file versions up to 54.0

Points about UnsupportedClassVersionError-

  1. It is an error which descends from java.lang.Error Since it is an error so you can’t do any exception handling to recover from it.
  2. This error is thrown at runtime.

Class file version – major and minor versions

Now the question is how does JVM determine whether the class file version is supported or not for that you have to know the class file format in Java.

Though a Java class file consists of 10 sections but there are only two sections that relate to UnsupportedClassVersionError-

  1. Magic Number which is the first 4 bytes of the class file and the value is 0xCAFEBABE. Magic number is used to uniquely identify the format.
  2. Version of class file format which are the next 4 bytes and contain the minor and major versions of the class file

If the class file version is greater that what JVM supports java.lang.UnsupportedClassVersionError is thrown.

Below table shows the major version number of the class file format being used for the Java versions. Reference - https://en.wikipedia.org/wiki/Java_class_file

Java Version Supported class version
Java SE 1761 (0x3D hex)
Java SE 1660 (0x3C hex)
Java SE 1559 (0x3B hex)
Java SE 1458 (0x3A hex)
Java SE 1357 (0x39 hex)
Java SE 1256 (0x38 hex)
Java SE 1155 (0x37 hex)
Java SE 1054 (0x36 hex)
Java SE 953 (0x35 hex)
Java SE 852 (0x34 hex)
Java SE 751 (0x33 hex)
Java SE 650 (0x32 hex)
Java SE 549 (0x31 hex)
JDK 1.448 (0x30 hex)
JDK 1.347 (0x2F hex)
JDK 1.246 (0x2E hex)
JDK 1.145 (0x2D hex)

Howto resolve UnsupportedClassVersionError

Since UnsupportedClassVersionError is related to the Java version being used so there are two things that can be done based on what final Java version you want to use for your application.

  1. Compile code in an earlier version of Java if you want to supposr earlier version.
  2. Run Java code in a newer version by upgrading application Java version support.

In Eclips IDE you can reduce/increase the compiler compliance level based on your requirement. For that you need to go to Project properties – Java Compiler and then enable project specific settings to reduce or increase compiler compliance level.

Also change the configured JRE by going to Project properties – Java Build Path – libraries tab. There you can edit the chosen JRE and select an alternate JRE.

From commandline you can use --release option with javac to compile for a specific release. Supported releases are 7,8,9,10,11,12

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


Related Topics

  1. java.lang.ClassCastException - Resolving ClassCastException in Java
  2. Java Exception Handling Tutorial
  3. throw Statement in Java Exception Handling
  4. Try-With-Resources in Java With Examples
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. How to Sort ArrayList in Java
  2. Thread Priority in Java Multi-Threading
  3. Byte Streams in Java IO
  4. Array in Java With Examples
  5. Find Duplicate Elements in an Array Java Program
  6. Spring JdbcTemplate Select Query Example
  7. Python String isnumeric() Method
  8. Installing Hadoop on a Single Node Cluster in Pseudo-Distributed Mode

Friday, April 29, 2022

Spliterator in Java

Spliterator in Java, just like iterator, is used for traversing the elements of a source. The source of elements covered by a Spliterator could be, for example, an array, a Collection, an IO channel, or a generator function.

As the name suggests, Spliterator in Java can split the source and partition off some of its elements as another Spliterator, to be used in possibly-parallel operations. That way a huge data source can be divided into small sized units that can be traversed and processed in parallel.


Java Spliterator interface

Spliterator is a generic interface in Java defined as-

Interface Spliterator<T>

Where T is the type of elements returned by this Spliterator.

Java Spliterator methods

Though spliterator will increase performance by traversing the collection in parallel but you can also use spliterator even if you are not using parallel execution.

If you use iterator you have to use two methods hasNext() to ensure that there is next element and then next() method to use that element. Spliterator in Java provides methods that combine these two methods into one and making it more convenient to use. Some of the frequently used methods of Spliterator are-

  • tryAdvance()- If a remaining element exists, performs the given action on it, returning true; else returns false. Its form is-
    tryAdvance(Consumer<? super T> action)
    
    Here action is an instance of Consumer, which is a functional interface, it specifies the function that has to be applied on the next element while traversing the collection (or any other source).
  • forEachRemaining- Performs the given action for each remaining element, sequentially in the current thread, until all elements have been processed or the action throws an exception. Its form is-
    default void forEachRemaining(Consumer<? super T> action)
    
  • estimateSize()- Returns an estimate of the number of elements that would be encountered by forEachRemaining traversal, or returns Long.MAX_VALUE if infinite, unknown, or too expensive to compute. Its form is-
    long estimateSize()
    
  • trySplit()- If current spliterator can be partitioned a new spliterator is created, it partitions the elements of the source so that new spliterator traverse one of the partition while original spliterator traverses the other partition.
  • characteristics()- Returns a set of characteristics of this Spliterator and its elements.

Spliterator characteristics

A Spliterator also reports a set of characteristics() of its structure, source, and elements from among ORDERED, DISTINCT, SORTED, SIZED, NONNULL, IMMUTABLE, CONCURRENT, and SUBSIZED.

These characteristics are defined as constant fields in the Spliterator interface.

Read more about them here: https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html#characteristics--

To see constant values- https://docs.oracle.com/javase/8/docs/api/constant-values.html#java.util.Spliterator

Using characteristics() method will give you a result represented as ORed values of the characterstics relevant for the given source.

Java Spliterator example

If you have a list of names and you want to iterate it and print the names, using iterator it can be done as follows-

public class IteratorDemo {
  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
    "Nick", "Amy", "Desi", "Margo");
    Iterator<String> itr = nameList.iterator();
    while (itr.hasNext()) {
      System.out.println("name - " + itr.next());   
    }
  }
}

Same iteration of a List can be done using spliterator like this-

public class SpliteratorDemo {
  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
    "Nick", "Amy", "Desi", "Margo");
    Spliterator<String> splitStr = nameList.spliterator();
    while(splitStr.tryAdvance((n) -> System.out.println("name - " + n)));
  }
}

You can see, with Spliterator, you need to use only one method tryAdvance() which combines both hasNext() and next() methods of the iterator.

Java Spliterator forEachRemaining method example

If you want to convert all the names to lowercase you can use forEachRemaining method.

import java.util.Arrays;
import java.util.List;
import java.util.Spliterator;

public class SpliteratorDemo {
  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
      "Nick", "Amy", "Desi", "Margo");
    Spliterator<String> splitStr = nameList.spliterator();
    splitStr.forEachRemaining((n) -> {
      String x = n.toLowerCase();
      System.out.println("" + x);
    });
  }
}

Java Spliterator trySplit method example

If you want to split the original spliterator so that you can traverse the element in parallel.

import java.util.Arrays;
import java.util.List;
import java.util.Spliterator;

public class SpliteratorDemo {
  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
      "Nick", "Amy", "Desi", "Margo");
    Spliterator<String> splitStr = nameList.spliterator();
    Spliterator<String> splitStr2 = splitStr.trySplit();
    // Check if splitting actually happened, then use it
    if(splitStr2 != null){
      System.out.println("Spliterator-2");
      while(splitStr2.tryAdvance((n) -> System.out.println("name - " + n)));
    }
    // Original spliterator
    System.out.println("Original Spliterator");
    while(splitStr.tryAdvance((n) -> System.out.println("name - " + n)));
  }        
}

Output

Spliterator-2
name - Ram
name - Sheila
name - Mukesh
name - Rani
Original Spliterator
name - Nick
name - Amy
name - Desi
name - Margo

When you are splitting the spliterator, make sure to check that splitting actually happened by checking for null.

Here note one thing, according to Java docs-

If the original thread hands a spliterator off to another thread for processing, it is best if that handoff occurs before any elements are consumed with tryAdvance(), as certain guarantees (such as the accuracy of estimateSize() for SIZED spliterators) are only valid before traversal has begun.

So make sure you first do the splitting then only start any operation on the elements.

Reference- https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Spliterator.html

That's all for this topic Spliterator 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. Java Stream API Tutorial
  2. Java Stream API Examples
  3. Primitive Type Streams in Java Stream API
  4. collect() Method And Collectors Class in Java Stream API
  5. Java Stream - Collectors.partitioningBy() With Examples

You may also like-

  1. Method Reference in Java
  2. Interface Static Methods in Java
  3. Deadlock in Java Multi-Threading
  4. Java CyclicBarrier With Examples
  5. CopyOnWriteArrayList in Java With Examples
  6. TreeMap in Java With Examples
  7. Difference Between Comparable and Comparator in Java
  8. Exception Propagation in Java Exception Handling

Thursday, April 28, 2022

How to Sort ArrayList in Java

In ArrayList elements are added in sequential order and while displaying the elements by iterating an arraylist that same default ordering will be used. Sometimes you may have a requirement to sort an ArrayList in Java in ascending or descending order. In this post we'll see how to sort an ArrayList of Strings, Integers or Dates in Java.


Options for sorting a List

You can sort an ArrayList using-

  1. sort() method of the List interface Java 8 onward. Note that sort() method is implemented as a default interface method in List interface.
    • default void sort(Comparator<? super E> c)- Sorts this list according to the order induced by the specified Comparator. If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements' natural ordering should be used.
  2. Using Collections.sort() method. There are two overloaded versions of sort method and according to Java docs their description is-
    • public static <T extends Comparable<? super T>> void sort(List<T> list)- Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

    • public static <T> void sort(List<T> list, Comparator<? super T> c)- Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2)must not throw a ClassCastException for any elements e1 and e2 in the list).
  3. Using sorted method of the Java Stream API. There are two overloaded variants of the sorted method.
    • sorted()- Returns a stream consisting of the elements of this stream, sorted according to natural order.
    • sorted(Comparator<? super T> comparator)- Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.

Sorting ArrayList of strings using sort() method of List

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    // Passing null so natural ordering is used
    cityList.sort(null);
    System.out.println("List sorted using natural ordering" + cityList);
    
    // Using naturalOrder method to sort in natural order
    cityList.sort(Comparator.naturalOrder());
    System.out.println("List sorted using natural ordering" + cityList);
    
    // Using reverseOrder method to impose reverse of natural ordering
    cityList.sort(Comparator.reverseOrder());
    System.out.println("List sorted in reverse" + cityList);
  }
}

Output

List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted in reverse[Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

Using Collections.sort() method to sort ArrayList

To sort an ArrayList of strings according to the natural ordering of its elements we can use the first of the two sort methods.

Collections.sort(List<T> list)
public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
    // sorting the list
    Collections.sort(cityList);
    System.out.println("List sorted using natural ordering" + cityList);
  }
}

Output

List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]

As you can see you just need to pass the ArrayList to sort method. Collections.sort will work in this case because String class implements Comparable interface and provides implementation for the method compareTo(String anotherString).

Same way Integer class or Date class also implements Comparable interface so list of integers (or dates) can also be sorted in natural order by using sort() method of the Collections class or by using sort() method of the List interface. In fact Java docs give a list of all the classes that implements comparable interface thus can be used with the sort method to sort the elements in the natural order.

Classes Implementing Comparable

Following is the list of classes that already implement Comparable interface in Java. Thus the ArrayList storing obejcts of any of these classes can be sorted in its natural ordering by passing the list to sort() method.

Class Natural Ordering
Byte Signed numerical
Character Unsigned numerical
Long Signed numerical
Integer Signed numerical
Short Signed numerical
Double Signed numerical
Float Signed numerical
BigInteger Signed numerical
BigDecimal Signed numerical
Boolean Boolean.FALSE < Boolean.TRUE
File System-dependent lexicographic on path name
String Lexicographic
Date Chronological
CollationKey Locale-specific lexicographic

Sorting an ArrayList of strings in descending order

Collections.sort() method always sorts ArrayList of strings in ascending order. For sorting an ArrayList in descending order you need to use the second sort method which takes two parameters. First is the list that has to be sorted and second a comparator class that can be used to allow precise control over the sort order.
For sorting an ArrayList in descending order there are two options,

  • Use method reverseOrder() provided by Collections class itself

    General form and description

    public static <T> Comparator<T> reverseOrder()
    
    Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
  • Using a custom comparator.

Sorting ArrayList in descending order using reverseOrder method

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
     // sorting the list in descending order
    Collections.sort(cityList, Collections.reverseOrder());
    System.out.println("List sorted in reverses order- " + cityList);
  }
}

Output

List sorted in reverses order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

Sorting ArrayList in descending order using custom Comparator

Internally reverseOrder method calls a Comparator class to sort the list in reverse order. We can do it ourselves too by writing our own comparator class.

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
     // sorting the list in descending order
    Collections.sort(cityList, (String a, String b)->  b.compareTo(a));
    System.out.println("List sorted in reverses order- " + cityList);
  }
}

Output

List sorted in reverses order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

Note that Comparator is implemented as a lambda expression here.

Sorting Java ArrayList using sorted method of the Java Stream

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
    List<String> tempList = cityList.stream().sorted().collect(Collectors.toList());
    System.out.println("List sorted in natural order- " + tempList);
    tempList = cityList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
    System.out.println("List sorted in reverse order- " + tempList);
  }
}

Output

List sorted in natural order- [Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted in reverse order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

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


Related Topics

  1. How ArrayList Works Internally in Java
  2. How to Join Lists in Java
  3. How to Remove Duplicate Elements From an ArrayList in Java
  4. Difference Between Comparable and Comparator in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Fail-Fast Vs Fail-Safe Iterator in Java
  2. How to Iterate a HashMap of ArrayLists of String in Java
  3. static import in Java
  4. Interface Static Methods in Java
  5. Method Reference in Java
  6. Count Number of Times Each Character Appears in a String Java Program
  7. Java ThreadLocal Class With Examples
  8. Try-With-Resources in Java With Examples

Wednesday, April 27, 2022

Comparing Two Strings in Python

For comparing two strings in Python you can use relational operators (==, <, <=, >, >=, !=). Using these operators content of the Strings is compared in lexicographical order and boolean value true or false is returned.

Note that for equality comparison use ‘==’ not 'is' operator as 'is' operator does the identity comparison (compares the memory location of the String objects).

Python String comparison

When Strings are compared in Python, comparison is done character by character.

Checking for equality using ‘==’

def check_equality(str1, str2):
  #using string slicing
  str = str1[8: :]
  print('String is ',str)
  if str == str2:
    print('Strings are equal')
  else:
    print('Strings are not equal')

str1 = "This is Python"
str2 = "Python"
check_equality(str1, str2)

Output

String is Python
Strings are equal

In the example using Python string slicing, a slice of the string is obtained which is then compared with another string for equality.

If you use ‘is’ operator, comparison returns false even if the content is same as in that case memory location of the objects is compared.

def check_equality(str1, str2):
  #using string slicing
  str = str1[8: :]
  print('String is', str)
  if str is str2:
    print('Strings are equal')
  else:
    print('Strings are not equal')

str1 = "This is Python"
str2 = "Python"
check_equality(str1, str2)

Output


String is Python
Strings are not equal

Python String comparison examples

Let’s see another example with other operators.

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

  if str1 < str2:
    print(str1, 'is less than', str2)

  if str1 != str2:
    print(str1, 'is not equal to', str2)

str1 = "This"
str2 = "That"
check_equality(str1, str2)

Output

This is greater than That
This is not equal to That

In the example following condition

if str1 < str2:
  print(str1, 'is less than', str2)

returns false so the message accompanying this condition is not displayed.

That's all for this topic Comparing Two Strings 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. Check if String Present in Another String in Python
  2. Removing Spaces From String in Python
  3. Python Program to Reverse a String
  4. Nonlocal Keyword in Python With Examples
  5. Method Overriding in Python

You may also like-

  1. Name Mangling in Python
  2. Python for Loop With Examples
  3. self in Python
  4. Named Tuple in Python
  5. Switch Case Statement in Java With Examples
  6. Linear Search (Sequential Search) Java Program
  7. Dependency Injection in Spring Framework
  8. Difference Between @Controller And @RestController Annotations in Spring