Java – String Handling

Java – String Handling 2017-08-09T13:00:17+00:00

Java String Handling :

In Java, a string is defined as a sequence of characters.

But, unlike many other languages that implement strings as character arrays, java implements strings as objects of type String.

Java handles String by two classes StringBuffer and String. The String and StringBuffer classes are defined in java.lang.

Thus, they are available to all programs automatically.

1. String Concatenation (+)

EX :


Output :
S1 = Java
S2 = 2all
Concatenation Operator = Java2all
S3 = Java2all
2. Character Extraction :
The String class provides ways in which characters can be extracted from a String object.
3. String Comparison :

The String class provides several methods that compare strings or substrings within strings.

equals( ) – used to compare two strings

General form:

Boolean equals(Object str)

Here, str is a String object.

It returns true if the strings contain the same character otherwise it returns false.

The comparison is case-sensitive.

equalsIgnoreCase( ) – Same as equals but this ignores case.

General form:

Boolean equalsIgnoreCase(String str)

Here, str is the String object.

It returns true if the strings contain the same character otherwise it returns false.

This is case in – sensitive.

regionMatches( )

This method compares a specific region inside a string with another specific region in another string.

There is an overloaded form that allows you to ignore case in such comparisons.

General form:

Boolean regionMatches(int startIndex, String str2, int str2StartIndes, int numChars)

Boolean regionMatches(Boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars)

startsWith( ) and endsWith()

The startsWith( )  method determines whether a given String begins with a specified string.

endsWith( ) determines whether the String ends with a specified string.

General Form

Boolean startsWith(String str)

Boolean endsWith(String str)

equals( ) Versus = =

Equals( ) method and the = = operator perform two different operations. The equals ( ) method compares the characters inside a String object. The = = operator compares two object references to see whether they refer to the same instance.

compareTo( )

It is not enough to know that two strings just for equal or not. For sorting applications, we need to know which is less than, equal to, or greater than the other string.

The String method compareTo( ) serves this purpose.

General Form:

int compareTo(String str)

4 Modifying a string :

If we want to modify a String, we must either copy it into a StringBufer or we can use following String methods:

5 valueOf() :

The valueOf() method converts data from internal format into a human-readable form. It has several forms:

String valueOf(double num)

String valueOf(long num)

String valueOf(Object ob)

String valueOf(char chars[ ] )

String valueOf(char chars[], int startIndex, int numChars)

Prev Next