Page 296 - ComputerScience_Class_11
P. 296
10.2 STRING CLASS
As explained earlier, a string is a combination of a set of characters written within double quotes. To assign a sentence
or a word to a String variable, the following syntax is used.
String (variable)= "String Literal";
For example:
String str1="Computer Science";
String str2="Kolkata – 700115";
10.2.1 Important String Methods
There are several useful String methods that come in handy while writing programs. Let us learn about them one by
one.
The length() Function
This function returns the number of characters present in a string. It returns an integer type of value. The length() is
the only function where the counting starts from 1. The syntax is:
int <variable> = String_datatype_Variable.length();
Let us see the below example:
Program 2 Write a program to count the number of charecters in a string.
1 import java.util.*;
2 class string_count
3 {
4 public static void main(String[] args)
5 {
6 String sub= "I am studying Computer Science ";
7 int len= sub.length();
8 System.out.println(sub + "contains " + len + " characters");
9 }
10 }
The output of the preceding program is as follows:
BlueJ: Terminal Window - Java
Options
I am studying Computer Science contains 31 characters
The charAt(int index) Function
For a string variable, this function returns the character at the given index. It returns character type data. The
syntax is:
char <variable> = String_datatype_Variable.charAt(int index);
294 Touchpad Computer Science (Ver. 3.0)-XI

