How do I use String.indent() to format output text?

The String.indent(int n) method in Java is a useful tool for formatting multi-line strings by adjusting the amount of leading space (indentation) on each line. Introduced in Java 12, it performs the following for the specified n indentation:

  1. Positive n: Adds n spaces to the beginning of each line in the string.
  2. Negative n: Removes up to n leading spaces from each line.
  3. Zero n: Leaves the string unchanged (but trims blank lines at the start/end).

This is particularly useful for formatting text in structured views, like logs, JSON, XML, or pretty-printed output.

Example: Using String.indent to Format Output

Here is how you can use the String.indent() method:

package org.kodejava.lang;

public class StringIndentExample {
    public static void main(String[] args) {
        // Original multi-line string (no indentation)
        String text = "Line 1\nLine 2\nLine 3";

        // Adding an indent of 4 spaces
        String indented = text.indent(4);
        System.out.println("Indented by 4 spaces:\n" + indented);

        // Removing 2 leading spaces (negative indent)
        String negativeIndent = indented.indent(-2);
        System.out.println("Indented with -2 (removing spaces):\n" + negativeIndent);

        // Applying indent to empty lines
        String withEmptyLines = "Line 1\n\nLine 3";
        String indentedWithEmptyLines = withEmptyLines.indent(4);
        System.out.println("Handling empty lines:\n" + indentedWithEmptyLines);
    }
}

Explanation of Code:

  1. Adding Indentation: The first call to .indent(4) adds 4 spaces to each line.
  2. Removing Indentation: .indent(-2) deducts 2 spaces from the start of each line (if spaces exist).
  3. Empty Lines: When dealing with blank lines, indent maintains the level of indentation for such lines, adding or removing spaces as needed.

Output:

Indented by 4 spaces:
    Line 1
    Line 2
    Line 3

Indented with -2 (removing spaces):
  Line 1
  Line 2
  Line 3

Handling empty lines:
    Line 1

    Line 3

Notes:

  • Empty lines and their indentation are preserved.
  • Lines with no leading spaces are unaffected by negative indentation.
  • Leading and trailing full blank lines are removed.

When to Use:

  • To format multiline strings cleanly.
  • To produce human-readable or formatted output in tools or commands (e.g., logging, text processing).

How do I use String.strip(), isBlank() and lines() methods?

The String class in Java provides the methods strip(), isBlank(), and lines(), which were introduced in Java 11. These methods are useful for managing whitespaces, checking for blank strings, and processing multi-line strings.

1. strip()

The strip() method removes leading and trailing whitespaces from a string. Unlike trim(), it uses Unicode-aware whitespace handling, making it more robust for international characters.

Example:

public class StringStripExample {
    public static void main(String[] args) {
        String str = " \u2009Hello World  "; // Unicode whitespace
        System.out.println(str.strip());      // Outputs: "Hello World"
        System.out.println(str.stripLeading()); // Removes leading spaces: "Hello World  "
        System.out.println(str.stripTrailing()); // Removes trailing spaces: " \u2009Hello World"
    }
}

Key Point:

  • strip() differs from trim() in that it removes all Unicode whitespace, not just ASCII spaces.

2. isBlank()

The isBlank() method checks whether a string is empty or contains only whitespaces. This includes Unicode whitespace and helps to quickly validate string content.

Example:

public class StringIsBlankExample {
    public static void main(String[] args) {
        String empty = "   "; // Contains whitespaces
        System.out.println(empty.isBlank()); // Outputs: true

        String nonBlank = "Hello";
        System.out.println(nonBlank.isBlank()); // Outputs: false

        String unicodeSpace = "\u2009"; // Unicode whitespace
        System.out.println(unicodeSpace.isBlank()); // Outputs: true
    }
}

Key Point:

  • isBlank() is stronger than isEmpty() because it treats strings with only whitespace as blank, whereas isEmpty() considers only an empty string ("").

3. lines()

The lines() method breaks a multi-line string into a stream of lines, using the platform’s line terminator (e.g., \n or \r\n) to split the string.

Example:

public class StringLinesExample {
    public static void main(String[] args) {
        String multiLineString = "Hello\nWorld\nJava 11";

        // Use 'lines()' to split the multi-line string
        multiLineString.lines().forEach(System.out::println);

        // Output:
        // Hello
        // World
        // Java 11
    }
}

Key Points:

  • lines() splits the string into lines and returns a Stream<String>.
  • It can be combined with stream operations like filter(), map(), and forEach().

Combining Methods for Common Use Cases

Here’s how you can combine them:

Trim and Check Blank:

public class StringExample {
    public static void main(String[] args) {
        String input = "   ";
        if (input.strip().isBlank()) {
            System.out.println("Input is blank or empty!");
        } else {
            System.out.println("Input: " + input.strip());
        }
    }
}

Processing Multi-Line Strings:

public class MultiLineExample {
    public static void main(String[] args) {
        String text = "  Line 1  \n  Line 2  \n  Line 3  ";

        text.lines()
            .map(String::strip) // Clean up each line
            .forEach(System.out::println);

        // Output:
        // Line 1
        // Line 2
        // Line 3
    }
}

