w3resource

Java Method Exercises: Print characters between two characters

Java Method: Exercise-9 with Solution

Write a Java method to print characters between two characters (i.e. A to P ).

Note: Prints 20 characters per line

Sample Solution:

Java Code:

public class Exercise9 {
   public static void main(String[] args) {
        print_Chars('(', 'z', 20);
    }
 public static void print_Chars(char char1, char char2, int n) {
        for (int ctr = 1; char1 <= char2; ctr++, char1++) {
            System.out.print(char1 + " ");
            if (ctr % n == 0) System.out.println("");
        }
		System.out.print("\n");
    }
}

Sample Output:

( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ;                                                                       
< = > ? @ A B C D E F G H I J K L M N O                                                                       
P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c                                                                       
d e f g h i j k l m n o p q r s t u v w                                                                       
x y z

Flowchart:

Flowchart: Print characters between two characters

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java method to compute the future investment value at a given interest rate for a specified number of years.
Next: Write a Java method to check whether an year (integer) entered by the user is a leap year or not.

What is the difficulty level of this exercise?



Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH