PROGRAMMING

m9/ JAVA
REMEMBERS




Last update:   19-10-2021

Multilines

Java (before JDK15) does not permit strings to span lines .
 
/**
 * To span strings on multiple lines, use:
 * 
 * a) concatenation operator +
 * b) String.join()
 * c) Text Block """ (starting with JDK15)
 */

package com.minte9.basics.strings;

public class Multilines {
    public static void main(String[] args) {
        
        //concatation
        String msg = ""
            + "AAA "
            + "BBB"
        ;
        System.out.println(msg);
            // AAA BBB


        // join
        String msg2 = String.join("\n",
            "CCC",
            "DDD"
        );
        System.out.println(msg2);
            // CCC 
            // DDD
    }
}

... 19 lines
 

Converting

Conveting Strings to Integers and vice versa.
 
/**
 * To convert String to int use valueOf()
 * To convert int to String use toString()
 */

package com.minte9.basics.strings;

public class Converting {
    public static void main(String[] args) {
        
        String a1 = "1";
        String a2 = "1.11";
        Integer b1 = Integer.valueOf(a1);
        Float b2 = Float.valueOf(a2);

        System.out.println(b1 + b2); // 2.1100001

        int i = 11;
        String a = "" + i;
        String b = String.valueOf(i);
        String c = Integer.toString(i);

        System.out.println(a); // 11
        System.out.println(b); // 11
        System.out.println(c); // 11
    }
}

... 14 lines
 

Padding

Use String.format() to pad strings.
 
/**
 * To pad a string use String.format()
 * 
 * "%ns" to pad LEFT
 * "%-ns" to pad RIGHT
 */
package com.minte9.basics.strings;

public class Padding {
    public static void main(String[] args) {
        
        // a...123
        System.out.println(
            "a" + String.format("%6s", "123") // LEFT
        );
            
        // 123...z
        System.out.println(
            String.format("%-6s", "123") + "z" // RIGHT
        ); 

        // 000123
        System.out.println(
            String.format("%6s", "123").replace(" ", "0") // LEFT
        ); 

        // 123000
        System.out.println(
            String.format("%-6s", "123").replace(" ", "0") // RIGHT
        );
    }
}

... 20 lines
 

Questions     github Basics
Exceptions

        A B C D E F
🔔
1/2