Home Java Introduction Classes Decisions Loops Access Inheritance Inner Classes Arrays Exceptions Strings Generics Container Input/Output MultiThreading jdk8 Versions Books


New String Methods

We have new methods for the "String" class such as:

isBlank() Returns true if the string is empty or contains only
white space, tabs or end of line characters.

isEmpty() Returns true if the string length is 0

lines() Returns a stream if lines that are separated by new line
characters.



File: string1.java
public class string1
{
    public static void main(String[] args)
    {
        String s1 = " ";         // Contains a space character
        String s2 = "\n\t";      // Contains newline and tab characters (whitespace)
        String s3 = "";          // Empty string
        String s4 = " Hello ";   // Contains non-whitespace characters

        System.out.println("s1 is blank: " + s1.isBlank() ); // true
        System.out.println("s2 is blank: " + s2.isBlank() ); // true
        System.out.println("s3 is blank: " + s3.isBlank() ); // true
        System.out.println("s4 is blank: " + s4.isBlank() ); // false
        System.out.println("-------------") ;

        System.out.println("s1 is isEmpty: " + s1.isEmpty() ); // false
        System.out.println("s2 is isEmpty: " + s2.isEmpty() ); // false
        System.out.println("s3 is isEmpty: " + s3.isEmpty() ); // true
        System.out.println("s4 is isEmpty: " + s4.isEmpty() ); // false

        String linesStr = "Line1\nLine2\rLine3\r\nLine4"  ;
        linesStr.lines().forEach( System.out::println );

        String repeatStr = "abc";
        System.out.println( repeatStr.repeat(3) ) ; // Output: abcabcabc
        System.out.println(  "=".repeat(20) );

        String stringWithBlanks = "  Learn ";
        System.out.println( "-" + stringWithBlanks.strip() + "-" ) ;
    }
}

var parameters in lambda expressions

We do not have to specify the exact type of the parameter in lambda expressions.

File: var1.java
import java.util.function.Function;

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

        Function<String, String> toLowerCase = (var input) -> input.toLowerCase() ;
        String result = toLowerCase.apply("Hello World") ;
        System.out.println(result) ;
        // Output: hello world
   }

}