String in Java
String in Java
A string in literal terms is a series of characters. Hey, did you say characters, isn‟t it a
primitive data type in Java. Yes, so in technical terms, the basic Java String is basically an
array of characters.
One of the primary functions of modern computer science, is processing human language.
Similarly to how numbers are important to math, language symbols are important to meaning
and decision making. Although it may not be visible to computer users, computers process
language in the background as precisely and accurately as a calculator. Help dialogs provide
instructions. Menus provide choices. And data displays show statuses, errors, and real-time
changes to the language.
As a Java programmer, one of your main tools for storing and processing language is going to
be the String class.
Now, let‟s get to some syntax, after all, we need to write this in Java code isn‟t it.
= new (argument);
Now we always cannot write our strings as arrays; hence we can define the String in Java as
follows:
//Representation of String
String strSample_2 = "ROSE";
=;
Check the below code snippet,and it explains the two methods to perform string
concatenation.
First is using “concat” method of String class and second is using arithmetic “+” operator.
Both results in the same output
Let‟s ask the Java String class a few questions and see if it can answer them ;)
output:
Length of String: 8
You answered yourself, buddy, there is an “indexOf” method that will help you determine the
location of a specific character that you specify.
Output:
Character at position 5: t
Index of character 'S': 4
String "charAt" Method
Similar to the above question, given the index, how do I know the character at that location?
Simple one again!! Use the “charAt” method and provide the index whose character you need
to find.
Output:
Character at position 5: t
String "CompareTo" Method
Do I want to check if the String that was generated by some method is equal to something
that I want to verify with? How do I compare two Strings?
Use the method “compareTo” and specify the String that you would like to compare.
Use “compareToIgnoreCase” in case you don‟t want the result to be case sensitive.
The result will have the value 0 if the argument string is equal to this string; a value less than
0 if this string is lexicographically less than the string argument; and a value greater than 0 if
this string is lexicographically greater than the string argument.
Output:
I partially know what the string should have contained, how do I confirm if the String
contains a sequence of characters I specify?
Use the method “contains” and specify the characters you need to check.
Returns true if and only if this string contains the specified sequence of char values.
Output:
How do I confirm if a String ends with a particular suffix? Again you answered it. Use the
“endsWith” method and specify the suffix in the arguments.
Returns true if the character sequence represented by the argument is a suffix of the character
sequence represented by this object.
Output:
I want to modify my String at several places and replace several parts of the String?
Java String Replace, replaceAll and replaceFirst methods. You can specify the part of the
String you want to replace and the replacement String in the arguments.
Output:
Just use the “toLowercase()” or “ToUpperCase()” methods against the Strings that need to be
converted.
Output:
String is a Final class; i.e once created the value cannot be altered. Thus String
objects are called immutable.
The Java Virtual Machine(JVM) creates a memory location especially for Strings
called String Constant Pool. That‟s why String can be initialized without „new‟
keyword.
String class falls under java.lang.String hierarchy. But there is no need to import
this class. Java platform provides them automatically.
String reference can be overridden but that does not delete the content; i.e., if
String h1 = "hello";
h1 = "hello"+"world";
then "hello" String does not get deleted. It just loses its handle.
Multiple references can be used for same String but it will occur in the same place;
i.e., if
String h1 = "hello";
String h2 = "hello";
String h3 = "hello";
then only one pool for String “hello” is created in the memory with 3 references-h1,h2,h3
System.out.println(S1);
System.out.println(S1);
Parameters:
NA
Return Value:
In this program, we have two Strings and we find out the length of them using length()
method.
Output:
A common scenario can be when a system admin wants to find the index of the '@' character
of the email Id of a client and then wants to get the remaining substring. In that situation,
IndexOf method can be used.
Syntax
publicintindexOf(int cha)
Parameters
cha − a character.
Return Value
This Java method returns the index within this string of the first occurrence of the specified
character. It returns -1 if the character does not occur.
The Java String IndexOf method has four overloads. All the overloads return an integer type
value, representing the returned index. These overloads differ in the type and number of
parameters they accept.
IndexOf(char b)
This method returns the index of the character 'b' passed as parameter. If that character is not
available in the string, the returned index would be -1.
IndexOf(char c, intstartindex)
The given method would return the index of the first occurrence of character 'c' after the
integer index passed as second parameter "startindex." All the occurrences of character 'c'
before the "startindex" integer index would be ignored.
IndexOf(String substring)
The above method returns the index of the first character of the substring passed as a
parameter to it. If that substring is not available in the string, the returned index would be -1.
IndexOf(String substring, intstartindex)
This Java method returns the index of the first character in the substring passed as the first
parameter, after the "startindex" index value. If substring starts from the passed integer value
of "startindex", that substring would be ignored.
Example
Output:
The charat method returns the character at the definite index. In this method index value
should be between 0 and string length minus 1
Method Syntax:
Parameter input:
index – This Java method accepts only single input which is an int data type.
Method Returns:
This method returns a character type data based on the index input
Exception:
Example 1:
Output:
Syntax :
publicintcompareTo(String str)
Parameter input :
str – This method only accepts only one input String data type.
Method Returns:
This Java method returns an intdatatype which is based on the lexicographical comparison
between two strings.
returns < 0 then the String calling the method is lexicographically first
returns == 0 then the two strings are lexicographically equivalent
returns> 0 then the parameter passed to the compareTo method is lexicographically
first.
Example 1:
Output
Compare To 'a' b is : -1
Compare To 'b' a is : 1
Compare To 'b' b is : 0
Here,
You can use method Use "compareToIgnoreCase" in case you don't want the result to be case
sensitive.
Example 2:
Output
In this method, if the first string is always lexicographically higher than second string, it
returns a positive number.
if a1 == a2, it returns 0
Example 3:
Output:
String 1: Guru1
String 2: Guru2
"Guru1" is lexicographically higher than "Guru2"
publicbooleanString.contains(CharSequence s)
Parameters
Return Value
This method returns true only if this string contains "s" else false.
Exception
Example 1:
Output:
It is a common case in programming when you want to check if specific String contains a
particular substring. For example, If you want to test if the String "The big red fox" contains
the substring "red." This method is useful in such situation.
if (str1.contains("example")) {
System.out.println("The Keyword :example: is found in given string");
} else {
System.out.println("The Keyword :example: is not found in the string");
}
}
}
Output:
Syntax
Public endsWith(suffix)
Parameters
Return Value
False: Character sequence supplied in "suffix" DOES NOT matches the end sequence
of the calling string
True: Character sequence supplied in "suffix" matches the end sequence of the
calling string
Exception
None
Example:
Output:
The java.lang.String.endsWith() returns true if this string ends with the specified suffix.
1. replace
2. replaceAll
3. replaceFirst.
With the help of these you can replace characters in your string. Lets study each in details:
Description:
This Java method returns a new string resulting from replacing every occurrence of
characters with a new characters
Syntax:
Parameters:
Return Value
Example 1
}
}
Output:
Description
The java string replaceAll() method returns a string replacing all the sequence of characters
matching regular expression and replacement string.
Signature:
Parameters:
Output:
Guru99isasiteprovidingfreetutorials
Description
The method replaces the first substring of the given string which matches that regular
expression.
Syntax
Parameters
Return Value
Example 3:
1. tolowercase() method
This Java string method converts every character of the particular string into the lower case
by using the rules of the default locale.
Note: This method is locale sensitive. Therefore it can show unexpected results if used for
strings which are intended to be interpreted separately.
Syntax
Parameters
NA
Return Value
Example 1:
}
}
Output:
2. toUppercase () method
The toUppercase() method is used to convert all the characters in a given string to upper case.
Syntax:
toUpperCase()
Parameters:
NA
Returns value:
Example 2:
Output:
Let‟s say you have a string – strTest - that contains a numeric value.
String strTest = “100”;
Try to perform some arithmetic operation like divide by 4 – This immediately shows you a
compilation error.
classStrConvert{
public static void main(String []args){
String strTest = "100";
System.out.println("Using String:" + (strTest/4));
}
}
Output:
int<IntVariableName> = Integer.parseInt(<StringVariableName>);
This will convert the Java String to java Integer and store it into the specified integer
variable.
classStrConvert{
public static void main(String []args){
String strTest = "100";
intiTest = Integer.parseInt(strTest);
System.out.println("Actual String:"+ strTest);
System.out.println("Converted to Int:" + iTest);
//This will now show some arithmetic operation
System.out.println("Arithmetic Operation on Int: " + (iTest/4));
}
}
Output:
Actual String:100
Converted to Int:100
Arithmetic Operation on Int: 25
Following is the code example shows the process of using Integer.valueOf() method:
Output:
Actual String:100
Converted to Int:100
Arithmetic Operation on Int:25
NumberFormatException
NumberFormatException is thrown If you try to parse an invalid number string. For example,
String „Guru99‟ cannot be converted into Integer.
Example: