Kotlin Koan—Part 13

Kotlin has nice extensions on Collection classes. JDK has provided developers a way to sort collections for a long time now, but often times, it’s done with external classes such as Collections. This puts us in a odd position of using procedural programming when performing operations such as sorting a collection.

A more OOP approach would be to have a sort method directly on a Collection as opposed to passing a collection to an external class with a static method. Kotlin extends Java collections by using its extension feature to complement the collection classes found in JDK.

Here is an example that demonstrates how to sort an ArrayList in Java.

fun task12(): List {
    val lst =  arrayListOf(1, 5, 2)
    lst.sortDescending()
    return lst
}

If all fairness to Java, JDK 8 did address this issue. Here is the equivalent Java code that does the same thing.

public class CollectionSort {
    public List sortList(){
        List lst = Arrays.asList(1, 5, 2);
        lst.sort(Comparator.reverseOrder());
        return lst;
    }
}

I’m not going to complain too much about the Java 8 syntax, but I think sortDescending() and sortAcending() is more readable than Comparator.natualOrder() and Comparator.reverseOrder(). However, the Kotlin approach is much superior to JDK 7 and earlier.

You can read the previous post here.

Advertisements

Bubble Sort—Java

The bubble sort is a very common algorithm that many computer science students are expected to learn. Yesterday I did a post that shows a Python implementation of the bubble sort which you can view here. Today I will demonstrate the same technique in Java.

import java.util.Arrays;

