Strings

2.1 Strings

Strings are a sequence of characters. In the Java programming language, string is an object rather than a primitive data type. The Java platform provides the String class to create and manipulate strings.

Creating Strings

The most direct way to create a string is to write:
 String greeting = "Hello world";
In this case, "Hello world" is a string literal—a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value—in this case, Hello world.
Every character in a string has a specific position in the string. The position of the first character is 0, the position of the second character is 1, and so on. The length of a string is the number of characters in it.
StringHello World
Character in the string
Hello World
Position of the character
in the string
012345678910

String Arithmetic

The + operator can concatenate two or more strings. In previous sections, you have seen statement that look something like this:
String name = "David";
System.out.println("Your name is " + name);
These two lines result in the display of the following text:
Your name is David
The + operator combines strings, other objects, and variables to form a single string. In the preceding example, the literal "Your Name is " is concatenated to the value of the String object name.
If any part of a concatenation operation is a String or a string literal, all elements of the operation will be treated as if they were strings:
System.out.println("Your roll number is " + 19);
This produces the output Your roll number is 19, as if the integer literals 19 is string.

No comments:

Post a Comment

Pages