Menu
Topics Index
...
`

CreatingStrings - Java Example Program


CreatingStrings
class CreatingStrings
{
    public static void main(String arg[])
    {
        String s = new String(); // LINE A
        System.out.println("~" + s + "~"); // Added "~" before and after to show the empty String
        String s1 = "Merit Campus "; //LINE B
        System.out.println(s1);
        String s2 = new String("Online Java learning tool, "); // LINE C
        System.out.println(s2);
        char characters[] = {'M', 'e', 'r', 'i', 't', ' ', 'C', 'a', 'm', 'p', 'u', 's'};
        String s3 = new String(characters); //LINE D
        System.out.println(s3);    
    }
}
OUTPUT

~~
Merit Campus
Online Java learning tool,
Merit Campus

DESCRIPTION

At LINE A, an empty string is created and assigned to s. Observe there is no space between '~' operators.
At LINE B, a String object is created using the String literal.
At LINE C, a String object is created using constructor and assigned to s2.
At LINE D, we are creating a String object from char array.

THINGS TO TRY
  • Place the below shown code in the program after LINE C
    byte b[] = {65, 66, 67, 68, 69};
    String s4 = new String(b);

    Print s4 and see the output. It should be ABCDE
    The ASCII values of 'A', 'B', 'C', 'D', 'E' are 65, 66, 67, 68, 69 so when we create a string from array b it prints ABCDE as output.

  • Place the below shown code in the program and see what happens
    String s5 = s1 + s2 + " improves programming skills."

    Print s5 and see the output. It should be Merit Campus online Java learning tool, improves programming skills.

© meritcampus 2019

All Rights Reserved.

Open In App