JAVA

  minte9
REMEMBERS




Last update:   29-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
    }
}

Converting

Conveting Strings to Integers and vice versa.
T 
package com.minte9.basics.strings;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import org.junit.Test;

public class ConvertingTest {
    
    @Test public void toNumberTest() {

        String a1 = "1";
        String a2 = "1.11";
        Integer b1 = Integer.valueOf(a1);
        Float b2 = Float.valueOf(a2);
        assertEquals(2.1100, b1+b2, 4);         // pass
        assertNotEquals("2.1100", b1+b2, 4);    // pass
    }

    @Test public void toStringTest() {

        int i = 11;
        assertEquals("11", "" + i);                     // pass
        assertEquals("11", "" + String.valueOf(i));     // pass
        assertEquals("11", "" + Integer.toString(i));   // pass
    }
}

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
        );
    }
}

Questions     github Basics
Exceptions
        A B C D E F
🔔
1/2