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)

How to 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

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

Tuesday, April 26, 2022

How to Display Pyramid Patterns in Java - Part2

In the first part How to display pyramid patterns in Java - Part1 we have already seen Java programs for displaying some of the pyramid patterns using numbers and special symbols. In this post java programs are provided for some of the other pyramid patterns using numbers.

Java code for number pattern - Pattern 1

1
12
123
1234
12345
123456
12345
1234
123
12
1

For this types of patterns it is simpler to have to separate for loops. One for the increasing part and another for the decreasing part. In each of these loops there will be a nested for loop also.

import java.util.Scanner;

public class PatternsDemo {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter highest number for the pattern (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = 1; i <= num; i++){
      for(int j = 1; j <= i; j++){
        System.out.print(j);
      }            
      System.out.println();       
    }
    for(int i = num; i >= 1; i--){
      for(int j = 1; j < i; j++){
        System.out.print(j);
      }
      System.out.println();
    }                               
  }
}

Java code for number pattern - Pattern 2

1
22
333
4444
55555
666666
55555
4444
333
22
1
import java.util.Scanner;

public class PatternsDemo {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter highest number for the pattern (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = 1; i <= num; i++){
      for(int j = 1; j <= i; j++){
        System.out.print(i);
      }            
      System.out.println();            
    }
    for(int i = num ; i >= 1; i--){
      for(int j = 1; j < i; j++){
        System.out.print(i -1);
      }
      System.out.println();
    }                                
  }
}

Java code for number pattern - Pattern 3

999999999
88888888
7777777
666666
55555
4444
333
22
1
22
333
4444
55555
666666
7777777
88888888
999999999
import java.util.Scanner;

public class PatternsDemo {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter highest number for the pattern (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = num; i >= 1; i--){
      for(int j = 1; j <= i; j++){
        System.out.print(i);
      }            
      System.out.println();            
    }
    for(int i = 2 ; i <=num ; i++){
      for(int j = 1; j <= i; j++){
        System.out.print(i);
      }
      System.out.println();
    }                                
  }
}

Java code for number pattern - Pattern 4

1234567
123456
12345
1234
123
12
1
12
123
1234
12345
123456
1234567
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){
    for(int i = num; i >= 1; i--){
      for(int j = 1; j <= i; j++){
        System.out.print(j);
      }            
      System.out.println();            
    }
    for(int i = 2 ; i <=num ; i++){
      for(int j = 1; j <= i; j++){
        System.out.print(j);
      }
      System.out.println();
    }                                
  }
}

Java code for number pattern - Pattern 5

1234567
 123456
  12345
   1234
    123
     12
      1
     12
    123
   1234
  12345
 123456
1234567
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){
    for(int i = num; i >= 1; i--){
      for(int j = i; j < num; j++){
        System.out.print(" ");
      }  
      for(int j = 1; j <= i; j++){
        System.out.print(j);
      }            
      System.out.println();            
    }
    for(int i = 2 ; i <=num ; i++){
      for(int j = num; j > i; j--){
        System.out.print(" ");
      } 
      for(int j = 1; j <= i; j++){
        System.out.print(j);
      }
      System.out.println();
    }                                
  }
}

Java code for number pattern - Pattern 6

1 2 3 4 5 6 7 
 1 2 3 4 5 6 
  1 2 3 4 5 
   1 2 3 4 
    1 2 3 
     1 2 
      1 
     1 2 
    1 2 3 
   1 2 3 4 
  1 2 3 4 5 
 1 2 3 4 5 6 
1 2 3 4 5 6 7 
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){
    // upper pyramid
    for(int i = num; i >= 1; i--){
      for(int j = 1; j <= num-i; j++){
        System.out.print(" ");
      }  
      for(int j = 1; j <= i; j++){
        System.out.print(j + " ");
      }            
      System.out.println(); 
    }
    //lower pyramid
    for(int i = 2 ; i <= num ; i++){
      for(int j=0; j< num-i; j++){
        System.out.print(" ");
      }
      for(int j = 1; j <= i; j++){
        System.out.print(j + " ");
      }
      System.out.println();
    }                                
  }
}

Java code for number pattern - Pattern 7

     1 
    1 2 
   1 2 3 
  1 2 3 4 
 1 2 3 4 5 
1 2 3 4 5 6 
 1 2 3 4 5 
  1 2 3 4 
   1 2 3 
    1 2 
     1 
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){
    //upper pyramid
    for(int i = 1; i <= num; i++){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 0; j < num - i; j++){
        System.out.print(" ");
      }
      // this loop will print the number
      for(int k = 1; k < i; k++){
        System.out.print(k + " ");
      }
      System.out.println(); 
    }
    for(int i = 1; i < num; i++){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 0; j < i; j++){
        System.out.print(" ");
      }
      // this loop will print the number
      for(int k = 1; k < num-i; k++){
        System.out.print(k + " ");
      }
      System.out.println(); 
    }  
  }
}

That's all for this topic How to Display Pyramid Patterns in Java - Part2. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Program to Display Prime Numbers
  2. Armstrong Number or Not Java Program
  3. Factorial Program in Java
  4. Arrange Non-Negative Integers to Form Largest Number - Java Program
  5. Convert float to String in Java

You may also like-

  1. Zipping Files And Folders in Java
  2. Read or List All Files in a Folder in Java
  3. Format Date in Java Using SimpleDateFormat
  4. Find Maximum And Minimum Numbers in a Given Matrix Java Program
  5. Inheritance in Java
  6. Method Overriding in Java
  7. Type Casting in Java With Conversion Examples
  8. Ternary Operator in Java With Examples

Monday, April 25, 2022

How to Display Pyramid Patterns in Java - Part1

Writing a Java program to display a pyramid pattern is a good way to learn about nested loops. The pattern may contain numbers or any special symbol. So let's see some of the patterns and how to write a Java program to display those number or symbol patterns.

If you have noticed in most of the patterns one common thing is; it narrows down at the top (or bottom in case of reverse pyramid) for that you have to print that much spaces before printing the number(s).

Java code for pyramid of numbers - Pattern 1

    1
   2 2
  3 3 3
 4 4 4 4
5 5 5 5 5

In this pattern display count of a number is equal to the number in that row.

Logic is to have a loop that will iterate depending on the rows that are needed. Then there is a nested loop to display spaces. There is another nested loop to display the number.

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){
    for(int i = 1; i <= num; i++){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 0; j < num - i; j++){
        System.out.print(" ");
      }
      // this loop will print the number
      for(int k = 0; k < i; k++){
        System.out.print(i + " ");
      }
      System.out.println();           
    }           
  }
}

Java code for pyramid of stars - Pattern 2

     *
    * *
   * * *
  * * * *
 * * * * *
* * * * * *

The logic for this pattern is same as above, only change is instead of number asterisk (*) has to be displayed.

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){
    for(int i = 1; i <= num; i++){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 0; j < num - i; j++){
        System.out.print(" ");
      }
      // this loop will print the number
      for(int k = 0; k < i; k++){
        System.out.print("* ");
      }
      System.out.println();           
    }          
  }
}

Java code for number pattern - Pattern 3

     1
    1 2
   1 2 3
  1 2 3 4
 1 2 3 4 5
1 2 3 4 5 6

In this pyramid pattern instead of displaying the same number, numbers are displayed in ascending order in each row starting from 1.

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){
    for(int i = 1; i <= num; i++){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 0; j < num - i; j++){
        System.out.print(" ");
      }
      // this loop will print the number
      for(int k = 1; k < i; k++){
        System.out.print(k + " ");
      }
      System.out.println();        
    }            
  }
}

Java code for half pyramid pattern - Pattern 4

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9

This pattern is same as the pattern above minus the spaces. So the loop that prints the spaces is not needed.

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){
    for(int i = 1; i <= num; i++){
      
      // this loop will print the number
      for(int j = 1; j <= i; j++){
        System.out.print(j + " ");
      }
      System.out.println();      
    }            
  }
}

Java code for number pattern - Pattern 5

        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321

Here rather than same number or in ascending order numbers are displayed in each row in both ascending and then descending order. That is why there is one more nested loop.

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){
    for(int i = 1; i <= num; i++){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 0; j < num - i; j++){
        System.out.print(" ");
      }
      // this loop will print the number ascending part
      for(int k = 1; k < i; k++){
        System.out.print(k);
      }
      // this loop will print the number descending part
      for(int l = i; l >=1; l--){
        System.out.print(l);
      }
      System.out.println();            
    }           
  }
}

Java code for reverse pyramid pattern - Pattern 6

12345678987654321
 123456787654321
  1234567654321
   12345654321
    123454321
     1234321
      12321
       121
        1

This is the reverse pyramid which follows the same pattern as above but upside down.

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){
    for(int i = num; i >= 1; i--){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 1; j <= num - i; j++){
        System.out.print(" ");
      }
      // this loop will print the number ascending part
      for(int k = 1; k < i; k++){
        System.out.print(k);
      }
      // this loop will print the number descending part
      for(int l = i; l >=1; l--){
        System.out.print(l);
      }            
      System.out.println();           
    }            
  }
}

Java code for pattern (Floyds Triangle) - Pattern 7

Triangle with consecutive numbers.

1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 21 
22 23 24 25 26 27 28 
29 30 31 32 33 34 35 36 
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){
    int number = 1;
    for(int i = 1; i <= num; i++){                
      for(int j = 0; j < i; j++){
        System.out.print(number++ + " ");
      }
      System.out.println();               
    } 
  }
}

Java code for pattern - Pattern 8

1 2 3 4 5 6 7 
1 2 3 4 5 6 
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1 
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){
    for(int i = 0; i < num; i++){      
      // this loop prints the number
      for(int j = 1; j <= num - i; j++){
        System.out.print(j + " ");
      }
      System.out.println();            
    }    
  }
}

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

>>>Return to Java Programs Page


Related Topics

  1. Armstrong Number or Not Java Program
  2. Swap or Exchange Two Numbers Without Using Any Temporary Variable Java Program
  3. Java Program to Check Prime Number
  4. Fibonacci Series Program in Java
  5. Java Program to Find The Longest Palindrome in a Given String

