How do I use Kotlin data types like String, Int, and Boolean?

In Kotlin, data types like String, Int, and Boolean are fundamental types that are used to work with text, numbers, and logical values respectively. Kotlin provides these types as part of its standard library, and they are straightforward to use. Below is an explanation of how to work with them:

1. String

A String in Kotlin represents a sequence of characters. You can create and manipulate strings easily.

Example:

fun main() {
    val name: String = "Kotlin"
    val greeting = "Hello, $name!" // String interpolation
    val length = name.length       // Access string property

    println(greeting)  // Output: Hello, Kotlin!
    println("Length of name: $length")  // Output: Length of name: 6

    // Multi-line string
    val multiLineString = """
        This is a
        multi-line string.
    """.trimIndent()

    println(multiLineString)
}

Key Features of Strings:

  • String interpolation ($) to include variables or expressions within a string.
  • Supports multi-line strings using triple quotes (""").
  • String manipulation methods, e.g., .length, .substring(), .toUpperCase(), etc.

2. Int

An Int is a basic data type representing a 32-bit integer in Kotlin. It is used for whole numbers.

Example:

fun main() {
    val number: Int = 42
    val doubled = number * 2
    val isEven = number % 2 == 0

    println("Number: $number")  // Output: Number: 42
    println("Doubled: $doubled")  // Output: Doubled: 84
    println("Is even? $isEven")  // Output: Is even? true
}

Key Points:

  • Int is one of the numeric data types, which also include Long, Short, Byte, Double, and Float.
  • Kotlin handles mathematical operations with Int and other numeric types directly.
  • Reading and writing numbers are simple, and type conversion can be performed using .toInt(), .toDouble(), etc.

3. Boolean

A Boolean in Kotlin represents a value that is either true or false.

Example:

fun main() {
    val isKotlinFun: Boolean = true
    val isJavaFun = false

    println("Is Kotlin fun? $isKotlinFun")  // Output: Is Kotlin fun? true
    println("Is Java fun? $isJavaFun")      // Output: Is Java fun? false

    // Logical operations
    val bothFun = isKotlinFun && isJavaFun  // AND operation
    val eitherFun = isKotlinFun || isJavaFun // OR operation

    println("Both fun? $bothFun")  // Output: Both fun? false
    println("Either fun? $eitherFun") // Output: Either fun? true
}

Key Points:

  • Booleans are used for logical operations and for controlling conditions in if statements, loops, etc.
  • Supports logical operators: && (AND), || (OR), ! (NOT).

Type Inference

In Kotlin, thanks to type inference, you don’t always need to explicitly specify the type of a variable. The compiler can infer the type based on the assigned value.

Example:

fun main() {
    val name = "Kotlin"  // Automatically inferred as String
    val age = 25         // Automatically inferred as Int
    val isActive = true  // Automatically inferred as Boolean

    println(name)
    println(age)
    println(isActive)
}

Additional Tips

  • Type Conversion: When converting between data types (e.g., String to Int), use methods like toInt(), toDouble(), etc.
    val number = "123".toInt()  // Converts String to Int
    val decimal = 3.14.toString()  // Converts Double to String
    
  • Null Safety: These types are non-null by default. If you want a variable to hold a null value, use the nullable types (e.g., String?, Int?, Boolean?).
    val nullableString: String? = null
    

With those basics, you are ready to work with String, Int, and Boolean in Kotlin!

How do I render boolean value as checkbox in JTable component?

To make a JTable renders a boolean as a checkbox in the table cell we need to tell the table that a cell stores a boolean type of data. To do this we have to implement a TableModel for the JTable component.

TableModel‘s getColumnClass(int columnIndex) must return the type of data stored in a cell. When it returns that the column stored a Boolean data, JTable displays a checkbox as the default renderer or editor for that cell.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;

public class JTableBooleanAsCheckbox extends JPanel {
    public JTableBooleanAsCheckbox() {
        initializeUI();
    }

    public static void showFrame() {
        JPanel panel = new JTableBooleanAsCheckbox();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTable Boolean as Checkbox");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(JTableBooleanAsCheckbox::showFrame);
    }

    private void initializeUI() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(500, 500));

        JTable table = new JTable(new BooleanTableModel());
        table.setFillsViewportHeight(true);
        JScrollPane pane = new JScrollPane(table);
        add(pane, BorderLayout.CENTER);
    }

    static class BooleanTableModel extends AbstractTableModel {
        String[] columns = {"STUDENT ID", "NAME", "SCORE", "PASSED"};
        Object[][] data = {
                {"S001", "ALICE", 90.00, Boolean.TRUE},
                {"S002", "BOB", 45.50, Boolean.FALSE},
                {"S003", "CAROL", 60.00, Boolean.FALSE},
                {"S004", "MALLORY", 75.80, Boolean.TRUE}
        };

        public int getRowCount() {
            return data.length;
        }

        public int getColumnCount() {
            return columns.length;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            return data[rowIndex][columnIndex];
        }

        @Override
        public String getColumnName(int column) {
            return columns[column];
        }

        // This method is used by the JTable to define the default
        // renderer or editor for each cell. For example if you have
        // a boolean data it will be rendered as a checkbox. A
        // number value is right aligned.
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return data[0][columnIndex].getClass();
        }
    }
}

Here is the result of the program:

JTable render Boolean as Checkbox

JTable render Boolean as Checkbox

How do I generate a random array of numbers?

Using java.util.Random class we can create random data such as boolean, integer, floats, double. First you’ll need to create an instance of the Random class. This class has some next***() methods that can randomly create the data.

package org.kodejava.util;

import java.util.Arrays;
import java.util.Random;

public class RandomDemo {
    public static void main(String[] args) {
        Random r = new Random();

        // generate some random boolean values
        boolean[] booleans = new boolean[10];
        for (int i = 0; i < booleans.length; i++) {
            booleans[i] = r.nextBoolean();
        }
        System.out.println(Arrays.toString(booleans));

        // generate a uniformly distributed int random numbers
        int[] integers = new int[10];
        for (int i = 0; i < integers.length; i++) {
            integers[i] = r.nextInt();
        }
        System.out.println(Arrays.toString(integers));

        // generate a uniformly distributed float random numbers
        float[] floats = new float[10];
        for (int i = 0; i < floats.length; i++) {
            floats[i] = r.nextFloat();
        }
        System.out.println(Arrays.toString(floats));

        // generate a Gaussian normally distributed random numbers
        double[] doubles = new double[10];
        for (int i = 0; i < doubles.length; i++) {
            doubles[i] = r.nextGaussian();
        }
        System.out.println(Arrays.toString(doubles));
    }
}

The result of the code snippet above are:

[true, true, false, true, false, true, true, false, false, true]
[34195704, 1462972230, -475641915, -1531017612, 332184915, 1555901473, -276309016, 1433394157, -451221924, -1178823255]
[0.3040716, 0.28814012, 0.34028566, 0.021003246, 0.49158317, 0.37954164, 0.5403056, 0.54187375, 0.7157934, 0.5964742]
[1.051268591002577, -1.1283332046139989, 0.8351395528722437, -0.24598168031182968, 0.7123515366756693, -0.9661681996105319, -1.6107009669125059, 0.43994917963255387, 1.1309345726165914, 1.2321618489324313]

For an example to create random number using the Math.random() method see How do I create random number?.

How do I convert primitive boolean type into Boolean object?

The following code snippet demonstrate how to use the Boolean.valueOf() method to convert primitive boolean value or a string into Boolean object. This method will return the corresponding Boolean object of the given primitive boolean value.

When a string value is passed to this method it will return Boolean.TRUE when the string is not null, and the value is equal, ignoring case, to the string "true". Otherwise, it will return Boolean.FALSE object.

package org.kodejava.lang;

public class BooleanValueOfExample {
    public static void main(String[] args) {
        boolean b = true;
        Boolean bool = Boolean.valueOf(b);
        System.out.println("bool = " + bool);

        // Here we test the conversion, which is likely unnecessary. But
        // here is shown the boolean true is equals to Boolean.TRUE static
        // variable and of course you can guest the boolean false value is
        // equals to Boolean.FALSE
        if (bool.equals(Boolean.TRUE)) {
            System.out.println("bool = " + bool);
        }

        // On the line below we convert a string to Boolean, it returns
        // true if and only if the string is equals to "true" otherwise it
        // returns false
        String s = "false";
        Boolean bools = Boolean.valueOf(s);
        System.out.println("bools = " + bools);

        String f = "abc";
        Boolean abc = Boolean.valueOf(f);
        System.out.println("abc = " + abc);
    }
}

The code snippet will print the following output:

bool = true
bool = true
boolS = false
abc = false

Can I create a boolean variable from string?

To convert a string into boolean we can use the Boolean.parseBoolean(String) method. If we pass a non null value that equals to true, ignoring case, this method will return true value. Given other values it will return a false boolean value.

package org.kodejava.lang;

public class BooleanParseExample {
    public static void main(String[] args) {
        // Parsing string "true" will result boolean true
        boolean boolA = Boolean.parseBoolean("true");
        System.out.println("boolA = " + boolA);

        // Parsing string "TRUE" also result boolean true, as the
        // parsing method is case insensitive
        boolean boolB = Boolean.parseBoolean("TRUE");
        System.out.println("boolB = " + boolB);

        // The operation below will return false, as Yes is not
        // a valid string value for boolean expression
        boolean boolC = Boolean.parseBoolean("Yes");
        System.out.println("boolC = " + boolC);

        // Parsing a number is also not a valid expression so the
        // parsing method return false
        boolean boolD = Boolean.parseBoolean("1");
        System.out.println("boolD = " + boolD);
    }
}

The code snippet above will print the following output:

boolA = true
boolB = true
boolC = false
boolD = false