Counting Characters and Permutations of Arrays

I just finished the “Basic” Java exercises at today and made the last two — #38 and #39 — a bit harder than they needed to be. #38 asks for you to “write a Java program to count the letters, spaces, numbers and other characters of an input string”. I interpreted this to mean each individual character, for instance, how many “h” or “L” or whatever. The solution suggests the use of Character.isLetter(), Character.isDigit(), and Character.isSpaceChar(), but I like my way better anyway:

import java.util.Scanner;

public class Exercise38 {
  public static void main(String[] args){
    Scanner in = new Scanner(;
    System.out.println("Enter a line of text: ");
    String userLine = in.nextLine();

    char[] userChars = userLine.toCharArray();
    int len = userLine.length();
    int[] charFrequency = new int[len];

    boolean counted = false;

    for(int ii = 0; ii < len; ++ii){
      for(int jj = 0; jj < ii; ++jj){
        counted = false;
          counted = true;

    System.out.format("In your string: \n\t\"%s\"\nthere were...\n", userLine);

    for(int ii = 0; ii < len; ++ii){       if(charFrequency[ii] > 0){
        System.out.format("\t%d \'%c\' character(s)\n", charFrequency[ii], userChars[ii]);


This above code will count each individual character in a user-inputted String. Below is some sample output:

15:14 |aww@airy Basic| javac; java Exercise38
Enter a line of text:
This is a line of text
In your string:
	"This is a line of text"
there were...
	1 'T' character(s)
	1 'h' character(s)
	3 'i' character(s)
	2 's' character(s)
	5 ' ' character(s)
	1 'a' character(s)
	1 'l' character(s)
	1 'n' character(s)
	2 'e' character(s)
	1 'o' character(s)
	1 'f' character(s)
	2 't' character(s)
	1 'x' character(s)

The second Exercise with instructions which I misinterpreted was Exercise 39. This one asks you to “write a Java program to create and display unique three-digit number using 1, 2, 3, 4. Also count how many three-digit numbers are there.” I assumed that this wasn’t meant to be hard-coded. That any numbers should be able to be used. I also expanded the code to allow arrays of any length. In essence, what I wrote was a Java program which gives all of the permutations of an array of numbers:

public class Exercise39 {
  public static void main(String[] args){

    int[] testArray = { 7, 3, 2 };


  public static void printArray(int[][] printMe){
    int nRows = printMe.length;
    int nCols = printMe[0].length;

    for(int ii = 0; ii < nRows; ++ii){
      System.out.format("%d\t : ", ii+1);
      for(int jj = 0; jj < nCols; ++jj){
        System.out.print(printMe[ii][jj] + " ");

  public static int[][] permuteIntegerArray(int[] array){
    int n = array.length;
    int nFactorial = integerFactorial(n);
    int nMinus1Factorial = integerFactorial(n-1);
    int[][] permuted = new int[nFactorial][n];

      permuted[0][0] = array[0];
      return permuted;
    } else if(n==2){
      permuted[0][0] = array[0];
      permuted[0][1] = array[1];
      permuted[1][0] = array[1];
      permuted[1][1] = array[0];
      return permuted;
    } else {
      int[][] smallerPermuted = new int[nMinus1Factorial][n-1];
      int[]   smallerArray    = new int[n-1];
      int counter = 0;
      for(int ii = 0; ii < n; ++ii){
        for(int jj = ii*nMinus1Factorial; jj < (ii+1)*nMinus1Factorial; ++jj){
          permuted[jj][0] = array[ii];
        counter = 0;
        for(int jj = 0; jj < n; ++jj){
          if(ii==jj) continue;
          smallerArray[counter] = array[jj];
        smallerPermuted = permuteIntegerArray(smallerArray);

        for(int jj = 0; jj < nMinus1Factorial; ++jj){
          for(int kk = 0; kk < n-1; ++kk){             permuted[jj+ii*nMinus1Factorial][kk+1] = smallerPermuted[jj][kk];     } } } }     return permuted;   }   public static int integerFactorial(int base){     int returnValue = base;     while(base > 2){
      returnValue *= base;
    return returnValue;

This is arguably much cooler than the example solution, though it is a bit long. I feel as though it can be shortened — any suggestions would be appreciated! Sample output below:

15:25 |aww@airy Basic| javac; java Exercise39

1	 : 7 3 2
2	 : 7 2 3
3	 : 3 7 2
4	 : 3 2 7
5	 : 2 7 3
6	 : 2 3 7

Java Potpourri I

I took a trip to Barnes & Noble today and found a really neat book, “Sams Teach Yourself Java in 24 Hours“. After working through the first few chapters, I found a few interesting odds and ends. Specifically (1) how to work with Strings, (2) switch statements, and (3) working with date and time. Strings are quite easy to work with in Java, and no imports are necessary:

public class Strings {

  public static void main(String args[]){

    String test = "test";
    String word = "word";

    System.out.println(test + " has " + test.length() + " letters.");

    String uppercase = "UPPERCASE";

    System.out.println("Does " + uppercase + " contain \"CASE\"?");

    System.out.println("Okay, where is it?");

    System.out.println("Does " + test + " contain \"CASE\"?");



Several methods are used above, including equals(), which returns true if two Strings are the same, character-by-character; length(), which returns the length of a given String; toUpperCase() and toLowerCase() which convert all of the characters in a string to uppercase and lowercase, respectively; contains() which returns true if a String contains a given substring; and indexOf() which first checks if a String contains a given substring and then returns the index of the beginning of that substring if it is contained within the String of interest.

Additional String methods are described in the Oracle Java tutorials, including charAt(), which retrieves the character of a particular String at the desired index; concat(), which concatenates two Strings (though this can more easily be achieved with a +=); and format(), which allows a C-style construction of Strings from variables of different data types:

public class Format {

  public static void main(String args[]){

    int myInt = 4;
    double myDouble = 3.5;
    String myString = "myString";

    String myFormat = "";

    myFormat = String.format("myInt: %d\nmyDouble: %f\nmyString: %s",
      myInt, myDouble, myString);




Another small difference I found today between Java and C++ is that Java allows underscores “_” in integer values to help break up the powers of ten. For instance:

public class Underscores {

  public static void main(String args[]){

    int a = 17_000;
    int b = 17000;

    System.out.println("a = " + a);
    System.out.println("b = " + b);



will print

15:28 |aww@airy Underscores| javac 

15:28 |aww@airy Underscores| java Underscores
a = 17000
b = 17000

while in C++, the following code returns an error

#include <iostream>
using namespace std;

int main(){

  cout << "This is a test." << endl;

  int a = 17_000;
  int b = 17000;

  cout << "a = " << a << endl;
  cout << "b = " << b << endl;

  return 0;


Underscores are also allowed in Perl, but not, apparently, in C++. Another interesting thing I came across while reading this book is that, in Java, switch statements can take Strings as arguments:

public class Switch {

  public static void main(String args[]){

    String controller = "greeting";

      case "greeting":
      case "farewell":
      case "Hawaiian":



I thought I remembered that only integers could be used in switch statements in C++, so I wrote a bit of code to check:

#include <iostream>

using namespace std;

int main(){

  char a = 'a';
  char b = 'b';

  char controller = a;

    case 'a':
      cout << "controller = " << a << endl;
    case 'b':
      cout << "controller = " << b << endl;

  return 0;


The C++ code runs fine, so I was mis-remembering. Finally, the book gives an example for working with dates and times in Java. Here’s my slightly edited version from what the book gives:

import java.time.*;
import java.time.temporal.*;

class Clock {

  public static void main(String[] args){

    // get current time and date
    LocalDateTime now =;

    int hour   = now.get(ChronoField.HOUR_OF_DAY);
    int minute = now.get(ChronoField.MINUTE_OF_HOUR);
    int month  = now.get(ChronoField.MONTH_OF_YEAR);
    int day    = now.get(ChronoField.DAY_OF_MONTH);
    int year   = now.get(ChronoField.YEAR);

    // display greeting
    if(hour < 12){
      System.out.println("Good morning!");
    } else if(hour < 17){       System.out.println("Good afternoon!");     } else {       System.out.println("Good evening!");     }     // begin time message by showing the minutes     System.out.print("It's");     if(minute != 0){       System.out.print(" " + minute + " ");       System.out.print( (minute != 1) ? "minutes" : "minute");       System.out.print(" past");     }     // display the hour     System.out.print(" ");     System.out.print((hour > 12) ? (hour - 12) : hour);
    System.out.print((hour > 11) ? " pm" : " am");
    System.out.print(" on ");

    // display the name of the month
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
      case 8:
      case 9:
      case 10:
      case 11:
      case 12:

    // display the date and year
    System.out.print(" " + day + ", " + year + ".");



Once the initial hurdle of understanding the syntax is overcome (now.get(ChronoField…)), dates and times seem to be pretty easy to work with in Java.

Reversing a number in Java

I have a lot of experience with C++. So while learning about if-else statements and loops is interesting, it’s essentially the same between C++ and Java. That being said, I think the best way to learn a programming language is to just write code in that language. So I’ve looked around for examples online and I found a few decent tutorial sites. The following code is taken from the second last site linked in the previous sentence, and the purpose of the code is to reverse a number (so 34 would become 43, 57 would become 75, etc.).

I don’t want to just copy the code from this example, but I did need to look up how to take user input. It seems like the easiest way is with java.util.Scanner, which can read in single variables or lines of text from the command line. Also, I wanted to look up how to construct Strings, because I wanted to avoid a case where “90” might be reversed to “9” instead of “09”. I want the output to be a String, not an integer.

import java.util.Scanner;

public class ReverseNumber {

  public static String reverseIt(int oldInt){

    String newInt = "";
    newInt += oldInt%10;
    newInt += (oldInt - (oldInt%10))/10;
    return newInt;


  public static void main(String args[]){

    Scanner userInt = new Scanner(;

    System.out.println("Enter any number between 10 and 99: ");
    int myInt = userInt.nextInt();

    System.out.println("You entered: " + myInt);
    System.out.println("Reversed, that is: " + reverseIt(myInt));



…it works! Strings are pretty easy to work with in Java, too. And since they’re a basic data type, no extra packages need to be included. This is in stark contrast to C++, where strings are more complex and a bit more difficult to work with. Strings can also be constructed with a StringBuilder() object or using String.format() for a more C-style look.

Getting Started with Java

Although, technically, I’ve done some Java programming before (around 2008), I’m more or less starting from scratch here. I’m getting set up to write some Java code on my Ubuntu machine (“ooby”). Getting started with Java on a Linux-based system requires the Java SE Development Kit (currently JDK 8) and a text editor. I use nano because I’m a pleb. (I once coded a website entirely in notepad on Windows and made all of the graphics in paint. I’ve since become only slightly more sophisticated.) The JDK can be installed very easily on Ubuntu, with just an apt-get:

14:21 |andrew@ooby java_examples| sudo apt-get install default-jdk

Apparently, this is all that needs to be done. Then, a “Hello World” program can be written (saved as

 * The HelloWorldApp class implements an application that
 * simply prints "Hello World!" to standard output.
class HelloWorldApp {
  public static void main(String[] args) {
    System.out.println("Hello World!"); // display the string.

This can be compiled and run with the following commands:

14:24 |andrew@ooby java_examples| javac 

14:24 |andrew@ooby java_examples| java HelloWorldApp
Hello World!

where the output is seen after the java command. That’s it! All set up to code some Java. Now, to set up the same thing on my MacBook Air (“airy”). I downloaded the JDK for Mac OS (“jdk-8uversion-macosx-x64.dmg”) from this page. You need to create an Oracle account to download this software. Installing the JDK *.dmg file allows the above code to run on Mac OS, as well.