Topics Index

Strings >
Siva Nookala - 14 Apr 2016
Strings, which are widely used in Java programming, are nothing but a sequence of characters.

In this topic we will discuss, what is a String and how to assign a value to String.
Creating Strings :
String s = "Hello World";
Strings can be created as shown above, here String is the data type and s is the reference which refers to the data "Hello World". There is also another way of creating Strings. The syntax is as shown below.
Syntax :
String s = new String("Hello World");

When we declare a string variable and assign some value, it means that we are creating a string object which cannot be changed. Whenever we modify the String a new String object is created with the modifications, and the original string is left as it is. Anyway Java provides String Buffer, StringBuilder Class In Java classes where strings(character sequences) can be modified even after they are created.
We can also create a String object from char as well as byte arrays as shown below.
char c[] = {'j', 'a', 'v', 'a'};
String s = new String(c);

For byte array:
byte b[] = {65, 66, 67, 68};
String s = new String(b);
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
        String s2 = new String("Online Java learning tool, "); // LINE C
        char characters[] = {'M', 'e', 'r', 'i', 't', ' ', 'C', 'a', 'm', 'p', 'u', 's'};
        String s3 = new String(characters); //LINE D

Merit Campus
Online Java learning tool,
Merit Campus


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.

  • 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.

Dependent Topics : Java StringBuffer  StringBuilder Class In Java 

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App