You may also like-

  1. Add Double Quotes to a String Java Program
  2. Matrix Multiplication Java Program
  3. How to Convert Date to String in Java
  4. Array in Java
  5. Polymorphism in Java
  6. Varargs (Variable-length Arguments) in Java
  7. Difference Between ReentrantLock and Synchronized in Java
  8. Configuring DataSource in Spring Framework

Sunday, April 24, 2022

Compress And Decompress File Using GZIP Format in Java

In this post we'll see how to use GZIP to compress and decompress a file in Java. You will mainly use GZIP tool to compress and decompress files in Unix systems. Here note that you can only compress a single file using GZIP not multiple files residing in a folder.

Refer Creating Tar File And GZipping Multiple Files - Java Program to see how to gzip multiple files in Java.

Steps to gzip a file

In order to compress a file using GZIP in Java the steps are as follows-

  1. For reading the source file (file which has to be GZIPped) create a FileInputStream.
  2. Create a FileOutputStream to the target file (output GZIPped file).
  3. Create a GZIPOutputStream wrapping the FileOutputStream.
  4. Then you just need to read from the input stream and write to the output stream.

Steps to decompress a file

In order to decompress a file using GZIP in Java the steps are as follows-

  1. For reading the compressed file create a FileInputStream.
  2. Wrap that FileInputStream with in a GZIPInputStream.
  3. Create a FileOutputStream to the new file (created on decompressing GZIP file).
  4. Then you just need to read from the input stream and write to the output stream.

