PROGRAMMING

  minte9
learningjourney




S R Q

Multilines

Java (before JDK15) does not permit strings to span lines.
 
/**
 * Span strings on multiple lines
 * 
 * Concatenation operator +
 * String.join()
 * Text Block """ (only with JDK15)
 */

package com.minte9.basics.strings;

public class Multilines {
    public static void main(String[] args) {
        
        String a = ""
            + "AAA "
            + "BBB"
        ;
        String b = String.join("\n",
            "CCC",
            "DDD"
        );

        System.out.println(a); // AAA BBB
        System.out.println(b); // CCC DDD
    }
}

Padding

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

public class Padding {
    public static void main(String[] args) {
        
        String a = "0" + String.format("%6s", "123"); // LEFT
        String b = String.format("%6s", "123").replace(" ", "0");
        String c = String.format("%-6s", "123").replace(" ", "0");

        System.out.println(a); // 000   123
        System.out.println(b); // 000123
        System.out.println(c); // 123000
    }
}

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  a = "1";
        String  b = "2.22";
        Integer c = Integer.valueOf(a); // 1
        Float   d = Float.valueOf(b);   // 2.22
        
        assertEquals(c, 1, 0);
        assertEquals(d, 2.23, 0.1);

        assertNotEquals(c, "1");
        assertNotEquals(d, 2.23, 0);
    }

    @Test public void toStringTest() {

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

Questions    
Last update: 72 days ago
Basics, Exceptions