Summary of Functionalities:

  • strip(): Removes leading/trailing Unicode whitespace.
  • isBlank(): Checks if a string is empty or only whitespace.
  • lines(): Processes multi-line strings by splitting them into lines.

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!

What is the purpose of String.strip() method of Java 11?

The purpose of the String.strip() method in Java 11 is to remove whitespaces from both the beginning and end of a string. This is very similar to the String.trim() method available in earlier versions of Java, but there is a key difference between them.

Here’s the difference:

  • String.strip(): Introduced in Java 11, strip() uses the unicode definition of whitespace. It removes not only space characters but also all other types of unicode-defined spaces, such as the thin space \u2009, etc.
  • String.trim(): Available from Java 1.0, trim() is more limited. It considers a whitespace to be any character whose ASCII value is less than or equal to 32 (a space, tab, newline, and a few other control characters).

Here are examples of how they work:

package org.kodejava.lang;

public class StringStripExample {
    public static void main(String[] args) {
        // String.strip()
        String first = " \u2009Hello  ";
        System.out.println(first.strip()); // Outputs "Hello"

        // String.trim()
        String second = " \u2009Hello  ";
        System.out.println(second.trim()); // Outputs "\u2009Hello"
    }
}

Output:

Hello
 Hello

Thus, strip() method is more comprehensive in removing different types of whitespace defined in Unicode, while trim() only removes ASCII control characters and spaces.

There are also String.stripLeading() and String.stripTrailing() methods that were introduced in Java 11, and they are similar to the strip() method, but they only remove the whitespace characters from either the beginning or the end of the string, respectively.

Here is what they do:

  • String.stripLeading(): This method removes any leading whitespace from the string. “Leading” in this context means any whitespace characters at the beginning of the string.
  • String.stripTrailing(): This method removes any trailing whitespace from the string. “Trailing” in this context means any whitespace characters at the end of the string.

Both stripLeading() and stripTrailing() use the Unicode definition of whitespace, the same as strip() method.

Here are examples of how they work:

package org.kodejava.lang;

public class StringStripLeadingTrailingExample {
    public static void main(String[] args) {
        // Strip leading whitespace
        String first = " \u2009Hello World  ";
        System.out.println(first.stripLeading());  // Outputs "Hello World  "

        // Strip trailing whitespace
        String second = " \u2009Hello World  ";
        System.out.println(second.stripTrailing()); // Outputs " \u2009Hello World"
    }
}

Output:

Hello World  
  Hello World

As demonstrated, stripLeading() removed the whitespace characters from the front of the string, and stripTrailing() removed the whitespace characters from the end of the string.

While \u00A0 is technically a type of whitespace (specifically, a non-breaking space or NBSP), it isn’t considered as such by the strip(), stripLeading(), and stripTrailing() methods, which follow the Character.isWhitespace(char) method’s definition of what constitutes a whitespace character.

According to the Java documentation, the Character.isWhitespace(char) method, which the strip() methods use, considers the following characters as whitespace:

  • ‘\t’ U+0009 HORIZONTAL TABULATION
  • ‘\n’ U+000A LINE FEED
  • ‘\u000B’ U+000B VERTICAL TABULATION
  • ‘\f’ U+000C FORM FEED
  • ‘\r’ U+000D CARRIAGE RETURN
  • ‘\u001C’ U+001C FILE SEPARATOR
  • ‘\u001D’ U+001D GROUP SEPARATOR
  • ‘\u001E’ U+001E RECORD SEPARATOR
  • ‘\u001F’ U+001F UNIT SEPARATOR
  • SPACE_SEPARATOR category types

The \u2009 (thin space) and \u0020 (space) are part of SPACE_SEPARATOR category according to Unicode standard and will be correctly stripped.

The \u00A0 (non-breaking space) is actually part of a different category called the NO-BREAK_SPACE and is not considered whitespace by Character.isWhitespace(char), so it won’t be stripped.

How do I use String.join() method in Java?

The String.join() method in Java is a static method added in Java 8 to the java.lang.String class. The String.join() is a static utility method used to concatenate multiple strings, arrays or collections (like lists and sets) of strings. This method makes it easier to join multiple strings with a specific delimiter. A delimiter is a sequence of characters used to separate strings.

This method returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter. This method saves us from writing boilerplate loop code just for concatenating strings with a delimiter.

Here is an example of how you can use it:

package org.kodejava.lang;

import java.util.Arrays;
import java.util.List;

public class StringJoinList {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("Java", "is", "cool");
        String result = String.join(" ", list);
        System.out.println(result);
    }
}

Output:

Java is cool

In this example, String.join() takes two parameters:

  1. A delimiter that is a CharSequence (like a String) that is placed between each joined String.
  2. An Iterable object like a List or a Set, over which the method iterates and joins all elements into a single String.

You can also use String.join() with an array of elements:

package org.kodejava.lang;

public class StringJoinArray {
    public static void main(String[] args) {
        String[] array = new String[]{"Java", "is", "cool"};
        String result = String.join(" ", array);
        System.out.println(result);
    }
}

Output:

Java is cool

In this case, String.join() still takes a delimiter as the first argument, but the second argument is an Array of elements to be joined.