Java example for compressing and decompressing file in GZIP format

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipDemo {

 public static void main(String[] args) {
  // Path to file which is gzipped
  String SOURCE_FILE = "G:\\Test\\abc.txt";
  // Path to gzipped output files
  String GZIP_OUTPUT_FILE = "G:\\Test\\abc.gz";
  // File you get after decompressings
  String GZIP_NEW_FILE = "G:\\Test\\newabc.txt";
  
  GZipDemo gZipDemo = new GZipDemo();
  try {
   // Compressing a file
   gZipDemo.compressGZipFile(SOURCE_FILE, GZIP_OUTPUT_FILE);
   
   // decompressing a file
   gZipDemo.deCompressGZipFile(GZIP_OUTPUT_FILE, GZIP_NEW_FILE);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }
 /**
  * Method to gzip a file
  * @param sourceFile
  * @param outputFile
  * @throws IOException
  */
 public void compressGZipFile(String sourceFile, String outputFile) 
    throws IOException{
  FileInputStream fis = new FileInputStream(sourceFile);
  FileOutputStream fos = new FileOutputStream(outputFile);
  GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(fos); 
  byte[] buffer = new byte[1024];
  int len;
  while((len = fis.read(buffer)) > 0){
   gZIPOutputStream.write(buffer, 0, len);
  }
  // Keep it in finally
  fis.close();
  gZIPOutputStream.close();
 }
 
 /**
  * Method to decompress a gzip file
  * @param gZippedFile
  * @param newFile
  * @throws IOException
  */
 public void deCompressGZipFile(String gZippedFile, String newFile) 
    throws IOException{
  FileInputStream fis = new FileInputStream(gZippedFile);
  GZIPInputStream gZIPInputStream = new GZIPInputStream(fis);
  FileOutputStream fos = new FileOutputStream(newFile);
  byte[] buffer = new byte[1024];
  int len;
  while((len = gZIPInputStream.read(buffer)) > 0){
   fos.write(buffer, 0, len);
  }
  // Keep it in finally
  fos.close();
  gZIPInputStream.close();
 }
}

That's all for this topic Compress And Decompress File Using GZIP Format in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Untar a File in Java
  2. Zipping Files And Folders in Java
  3. Unzip File in Java
  4. Read or List All Files in a Folder in Java
  5. Write to a File in Java

You may also like-

  1. How to Create PDF From XML Using Apache FOP
  2. Producer-Consumer Java Program Using volatile
  3. How to Run Threads in Sequence in Java
  4. Comparing Enum to String in Java
  5. How HashMap Works Internally in Java
  6. Java Semaphore With Examples
  7. Serialization Proxy Pattern in Java
  8. Polymorphism in Java

Saturday, April 23, 2022

How to Inject Null And Empty String Values in Spring

This post shows how you can inject null or empty String as a value for any property in Spring framework.

Injecting empty string

If you are trying to inject an empty string as a value for any property in Spring then you can just pass "" as a value for that property.

As example

If you have an Employee class with name as field. Then you can use "" for name property.

If passed as a constructor argument then the configuration is as given below-

<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
  <constructor-arg name="name" value="" />        
</bean> 

If passed as property then the configuration is as given below-

<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
  <property name="name" value=""/>      
</bean>

Injecting null

If you need to inject null value for any field in Spring then use the special <null/> element for it, don’t use value=”null” because that will pass "null" as a String value.

So don’t do this-

<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
  <constructor-arg name="name" value="null" />   
</bean>

Use <null/> element instead in your Spring configuration.

<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
  <constructor-arg name="name">
    <null/>
  </constructor-arg>
</bean>

If passed as setter property-

<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
  <property name="name"><null/></property>
</bean>

That's all for this topic How to Inject Null And Empty String Values in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Dependency Injection Using factory-method in Spring
  2. Wiring Collections in Spring
  3. Spring Expression Language (SpEL) With Examples
  4. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
  5. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

You may also like-

  1. Spring Bean Life Cycle
  2. Spring Component Scan to Automatically Discover Beans
  3. How to Read Properties File in Spring Framework
  4. Spring Profiles With Examples
  5. How HashMap Internally Works in Java
  6. Java Reflection API Tutorial
  7. Initializer Block in Java
  8. What is Hadoop Distributed File System (HDFS)

Bucket Sort Program in Java

In this post we’ll see how to write Bucket sort program in Java. Bucket sort is one of the O(N) sorting algorithm like Radix sort and Counting sort. Since it runs in linear time (O(N)) so Bucket sort is faster than the comparison based algorithms like Merge Sort or Quick Sort.

Just like Counting sort, Bucket sort also makes some assumption about the input data beforehand like data should be uniformly distributed and should be with in a range.

How does Bucket sort work

Bucket sort works by assigning the input elements to different buckets and then sorting those buckets individually using any sorting technique like insertion sort so the elements in those buckets are sorted. After that merge the buckets to get the sorted output.

For distributing the elements to the buckets uniformly a good hash function is needed. The hash code given by hash function should also be an ordered hash such that if element i is greater than element j then hash(i) should also be greater than hash(j).

Let’s try to clarify working of bucket sort with an example where the elements in input array are with in the range 0..99- {47, 85, 10, 45, 16, 34, 67, 80, 34, 4, 0, 99}

Another array for buckets is needed. Let’s say we want that the elements having hash code 0-9 are put in bucket 0, 10-19 in bucket 1 ..... 90-99 in bucket 9 then we need an array of length 10 for buckets.

Since more than one element may be assigned to the same bucket so a list is needed at each index of the bucket array to store those elements.

With these requirement and the input array as shown above the structure should be as given below.

bucket sort in java

After sorting individual buckets you will have a structure as shown below.

Now starting from bucket 0 merge all the buckets to get the sorted output.

Bucket sort Java program

  1. Following the steps for bucket sort as explained above you need to create a bucket array and assign a List (preferably linked list) to each array index.
    List<Integer>[] buckets = new List[noOfBuckets];
    // Associate a list with each index 
    // in the bucket array         
    for(int i = 0; i < noOfBuckets; i++){
        buckets[i] = new LinkedList<>();
    }
  2. Distribute input elements to the buckets as per the calculated hash.
  3. Sort each bucket, for that sort() method of the Collections utility class is used in the program.
  4. Merge buckets, you can use the input array itself as output (sorted array) while merging the buckets.
    for(List<Integer> bucket : buckets){
      for(int num : bucket){
        intArr[i++] = num;
      }
    }
    
    Though outer and inner loops are used while merging but in the outer loop you are retrieving the list at each index and then iterating that list in the inner loop so effectively you are linearly traversing all the buckets which should take O(N) time.

Java code

public class BucketSort {
  public static void main(String[] args) {
    int[] intArr = {47, 85, 10, 45, 16, 34, 67, 80, 34, 4, 0, 99};
    //int[] intArr = {21,11,33,70,5,25,65,55};
    System.out.println("Original array- " + Arrays.toString(intArr));
    bucketSort(intArr, 10);
    System.out.println("Sorted array after bucket sort- " + Arrays.toString(intArr));
  }
    
  private static void bucketSort(int[] intArr, int noOfBuckets){
    // Create bucket array
    List<Integer>[] buckets = new List[noOfBuckets];
    // Associate a list with each index 
    // in the bucket array         
    for(int i = 0; i < noOfBuckets; i++){
      buckets[i] = new LinkedList<>();
    }
    // Assign numbers from array to the proper bucket
    // by using hashing function
    for(int num : intArr){
      //System.out.println("hash- " + hash(num));
      buckets[hash(num)].add(num);
    }
    // sort buckets
    for(List<Integer> bucket : buckets){
      Collections.sort(bucket);
    }
    int i = 0;
    // Merge buckets to get sorted array
    for(List<Integer> bucket : buckets){
      for(int num : bucket){
        intArr[i++] = num;
      }
    }
  }
    
  // A very simple hash function
  private static int hash(int num){
    return num/10;
  }
}

Output

Original array- [47, 85, 10, 45, 16, 34, 67, 80, 34, 4, 0, 99]
Sorted array after bucket sort- [0, 4, 10, 16, 34, 34, 45, 47, 67, 80, 85, 99]

Performance of Bucket Sort

Average time complexity of Bucket sort is considered O(n+k) where O(n) is the time spent in distributing elements across the buckets and sorting them and O(k) is the time spent in merging the buckets.

In worst case when most of the elements land in the same bucket time complexity is O(n2).

Space complexity of Bucket sort is O(n+k) as an auxiliary array of size k is needed for buckets. Each index of that bucket array holds reference to a list, total number of nodes in all those lists will be n making the total auxiliary space requirement as (n+k).

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

>>>Return to Java Programs Page


Related Topics

  1. Selection Sort Program in Java
  2. Bubble Sort Program in Java
  3. How to Run a Shell Script From Java Program
  4. How to Remove Elements From an Array Java Program
  5. How to Sort Elements in Different Order in Java TreeSet

You may also like-

  1. How to Read Properties File in Java
  2. Creating PDF in Java Using iText
  3. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  4. How to Display Pyramid Patterns in Java - Part1
  5. collect() Method And Collectors Class in Java Stream API
  6. Transaction Management in Java-JDBC
  7. Association, Aggregation And Composition in Java
  8. Spring MVC Exception Handling - @ExceptionHandler And @ControllerAdvice Example

Friday, April 22, 2022

Java Stream - Collectors.averagingInt(), averagingLong(), averagingDouble()

Collectors Class in Java Stream API provides many useful utility methods that can be used with Java Streams. One such group of methods, which can be classified as Collectors.averaging methods produces the arithmetic mean of the stream elements. There are following averaging methods for types int, long and double respectively.

  1. public static <T> Collector<T,?,Double> averagingInt(ToIntFunction<? super T> mapper)- This method is used to get average of stream of integers. If no elements are present, the result is 0.
  2. public static <T> Collector<T,?,Double> averagingLong(ToLongFunction<? super T> mapper)- This method is used to get average of stream of longs. If no elements are present, the result is 0.
  3. public static <T> Collector<T,?,Double> averagingDouble(ToDoubleFunction<? super T> mapper)- This method is used to get average of stream of doubles. If no elements are present, the result is 0.

As you can notice the argument passed to these methods are of type ToIntFunction, ToLongFunction and ToDoubleFunction respectively. These are functional interfaces which are implemented to extract the property to be averaged meaning their implementation produces a int-valued, long-valued and double-valued result respectively.

Collectors.averagingInt() Java example

In this example we’ll get the average of the List elements where elements are of type Integer.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CollectorAveraging {

  public static void main(String[] args) {
      List<Integer> numbers = Arrays.asList(16, 17, 32, 5, 3);
      double avg = numbers.stream().collect(Collectors.averagingInt(Integer::intValue));
      System.out.println("Average of the list elements- " + avg);
  }
}

Output

Average of the list elements- 14.6

Collectors.averagingLong() Java example

In this example we’ll get the average of the List elements where elements are of type long.

public class CollectorAveraging {

  public static void main(String[] args) {
      List<Long> numbers = Arrays.asList(16L, 17L, 32L, 5L, 3L);
      double avg = numbers.stream().collect(Collectors.averagingLong(Long::longValue));
      System.out.println("Average of the list elements- " + avg);
  }
}

Output

Average of the list elements- 14.6

Collectors.averagingDouble() Java example

In this example we’ll get the average of the List elements where elements are of type double.

public class CollectorAveraging {

  public static void main(String[] args) {
      List<Double> numbers = Arrays.asList(16.87, 17.34, 23.45, 2.22, 3.67);
      double avg = numbers.stream().collect(Collectors.averagingDouble(Double::doubleValue));
      System.out.println("Average of the list elements- " + avg);
  }
}

Output

Average of the list elements- 12.709999999999999

Collectors.averagingInt with Custom Object Example

In this example we’ll use summing method to get the average of salaries for all the employees.

Employee Class

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
  @Override
  public String toString() {
      return "Emp Id: " +  getEmpId() + " Name: " + getName() + " Age: " + getAge();
  }
}
public class CollectorAveraging {

