x

Java – String examples

PREV     NEXT

What is a string?

In C, C++, a string represents an array of characters (last character ends with ‘\0’).


In Java, a string represents the object of String class. We also have character array in java.

Is String a class or a datatype?

String is a class defined in java.lang package. In Java, every class is considered as user defined data type. So we can take string as a data type.

Ways to create a String:

Method 1:

By declaring a string variable and assigning a group of characters to the string variable.

Syntax:  

  String <variable_name>;

<variable_name> = value;

Example:   

  String name;

name = “Hari”;

Declaration and assignment can be made in a single statement. This is just a simplification of the above.

Syntax:    

String <variable_name> = value;

  Example:     

String name = “Hari”;

Method 2:

Using the new operator, create a String object by passing the string value as an argument to the String constructor.

Syntax:

String <object> = new String(<value>);

 Example:

 String name = new String(“Hari”);

Method 3:

Converting the character array into strings.

Syntax:

String <object> = new String(<Char_Array>);

Example:     

char n[] = {‘H’,’a’,’r’,’i’};

String name = new String(n);

Note: A string can also be empty with no characters inside it.

 Example:

 String s=””

Concatenating strings:

The concat() method is used for concatenating two strings.

Example:

String s1 = “freduu”;

String s2 = “ java tutorial”;

String s = s1.concat(s2);

System.out.println(s); //Output: freduu java tutorial

Strings can also be concatenated with the help of ‘+’ operator.

Example:   

String s1 = “freduu”;

String s2 = “ java tutorial”;

String s = s1+s2;

System.out.println(s); //Output: freduu java tutorial

Note: Concatenating a variable of int type with an empty string would convert the integer into String.

Example:    

int i = 2;

String s =””+i; // converts i to string

  •   However this method is considered to be a bad practice.
  • String.valueOf(int) or char.toString() is preferred for conversion.

Comparing strings:

The equals() method of the String class is used to compare the value of two strings. If the content of two strings is same, then the equals() method, returns true. Otherwise as false.

Example:

String s1 = “Today we are feeling blue”;

String s2 = “Today we are feeling blue”;

Boolean equality = s1.equals(s2); // equality would contain true

Equals method is case sensitive. Suppose if we do not want to consider the case of the strings while comparing, then we could use equalsIgnorecase() method.

Example:

String str1 = “Java”;

String str2 = “java”;

Boolean comp = str1.equalsIgnoreCase(str2);  // comp would contain true

There is another method for comparing strings which is compareTo() method. This method compares the strings lexicographically, which checks the unicode value corresponding to every character.

If str1 <str2 , returns -ve number

If str1>str2, returns +ve number

If both strings are equal, 0 is returned.

The numbers returned are the difference of the character values (unicode value) at which both the strings differ. The compareTo() method is used in sorting problems, where we need to sort a set of strings in an alphabetical order like the name of employee in an employer list.

Example:

String s1 = ”java”;

String s2 = “java”;

String s3 = “jazz”;

String s4 = “jassy;

System.out.println(s1.compareTo(s2));

System.out.println(s1.compareTo(s3)); // s1 precedes s3 since z comes after v

System.out.println(s1.compareTo(s4)); // s1 follows after s4 since s comes before v

Output:

0

-4

3

Extracting substrings:

The substring() method can be used to extract sequence of characters (substring) from a given string. There are variations in using the substring method.

Syntax :

 String substring(int p1, int p2)

This method extracts the characters starting from the position p1 to p2-1.

Example:        


String s1 = “Airport”

String s = s1.substring(3,7);  // s would contain “port”

Syntax:

String substring(int p)

This method extracts the characters starting from the position p till the end of the string.

Example:

String s1 = “Airport”

String s = s1.substring(3);  // s would contain “port”

 Finding Length of the String:

The length() method returns the number of characters in the String.

Example:        

String s =”Air”

int length = s.length(); // length would have 3,

Methods of String class:

Method Signature Description
char charAt(int i) Returns the character at the position i.
int length() Returns the number of characters or the length of the string.
int compareTo(String s) Compares the strings lexicographically.

Returns 0 if the strings compared are equal.

Returns positive number if the string object is greater than the string argument passed.

Returns negative number if the string object is less than the string argument passed.

int compareToIgnoreCase(String s) Same as compareTo() except that it does not considers the case of the strings. i.e. case insensitive.
int indexOf(String target) Returns the first occurrence (position) of the target string (from left to right) in the main string which is calling.

If target string is not found, then it returns a negative value.

int lastIndexOf(String target) Returns the last occurrence (position) of the target string in the main string.

If target string is not found, then it returns a negative value.

boolean equals(String s) Returns true, if the two strings contains the same value otherwise false.
boolean equalsIgnoreCase(String s) Same as equals() except that it does not considers the case of the strings. i.e. case insensitive.
boolean startswith(String s) Returns true, if the main string starts with the given sub string specified in the argument. Otherwise returns false. Case sensitive.
boolean endswith(String s) Returns true, if the main string ends with the given sub string specified in the argument. Otherwise returns false. Case sensitive.
boolean isEmpty() Returns true, if the string being checked is an empty string. Otherwise returns false.
boolean contains(char_sequence) Returns true, if the main string contains the given character sequence specified in the argument. Otherwise returns false.
String replace(char newchar, char oldchar)

String replace(substring new, substring old)

Returns the string in which the occurrence of oldchar is replaced with newchar.

Returns the string in which the occurrence of the sequence of a character (sub-string) are replaced with the new set of characters.

String replaceAll(String regex, String newstring) Returns the string in which regular expression (format/pattern of a string) is replaced with the newstring.
String substring(int p)

 

String substring(int p1, int p2)

Returns the substring starting from the position p of main string till the end.

Returns the substring starting from the position p1 till the position p2-1.

String concat(String s) Returns the concatenated string of the argument string and the string object.
String toLowerCase() Returns the same string with lowercase letters.
String toUpperCase() Returns the same string with uppercase letters.
String trim() Returns the main string with the white space(s) at the beginning and the trailing(end) as trimmed.

Doesn’t trim the whitespace in the middle of the string.

String[] split(delimiter) Returns the set of strings separated by the delimiter.

I.e. splits the main string into substrings with respect to the delimiter like white space, comma, tab etc.

String valueOf(dataType anyvalue) Converts the given data in the argument to a string value.
void getChars(int p1, int p2, char arr[], int p3) Gets the characters from the position p1 to p2 in the main string and copies it in the char array, starting from the position p3 onwards.

Copies set of characters from a string to a char array.

Note: String methods can be chained.

Example:

String s = “Hi this is  Sai  “

String name = s.substring(11).trim().toLowerCase();

System.out.print(name);  // name would contain sai

String class is Immutable:

Immutable is the nature which defines the inability to change. By default the value of String are considered as constant. Unlike some functions which are mutable whose value can change, the class String is immutable (cannot be modified).

Consider the following strings.

String f1 = “foot”;

String f2 = “ball”;

f1=f1+f2;

System.out.print(f1); // would produce the concatenated value football.

 String

In this the actual string(foot) is not modified but the reference f1 of the old string points to the new string which is generated by the string concatenation operation.

PREV     NEXT



Like it? Please Spread the word!