public class BubbleSort {

public static void main(String [] args){
Integer [] nums = {9, 4, 2, 1, 10};
System.out.println("Unsorted is " + Arrays.toString(nums));

bubbleSort(nums);
System.out.println("Sorted is " + Arrays.toString(nums));
}

public static<T extends Comparable> void bubbleSort(T [] array){
int n = array.length;
T temp;

for(int i = 0; i < n; i++){
for (int j = 1; j  0){
//Swap the elements
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
}
}

Java is a little more verbose than Python. Since it is a statically typed language (which means you have to declare the data type up front, as opposed to Python’s duck typing method), I chose to use generics to implement this sort.

Generics were introduced in JDK 1.5. They allow us to write code that is widely applicable to many types of objects without forcing us to use the Object class. You can find a wide use of generics in the java.util package.

In this case, I declared my generic method like this

public static<T extends Comparable> void bubbleSort(T [] array){

Let’s go through this one word at a time.

  1. public—This is the keyword that makes this method publically available
  2. static—This keyword attaches this method to the class rather than an object
  3. <T extends Comparable>—This is the code that declares this method to be a generic method. T is the type of the object, followed by extends Comparable which means that any object that implements the Comparable interface is accetable to this method.
  4. T [] array—This declares an array of type T (which is any class that implements Comparable in this case)

Now that we have declared this to be a generic method, this method will work with any object that implements the Comparable interface. The Comparable interface is widely used throughout Java in sorting. It declares a compareTo(T obj) method which returns a positive number when an item is greater than the comparing object, zero when the two objects are equal, and a negative number when the comparing object is less than the other object.

Since this interface exists, Java lets us sort anything that implements this interface easily. That allows programmers a high degree of freedom and flexibility when creating custom classes because the programmer gets to decide how one object is greater than, less than, or equal to another object.

We apply the Comparable interface to this bubble sort method here

if(array[j - 1].compareTo(array[j]) > 0){
//Swap the elements
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}

If the left hand portion array[j - 1].compareTo(array[j]) is 0, then these two items are 0. If the result is a negative number then array[j - 1] is less than array[j], otherwise array[j - 1] is greater than array[j] and it needs to get swapped.

When run, we get this output

Unsorted is [9, 4, 2, 1, 10]
Sorted is [1, 2, 4, 9, 10]

Java Data Types

Almost everything we do in computer programming involves data. In many cases, the data itself is more valuable then the program. Many tax programs are written, but they all work on the same data. We may write tax software that displays fancy charts of your AGI over a period of 5 years, or we may write a program that calculates your net income. These programs are very worthwhile without data.

Java has two main ways of representing data. The first set of data types are called primitives. They are as follows

  • byte (8-bit signed)
  • short (16-bit signed)
  • int (32-bit signed)
  • long (64-bit signed)
  • float (32-bit)
  • double (64-bit)
  • boolean (true/false)
  • char (16-bit unicode characters)

Whole Numbers

Let’s discuss each of these data types in turn starting with byte. A byte is smallest integer variable available to Java programmers and can hold values between -128 and 127. I generally use bytes in situations where I need to be conscious of my memory usage or when I’m programming on the web and need to transfer information from one site to another.

We can make a byte like this

byte b = 120; //This variable stores the number 120

Next up the ladder is the short. Like bytes, shorts contain whole numbers between -32768 and 32767. Use shorts when you need to be concerned about memory usage.

Create a short by

short s = 120; //This variable also store the number 120

The next primitive data type is int. This is one of the most commonly used numeric data type in Java programs. The int primitive data type stores values between -2147483648 and 2147483647.

Create an int by

int i = 1; //This int variable holds the number 1

The long is the final whole number data type. At 64-bits this variable comes in as a monster that can store values between -9223372036854775808 and -9223372036854775807. Longs make great candidate in scientific applications where the program may end up processing large sets of data. I also see them used to store primary keys in database programming.

Create a long by

long l = 100; //This long variable holds the number 100

Decimals and Fractions

There are times where you need to store numeric data that is not a whole number. For example, in many cases you may need to use the number PI (3.14159) in a calculation. Our next two data types hold such numbers.

The first is float, which is a floating point number (hence the name). This is a 32-bit variable that can store 1.4E-45 to 3.4028235E38. Double is the more commoly used data type (64-bits) and stores values ranging from 4.9E-324 to 1.7976931348623157E308.

float f = 5.99; //Make a float that stores the number 5.99
double d = -1.00; //Make a double that stores the number -1.00;

Never store money in these data types! The internal mechanics of these data types cause a loss in percision that can result in inaccuracies. Money should always get stored in the BigDecimal object.

Non Numeric Data

Java has the ability to store non-numeric data. Sometimes all a programmer needs to know if when something it True or False. The boolean data type is used for such a purpose.

boolean bTrue = true; //This boolean is true
bTrue = false; //Now it's false

We can also store unicode characters with the char type.

char c = 'a'; //Store the letter a
char tab = '\t'; //Stores  a tab character

Objects

Java also supports another data type that is not a primitive. These are called objects (to be discussed in another post). At this point there is one critical object to discuss that is called the String. String is a special kind of object that supports words and textual data.

//Since Strings are objects, so we use the 'new' keyword to create them
String str = new String("Hi! I'm a string of letters");

//But you can also do this since Java has special built-in support for Strings
String anotherString = "Hi! I'm another String!";

A working example

Below is a working example program that you can use to see the data types discussed above in action.


public class DataTypes {

    public static void main(String [] args){
        byte byteMin = Byte.MIN_VALUE;
        byte byteMax = Byte.MAX_VALUE;

        System.out.println("Bytes are the smallest data types (8-bit) and represent whole numbers.");
        System.out.println("The smallest value you can store in a byte is " + byteMin + " and" +
                " the maximum value is " + byteMax);
        System.out.println("");

        short shortMin = Short.MIN_VALUE;
        short shortMax = Short.MAX_VALUE;

        System.out.println("Shorts are one step larger than bytes (16-bit) and represent whole numbers.");
        System.out.println("The smallest value you can store in a short is " + shortMin + " and" +
                " the maximum value is " + shortMax);
        System.out.println("");

        int intMin = Integer.MIN_VALUE;
        int intMax = Integer.MAX_VALUE;

        System.out.println("Integers are one step larger than shorts (32-bit) and represent whole numbers.");
        System.out.println("The smallest value you can store in an integer is " + intMin + " and" +
                " the maximum value is " + intMax);
        System.out.println("");

        long longMin = Long.MIN_VALUE;
        long longMax = Long.MAX_VALUE;

        System.out.println("Longs are the largest of whole number data type (64-bit).");
        System.out.println("The smallest value you can store in a long is " + longMin + " and" +
                " the maximum value is " + longMax);
        System.out.println("");

        float floatMin = Float.MIN_VALUE;
        float floatMax = Float.MAX_VALUE;

        System.out.println("Floats represent decimal types. (32-bit)");
        System.out.println("The smallest value you can store in a float is " + floatMin + " and" +
                " the maximum value is " + floatMax);
        System.out.println("");

        double doubleMin = Double.MIN_VALUE;
        double doubleMax = Double.MAX_VALUE;

        System.out.println("Doubles also represent decimal types. (64-bit)");
        System.out.println("The smallest value you can store in a double is " + doubleMin + " and" +
                " the maximum value is " + doubleMax);
        System.out.println("");

        boolean booleanFalse = false;
        boolean booleanTrue = true;

        System.out.println("Booleans store true or false values.");
        System.out.println("booleanFalse = " + booleanFalse);
        System.out.println("booleanTrue = " + booleanTrue);
        System.out.println("");

        char charMin = Character.MIN_VALUE;
        char charMax = Character.MAX_VALUE;

        System.out.println("char represents a 16-bit unicode character");
        System.out.println("The smallest char value is " + charMin + " and the largest is " + charMax);
        System.out.println("");

        String string = new String("I'm a string of text");
        System.out.println("Java also has the Object data type. This is different from our other data types.");
        System.out.println("It this example, we have and object that is a String. Strings hold text.");
        System.out.println("string = " + string);
    }
}

This is the output of the program when executed

Bytes are the smallest data types (8-bit) and represent whole numbers.
The smallest value you can store in a byte is -128 and the maximum value is 127

Shorts are one step larger than bytes (16-bit) and represent whole numbers.
The smallest value you can store in a short is -32768 and the maximum value is 32767

Integers are one step larger than shorts (32-bit) and represent whole numbers.
The smallest value you can store in an integer is -2147483648 and the maximum value is 2147483647

Longs are the largest of whole number data type (64-bit).
The smallest value you can store in a long is -9223372036854775808 and the maximum value is 9223372036854775807

Floats represent decimal types. (32-bit)
The smallest value you can store in a float is 1.4E-45 and the maximum value is 3.4028235E38

Doubles also represent decimal types. (64-bit)
The smallest value you can store in a double is 4.9E-324 and the maximum value is 1.7976931348623157E308

Booleans store true or false values.
booleanFalse = false
booleanTrue = true

char represents a 16-bit unicode character
The smallest char value is  and the largest is ￿

Java also has the Object data type. This is different from our other data types.
It this example, we have and object that is a String. Strings hold text.
string = I'm a string of text

Getting Started

Java is one of the most widely used programming languages today. According to Oracle, over 3 Billion devices run Java. Java is used in a wide variety of applications. For example, many Android applications are written in Java. Java is used in Web applications that power eCommerece stores that connect to databases or even other websites using technologies such as REST. Many people have written desktop Java applications that make schedules or handle payroll. I have even seen Java powered cash registers.

The point is that anyone who grabs a solid understanding of Java will not struggle to find work in the foreseeable future. As of this writing, the Java platform is in its 8th version with JDK 9 on its way. Java development has a massive community of people who are happy to share programming techniques and help others improve their code. Companies such as Google contribute to Java by publishing software libraries to enhance the language.

However, to get started in Java, we need to install our build tools. The Java Development Kit (JDK) can be downloaded from Oracle’s website here. Alternatively, you can also use OpenJDK which is a community drive version of Java. Install either of these software packages will install the Java Runtime Environment (JRE), the Java compiler, and related software libraries on your system that make Java development possible.

Now let’s write our first Java application. To do this, you need to use a plain text editor (on Windows, that would be notepad. Apple users may use TextEdit). In the end, Java source files are files that end with the .java extension. Once you have your text editor open, start by typing the following code.

 
public class HelloWorld { 
    public static void main(String [] args){ 
        System.out.println("Hello World"); 
    } 
} 

Once you have this code inserted into your text editor, you should use the save as feature and save this file HelloWorld.java. This is a critical step because required the name of the file to match the name of the class (this is the name that follows the keyword class, so in our case, it’s HelloWorld). Once you have saved the file, you will need to open your system’s command prompt or terminal.

At this point, you need to compile your java file. Java is a compiled language that relies on the Java compiler to turn your *.java into an *.class file. To run the java compiler, navigate to the folder (or directory) that you saved your HelloWorld.java file in and then type.

javac HelloWorld.java

If all goes well, you will have a HelloWorld.class file in that folder next to HelloWorld.java. To run the program type:

java HelloWorld

Your system will print:

Hello World

Congratulations! You have wrote, compiled, and ran your first Java program!