  public static void main(String[] args) {
     List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                  new Employee("E002", 35, "Shelly", 'F', 8000), 
                  new Employee("E003", 24, "Mark", 'M', 9000), 
                  new Employee("E004", 37, "Ritu", 'F', 11000),
                  new Employee("E005", 32, "Anuj", 'M', 6000), 
                  new Employee("E006", 28, "Amy", 'F', 14000));
     double avg = empList.stream().collect(Collectors.averagingInt(Employee::getSalary));
     System.out.println("Average employee salary- " + avg);
  }
}

Output

Average employee salary- 8833.333333333334

That's all for this topic Java Stream - Collectors.averagingInt(), averagingLong(), averagingDouble(). 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 - Collectors.summingInt(), summingLong(), summingDouble()
  2. Java Stream - Collectors.joining() With Examples
  3. Java Stream - findFirst() With Examples
  4. Java Stream - noneMatch() With Examples
  5. Java Stream - limit() With Examples

You may also like-

  1. Reflection in Java - Getting Constructor Information
  2. Serialization Proxy Pattern in Java
  3. StringJoiner Class in Java With Examples
  4. Binary Tree Traversal Using Breadth First Search Java Program
  5. Java Collections Interview Questions And Answers
  6. Installing Anaconda Distribution On Windows
  7. Autowiring in Spring Using XML Configuration
  8. Spring Batch Processing With List of Objects in batchUpdate() Method

Thursday, April 21, 2022

Java Stream - Collectors.summingInt(), summingLong(), summingDouble()

