Object Oriented Programming: Unit IV: I/O, Generics, String Handling

Basic String Class

Definition, Syntax of String Constructor, Method with Description, Example Java Programs

String is a collection of characters. In Java String defines the object. The string is normally used to represent the collection of characters

Basic String Class

Definition: String is a collection of characters. In Java String defines the object. The string is normally used to represent the collection of characters

Syntax of String Constructor

Example Program

Let us look at a sample program in which the string object is used in order to handle some text.

Java Program [String Demo.Java]

/*This is a Java program which makes use of strings

*/

class String Demo

{

public static void main(String args[])

{

String s "Hello, How are You?";

System.out.println(s);

}

}

Output

Hello, How are You?

String Literal

In Java String can be represented as a sequence of characters enclosed within the double quotes.

For example

String s= "Hello, How are you?"

We can initialize the string using the empty string literal. For example

String mystr=""

Similarly the escape sequence can be used to denote a particular character in the string literal. For example we can use back slash followed by double quote to print the double quote character.

“\" “

Alternatively, String can be denoted as the array of characters.For example:

char str[] = {'P', 'R', 'O', 'G', 'R', 'A', 'M'};

Now we can have a variable s which can then be initialized with the string "PROGRAM" as follows -

String s = new String(str);

Operations on String

Following are some commonly defined methods by a string class -


Object Oriented Programming: Unit IV: I/O, Generics, String Handling : Tag: : Definition, Syntax of String Constructor, Method with Description, Example Java Programs - Basic String Class