Collectors Class in Java Stream API is an implementation of Collector interface and provides many useful operations that can be used with Java Streams. One such group of methods, which can be classified as Collectors.summing methods, is used to add the stream elements. There are following summing methods for types int, long and double respectively.

  1. public static <T> Collector<T,?,Integer> summingInt(ToIntFunction<? super T> mapper)- This method is used to get the sum of stream of ints, if there is no element in the stream then the result is 0.
  2. public static <T> Collector<T,?,Long> summingLong(ToLongFunction<? super T> mapper)- This method is used to get the sum of stream of longs, if there is no element in the stream then the result is 0.
  3. public static <T> Collector<T,?,Double> summingDouble(ToDoubleFunction<? super T> mapper)- This method is used to get the sum of stream of doubles, if there is no element in the stream then the result is 0.

As you can notice the argument passed to these methods are of type ToIntFunction, ToLongFunction and ToDoubleFunction respectively. These are functional interfaces which are implementd to extract the property to be summed meaning their implementation produces a int-valued, long-valued and double-valued result.

Collectors.summingInt() Java example

In this example we’ll get the sum of the List elements where elements are of type Integer.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CollectorSumming {

  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(11, 5, 2, 10, 1);
      int sum = numbers.stream().collect(Collectors.summingInt(Integer::intValue));
      System.out.println("Sum of list elements: " + sum);

  }
}

Output

Sum of list elements: 29

Collectors.summingLong() Java example

In this example we’ll get the sum of the List elements where elements are of type Long.

public class CollectorSumming {

  public static void main(String[] args) {
    List<Long> numbers = Arrays.asList(11L, 5L, 2L, 10L, 1L);
      long sum = numbers.stream().collect(Collectors.summingLong(Long::longValue));
      System.out.println("Sum of list elements: " + sum);
  }
}

Output

Sum of list elements: 29

Collectors.summingDouble() Java example

In this example we’ll get the sum of the List elements where elements are of type Double.

public class CollectorSumming {

  public static void main(String[] args) {
    List<Double> numbers = Arrays.asList(11.5, 5.0, 2.65, 10.34, 7.89);
    double sum = numbers.stream().collect(Collectors.summingDouble(Double::doubleValue));
      System.out.println("Sum of list elements: " + sum);
  }
}

Output

Sum of list elements: 37.38

Collectors.summingInt with Custom Object Example

In this example we’ll use summing method to get the sum of salaries for all the employees.

Employee Class

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
  @Override
  public String toString() {
      return "Emp Id: " +  getEmpId() + " Name: " + getName() + " Age: " + getAge();
  }
}
public class CollectorSumming {

  public static void main(String[] args) {
     List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                  new Employee("E002", 35, "Shelly", 'F', 8000), 
                  new Employee("E003", 24, "Mark", 'M', 9000), 
                  new Employee("E004", 37, "Ritu", 'F', 11000),
                  new Employee("E005", 32, "Anuj", 'M', 6000), 
                  new Employee("E006", 28, "Amy", 'F', 14000));
    int sum = empList.stream().collect(Collectors.summingInt(Employee::getSalary));
      System.out.println("Sum of employee salaries: " + sum);
  }
}

Output

Sum of employee salaries: 53000

That's all for this topic Java Stream - Collectors.summingInt(), summingLong(), summingDouble(). 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 - Collectors.averagingInt(), averagingLong(), averagingDouble()
  2. Java Stream - Collectors.teeing() With Examples
  3. Java Stream - Collectors.partitioningBy() With Examples
  4. Spliterator in Java
  5. Java Stream - limit() With Examples

You may also like-

  1. JVM Run-Time Data Areas - Java Memory Allocation
  2. Shallow Copy And Deep Copy in Java Object Cloning
  3. Is String Thread Safe in Java
  4. Java Program to Get Current Date and Time
  5. Angular First App - Hello world Example
  6. Java Application With User Input in Docker Container
  7. Spring MVC Pagination Example Using PagedListHolder
  8. Spring Boot Hello World Web Application Example

Wednesday, April 20, 2022

How to Reverse a Doubly Linked List in Java

In this post we’ll see a Java program to reverse a doubly linked list.

Reversing a doubly linked list

In a doubly Linked list each node stores reference to both next and previous nodes. For reversing a doubly linked list, for each node previous and next references should be swapped.

Once the doubly linked list is reversed head and tail references should also be adjusted accordingly.

reverse doubly linked list java

Java program to reverse a doubly linked list can be written using both-

Java program to reverse a doubly linked list – Iterative

public class ReverseDLL {
 private Node head;
 private Node tail;
 static class Node{
  //data
  int i;
  // next node in the list
  Node next;
  // previous node in the list
  Node prev;
  Node(int i){
   this.i = i;
  }
  public void displayData(){
   System.out.print(i + " ");
  }
 }
 // constructor
 public ReverseDLL(){
  this.head = null;
  this.tail = null;
 }
 
 public boolean isEmpty(){
  return head == null;
 }
 
 public void insertFirst(int i){
  //Create a new node
  Node newNode = new Node(i);
  // if first insertion tail should
  // also point to this node
  if(isEmpty()){
   tail = newNode;
  }else{
   head.prev = newNode;
  }
  newNode.next = head;
  head = newNode;
 }
 
 // Method for forward traversal
 public void displayForward(){
  System.out.println("Forward display");
  Node current = head;
  while(current != null){
   current.displayData();
   current = current.next;
  }
  System.out.println("");
 }
 // Method to traverse and display all nodes
 public void displayBackward(){
  System.out.println("Backward display");
  Node current = tail;
  while(current != null){
   current.displayData();
   current = current.prev;
  }
  System.out.println("");
 }
 // Method for reversing doubly linked list
 public void reverseList(){
  Node previous = null;
  //change reference head becomes tail in reversal
  tail = head;
  Node current = head;
  while(current != null){
   // swap prev and next for the current node
   previous = current.prev;
   current.prev = current.next;
   current.next = previous;
   // to move to next node current.prev has to be called
   // as that has reference to next node now
   current = current.prev;
  }
  if(previous != null){
   head = previous.prev;
  }
 }
 public static void main(String[] args) {
  ReverseDLL list = new ReverseDLL();
  list.insertFirst(4);
  list.insertFirst(3);
  list.insertFirst(2);
  list.insertFirst(1);
  list.displayForward();
  
  list.reverseList();
  list.displayForward();
  list.displayBackward();
 }
}

Output

Forward display
1 2 3 4 
Forward display
4 3 2 1 
Backward display
1 2 3 4 

Java program to reverse a doubly linked list – Recursive

In the recursive method for reversing a doubly linked linked list method is called passing the first node then the method is recursively called by passing the next node (node.next).

public class ReverseDLL {
 private Node head;
 private Node tail;
 static class Node{
  //data
  int i;
  // next node in the list
  Node next;
  // previous node in the list
  Node prev;
  Node(int i){
   this.i = i;
  }
  public void displayData(){
   System.out.print(i + " ");
  }
 }
 // constructor
 public ReverseDLL(){
  this.head = null;
  this.tail = null;
 }
 
 public boolean isEmpty(){
  return head == null;
 }
 
 public void insertFirst(int i){
  //Create a new node
  Node newNode = new Node(i);
  // if first insertion tail should
  // also point to this node
  if(isEmpty()){
   tail = newNode;
  }else{
   head.prev = newNode;
  }
  newNode.next = head;
  head = newNode;
 }
 
 // Method for forward traversal
 public void displayForward(){
  System.out.println("Forward display");
  Node current = head;
  while(current != null){
   current.displayData();
   current = current.next;
  }
  System.out.println("");
 }
 // Method to traverse and display all nodes
 public void displayBackward(){
  System.out.println("Backward display");
  Node current = tail;
  while(current != null){
   current.displayData();
   current = current.prev;
  }
  System.out.println("");
 }

  public Node reverseListRec(Node current){
    if (current == null) {
      return current;
    }
    if (current.next == null) {
    current.prev = null;
      return current;
    }
    Node node = reverseListRec(current.next);
    current.next.next = current;    
    current.prev = current.next;
    current.next = null;
    return node;
  }
 public static void main(String[] args) {
  ReverseDLL list = new ReverseDLL();
  list.insertFirst(4);
  list.insertFirst(3);
  list.insertFirst(2);
  list.insertFirst(1);
  list.displayForward();
  // change tail reference before calling reverse method
  list.tail = list.head;
  Node node = list.reverseListRec(list.head);
  // change head to point to returned node
  list.head = node;
  //list.reverseList();
  list.displayForward();
  list.displayBackward();
 }
}

Output

Forward display
1 2 3 4 
Forward display
4 3 2 1 
Backward display
1 2 3 4 

In the recursive method for reversing doubly linked list reference is reversed in the following lines.

current.next.next = current;
current.prev = current.next;
Following image tries to clarify what this line does.
reverse a doubly linked list

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

>>>Return to Java Programs Page


Related Topics

  1. How to Reverse a Linked List in Java
  2. Deque Implementation in Java Using Doubly Linked List
  3. Binary Tree Implementation in Java - Insertion, Traversal And Search
  4. How to Convert Array to ArrayList in Java
  5. Radix Sort Program in Java

You may also like-

  1. Binary Search Program in Java
  2. Setting And Getting Thread Name And Thread ID - Java Program
  3. Converting int to String in Java
  4. Difference Between Two Dates in Java
  5. Java Concurrency Interview Questions And Answers
  6. How HashSet Works Internally in Java
  7. Spring Batch Processing Using JDBCTemplate batchUpdate() Method
  8. HDFS Federation in Hadoop Framework

Tuesday, April 19, 2022

How to Read Properties File in Spring Framework

This post shows how to read properties file in Spring framework using XML configuration or by using @PropertySource Annotation.

There are scenarios when you have to provide few configuration properties in order to configure the resource like in case of Database you need to provide driver class, DB location, user name and password or in case of sending mail through your application you need to provide properties like SMTP host, user name, password.

Many a times developers put all these details in the Spring XML configuration file itself which is not a good practice. It’s better to put them in a properties file that way you can have specific properties files like db.properties, mail.properties, app.properties etc. and read the property value from that properties file rather than hard coding them. Another advantage is that any change in any setting will require you to change the specific properties file only.

In Spring reading properties file and setting property values can be done using-

  • XML configuration
  • Using @PropertySource Annotation

Reading properties file in Spring using XML configuration

Suppose you have your Database properties in a properties file called db.properties residing under config folder under resources folder.

db.properties (for connecting to MYSQL DB)

db.driverClassName=com.mysql.jdbc.Driver db.url=jdbc:mysql://localhost:3306/netjs db.username=root db.password=password pool.initialSize=5

Then you can use ${property key} placeholders in <bean> definitions. In order to resolve these placeholders you must register a PropertySourcesPlaceholderConfigurer. This happens automatically when using <context:property-placeholder> in XML.

Full XML configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!--  For reading properties files --> 
    <context:property-placeholder location="classpath:config/db.properties" />
    
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
        <property name="dataSource" ref="dataSource"></property>  
    </bean>  
    <bean id="employeeDAO" class="org.netjs.daoimpl.EmployeeDAOImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>  
    </bean>
    
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value = "${db.driverClassName}" />
        <property name="url" value = "${db.url}" />
        <property name="username" value = "${db.username}" />
        <property name="password" value = "${db.password}" />
        <property name="initialSize" value = "${pool.initialSize}" />
    </bean>

</beans>

Reading properties file in Spring using @PropertySource Annotation

Spring also has @PropertySource annotation (added in Spring 3.1) for reading properties file. It can be used with @Value annotation to read the value of the given property.

Example Program

Given a file db.properties (as used above) containing the key/value pairs, the following Configuration class uses @PropertySource along with @Value annotation to read properties.

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@PropertySource("classpath:config/db.properties")
public class DBConfig {
  @Value("${db.driverClassName}")
  private String dbDriverClass;
  @Value("${db.url}")
  private String dbUrl;
  @Value("${db.username}")
  private String dbUser;
  @Value("${db.password}")
  private String dbPwd;
    
  @Bean
  public BasicDataSource dataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(dbDriverClass);
    ds.setUrl(dbUrl);
    ds.setUsername(dbUser);
    ds.setPassword(dbPwd);
    return ds;
  }
    
  //register PropertySourcesPlaceholderConfigurer
  //in order to resolve ${...} placeholders
  @Bean
  public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
    return new PropertySourcesPlaceholderConfigurer();
  }
}

Here you can see how fields are annotated with @Value(property key name) annotation in order to map them with the specific property in the .properties file.

In order to resolve ${...} placeholders in <bean> definitions or @Value annotations using properties from a PropertySource, one must register a PropertySourcesPlaceholderConfigurer. This happens automatically when using <context:property-placeholder> in XML (in above example), but must be explicitly registered using a static @Bean method when using @Configuration classes. That’s what is done in DBConfig class.

If you want to run this you can use the following class-

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

public class App {

 public static void main(String[] args) {
  AbstractApplicationContext context = new AnnotationConfigApplicationContext
   (DBConfig.class);
  BasicDataSource ds = (BasicDataSource)context.getBean("dataSource");
  System.out.println("URL - " + ds.getUrl());
 }
}

Using @PropertySource Annotation with Spring’s Environment

Rather than using @Value annotation, Environment should be used to read properties file in Spring. Actually @PropertySource annotation adds a PropertySource to Spring's Environment so that can be used to make your code simpler.

Reading properties file example with Environment

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:config/db.properties")
public class DBConfig {
 @Autowired
 private Environment env;
 
 @Bean
 public BasicDataSource dataSource() {
  BasicDataSource ds = new BasicDataSource();
  System.out.println("User " + env.getProperty("db.username"));
  ds.setDriverClassName(env.getProperty("db.driverClassName"));
  ds.setUrl(env.getProperty("db.url"));
  ds.setUsername(env.getProperty("db.username"));
  ds.setPassword(env.getProperty("db.password"));
  return ds;
 }
}

In that case you just need to Autowire (or Inject) Environment into your Config class and use Environment object to get property value.

Property overriding with @PropertySource

In cases where a given property key exists in more than one .properties file, the last @PropertySource annotation processed will 'win' and override. For example, given two properties files a.properties and b.properties, consider the following two configuration classes that reference them with @PropertySource annotations:

 @Configuration
 @PropertySource("classpath:/com/myco/a.properties")
 public class ConfigA { }

 @Configuration
 @PropertySource("classpath:/com/myco/b.properties")
 public class ConfigB { }

The override ordering depends on the order these classes are registered with the application context.

Using ignoreResourceNotFound attribute with @PropertySource

In case your properties file is optional and you don't want exception to be thrown if it doesn't exist you can use ignoreResourceNotFound attribute and set it as true. Default is false.

As example

If you want to load test.properties file and want to ignore the resource if not found then you can do it as-

@Configuration
@PropertySource(value="classpath:config/test.properties", ignoreResourceNotFound=true)
public class DBConfig {
 @Autowired
 private Environment env;
 ..........
 ..........

That's all for this topic How to Read Properties File in Spring Framework. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Data access in Spring framework
  2. Spring JdbcTemplate Select Query Example
  3. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
  4. @Resource Annotation in Spring Autowiring
  5. Spring Profiles With Examples

You may also like-

  1. Dependency Injection in Spring Framework
  2. Spring Component Scan Example
  3. Difference Between Array And ArrayList in Java
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. Executor And ExecutorService in Java With Examples
  6. Difference Between CountDownLatch And CyclicBarrier in Java
  7. Java Multithreading Interview Questions And Answers
  8. Unzip File in Java