Java Strings
String is sequence of characters which are make a words. Java programing are provide String class to deal text values. That are defined in the java.lang package. We can declare string object (variable) by using String class.
String name;
String address;
We can assign string text to variable in two ways. By using literals and using new operator.
String name="Java"; //using literals
String address=new String("Everywhere");//using new
Both given statement are create object of strings and set string literals values. String literals will be defined inside " " double quotes. String object is immutable, so we cannot modified exist specified text contain to string. But there are possible to assign new literals to an String object. For example.
public class MyString {
public static void main(String[] args) {
String textData="Old Code";
System.out.println(textData);
//Assign a new literals to string object
textData="New Code";
System.out.println(textData);
}
}
Output
Old Code
New Code
String is collection of character element. Java String class is provide charAt(int) function to get specific character of particular index.
public class MyString {
public static void main(String[] args) {
String textData="ABCD";
System.out.println(textData.charAt(0));
System.out.println(textData.charAt(1));
System.out.println(textData.charAt(2));
}
}
Output
A
B
C
String class methods
Method | Syntax |
---|---|
equals | public boolean java.lang.String.equals(java.lang.Object) |
toString | public java.lang.String java.lang.String.toString() |
hashCode | public int java.lang.String.hashCode() |
compareTo | public int java.lang.String.compareTo(java.lang.Object) |
compareTo | public int java.lang.String.compareTo(java.lang.String) |
indexOf | public int java.lang.String.indexOf(java.lang.String,int) |
indexOf | public int java.lang.String.indexOf(int) |
indexOf | public int java.lang.String.indexOf(java.lang.String) |
indexOf | public int java.lang.String.indexOf(int,int) |
valueOf | public static java.lang.String java.lang.String.valueOf(char) |
valueOf | public static java.lang.String java.lang.String.valueOf(java.lang.Object) |
valueOf | public static java.lang.String java.lang.String.valueOf(boolean) |
valueOf | public static java.lang.String java.lang.String.valueOf(char[],int,int) |
valueOf | public static java.lang.String java.lang.String.valueOf(char[]) |
valueOf | public static java.lang.String java.lang.String.valueOf(double) |
valueOf | public static java.lang.String java.lang.String.valueOf(float) |
valueOf | public static java.lang.String java.lang.String.valueOf(long) |
valueOf | public static java.lang.String java.lang.String.valueOf(int) |
length | public int java.lang.String.length() |
isEmpty | public boolean java.lang.String.isEmpty() |
charAt | public char java.lang.String.charAt(int) |
codePointAt | public int java.lang.String.codePointAt(int) |
codePointBefore | public int java.lang.String.codePointBefore(int) |
codePointCount | public int java.lang.String.codePointCount(int,int) |
offsetByCodePoints | public int java.lang.String.offsetByCodePoints(int,int) |
getChars | public void java.lang.String.getChars(int,int,char[],int) |
getBytes | public byte[] java.lang.String.getBytes() |
getBytes | public byte[] java.lang.String.getBytes(java.lang.String) throws java.io.UnsupportedEncodingException |
getBytes | public void java.lang.String.getBytes(int,int,byte[],int) |
getBytes | public byte[] java.lang.String.getBytes(java.nio.charset.Charset) |
contentEquals | public boolean java.lang.String.contentEquals(java.lang.StringBuffer) |
contentEquals | public boolean java.lang.String.contentEquals(java.lang.CharSequence) |
equalsIgnoreCase | public boolean java.lang.String.equalsIgnoreCase(java.lang.String) |
compareToIgnoreCase | public int java.lang.String.compareToIgnoreCase(java.lang.String) |
regionMatches | public boolean java.lang.String.regionMatches(int,java.lang.String,int,int) |
regionMatches | public boolean java.lang.String.regionMatches(boolean,int,java.lang.String,int,int) |
startsWith | public boolean java.lang.String.startsWith(java.lang.String) |
startsWith | public boolean java.lang.String.startsWith(java.lang.String,int) |
endsWith | public boolean java.lang.String.endsWith(java.lang.String) |
lastIndexOf | public int java.lang.String.lastIndexOf(int,int) |
lastIndexOf | public int java.lang.String.lastIndexOf(java.lang.String,int) |
lastIndexOf | public int java.lang.String.lastIndexOf(int) |
lastIndexOf | public int java.lang.String.lastIndexOf(java.lang.String) |
substring | public java.lang.String java.lang.String.substring(int) |
substring | public java.lang.String java.lang.String.substring(int,int) |
subSequence | public java.lang.CharSequence java.lang.String.subSequence(int,int) |
concat | public java.lang.String java.lang.String.concat(java.lang.String) |
replace | public java.lang.String java.lang.String.replace(char,char) |
replace | public java.lang.String java.lang.String.replace(java.lang.CharSequence,java.lang.CharSequence) |
matches | public boolean java.lang.String.matches(java.lang.String) |
contains | public boolean java.lang.String.contains(java.lang.CharSequence) |
replaceFirst | public java.lang.String java.lang.String.replaceFirst(java.lang.String,java.lang.String) |
replaceAll | public java.lang.String java.lang.String.replaceAll(java.lang.String,java.lang.String) |
split | public java.lang.String[] java.lang.String.split(java.lang.String,int) |
split | public java.lang.String[] java.lang.String.split(java.lang.String) |
join | public static java.lang.String java.lang.String.join(java.lang.CharSequence,java.lang.CharSequence[]) |
join | public static java.lang.String java.lang.String.join(java.lang.CharSequence,java.lang.Iterable) |
toLowerCase | public java.lang.String java.lang.String.toLowerCase(java.util.Locale) |
toLowerCase | public java.lang.String java.lang.String.toLowerCase() |
toUpperCase | public java.lang.String java.lang.String.toUpperCase() |
toUpperCase | public java.lang.String java.lang.String.toUpperCase(java.util.Locale) |
trim | public java.lang.String java.lang.String.trim() |
toCharArray | public char[] java.lang.String.toCharArray() |
format | public static java.lang.String java.lang.String.format(java.util.Locale,java.lang.String,java.lang.Object[]) |
format | public static java.lang.String java.lang.String.format(java.lang.String,java.lang.Object[]) |
copyValueOf | public static java.lang.String java.lang.String.copyValueOf(char[],int,int) |
copyValueOf | public static java.lang.String java.lang.String.copyValueOf(char[]) |
intern | public native java.lang.String java.lang.String.intern() |
wait | public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException |
wait | public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException |
wait | public final void java.lang.Object.wait() throws java.lang.InterruptedException |
getClass | public final native java.lang.Class java.lang.Object.getClass() |
notify | public final native void java.lang.Object.notify() |
notifyAll | public final native void java.lang.Object.notifyAll() |
chars | public default java.util.stream.IntStream java.lang.CharSequence.chars() |
codePoints | public default java.util.stream.IntStream java.lang.CharSequence.codePoints() |
String Method example
Concatenating two string
Using a + operator or concat() method are used to combine the value of two literals or two string object value in java programming.
public class MyString {
public static void main(String[] args) {
String textOne="Java ",textTwo="Programming";
//concatenating two string object values by + operator
String test1=textOne + textTwo;
//concatenating two string object values by concat()
String test2=textOne.concat(textTwo);
System.out.println(test1);
System.out.println(test2);
}
}
Output
Java Programming
Java Programming
Compare Two String
When we are compare two string object value in Java Programming, Then there is possible most of programmer are use == (equal to equal to) Operator. But that is not valid when create a string object by using new operator And compare the string object to a constant literals. See this example.
//compare string
public class MyString{
public static void main(String[] args) {
String text1="case1";
String text2="case1";
//Case 1 :Compare two normal text variables
if(text1==text2){
System.out.println("Case 1 True");
}else{
System.out.println("Case 1 False");
}
String text3=new String("case2");
//Case 2 : comparing of one string object and text string
if(text3=="case2"){
System.out.println("Case 2 True");
}else{
System.out.println("Case 2 False");
}
String text4=new String("case3");
String text5=new String("case3");
//case 3 : comparing of two string object
if(text4==text5){
System.out.println("Case 3 True");
}else{
System.out.println("Case 3 False");
}
}
}
Output
Case 1 True
Case 2 False
Case 3 False
So we can use equal() String function to compare two different objects and constant literals value. Comparing of string value using of equal() java function.
//java compare string
public class MyString{
public static void main(String[] args) {
String text1="case1";
String text2="case1";
String text3=new String("case2");
String text4=new String("case3");
String text5=new String("case3");
//compare value of two string by equals() function
System.out.println(text1.equals(text2));
System.out.println(text3.equals("case2"));
System.out.println(text4.equals(text5));
System.out.println("case2".equals(text5));
}
}
Output
true
true
true
false
Split a String in Java
When we are need to split string elements by specific character,digits and symbols to separate. In this situation we can use split() function in java programming. For example.
//split a string in Java
class Execution{
public int data;
public static void main(String[] args) {
String dataVale="10-12-2020";
//divide string by -
String[] newData=dataVale.split("-");
System.out.println(newData[0]); //10
System.out.println(newData[1]); //12
System.out.println(newData[2]); //2020
}
}

10
12
2020
There is an basic example in case we are need to split string in particular limit then we can choose another variant of split(String regex, int limit) function.
//Split a string in Java
class Execution{
public static void main(String[] args) {
String dataVale="1-2-3-4-5";
//divide string by -
String[] splitData=dataVale.split("-",4); //limit 4
for (String item : splitData) {
System.out.println(item);
}
}
}

1
2
3
4-5
Note that This function are split a string from left to right.
Replace Text In String
When we are need to modify specific character or text value in any string objects. Then we can use replaceAll(String oldText, String newText) method. This method are replacing all oldText value to newText value , And return a new String literals
public class MyString {
public static void main(String[] args) {
String textData="Learn X to X";
//Replace letter X to Java
String newText=textData.replaceAll("X","Java");
System.out.println(textData); //actual text
System.out.println(newText); //new converted text
}
}
Output
Learn X to X
Learn Java to Java
Uppercase and Lowercase conversion
Some case we are need to convert a string data to lowercase and uppercase letters. In this situation we can use toLowerCase() in toUpperCase() methods.
public class MyString {
public static void main(String[] args) {
String textData="Simple Text";
//lowercase conversion
System.out.println("Lower Case Text: "+(textData.toLowerCase()));
//uppercase conversion
System.out.println("Upper Case Text: "+(textData.toUpperCase()));
//Actual object value
System.out.println("Given Text: "+textData);
}
}
Output
Lower Case Text: simple text
Upper Case Text: SIMPLE TEXT
Given Text: Simple Text
Note that both method ( toLowerCase() and toUpperCase() ) are not modified the object value that is returning new Text when is form of lowercase and uppercase letters.
Evaluate string mathematical expression
Generally all math operations are work in numeric values. In case given mathematical equation and expression are in form of string. Then there are very difficult to execute this evaluates logically. We can evaluate in this expression as follows.
//Evaluate string math expression
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
class Execution{
public static void main(String[] args) {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByName("JavaScript");
String text = "1000+10*2";
try{
//When String text is valid mathematical expression
System.out.println(se.eval(text)); //1020
}catch(Exception e){
System.out.println(e);
}
}
}
Output
1020
Convert string to integers in java
parseInt() method are used to convert string text to an integers. note that string text is form of numbers otherwise it will produce an exception. So put this process inside try catch block.
//Java convert string to integers
class Execution{
public static void main(String[] args) {
String text="123";
int number=0;
try{
//convert text value to int
number=Integer.parseInt(text);
System.out.println(number);
}catch(NumberFormatException ex){
number=0;
System.out.println("Invalid Text");
}
}
}
Output
123
Trim String Text
public class MyString{
public static void main(String[] args){
String text = " Simple\tTest String ";
//Replace tab to space
//And removing spaces in beginning and end of text data
String trimText=text.trim(); //trim
System.out.println(text);
System.out.println(trimText);
}
}
Simple Test String
Simple Test String
Substrings String Text
This method are useful to implements new substring.
public class MyString{
public static void main(String[] args){
String text = "Code Keyword A-Z";
String subTextOne=text.substring(5);
String subTextTwo=text.substring(5,12);
System.out.println(text);
System.out.println(subTextOne);
System.out.println(subTextTwo);
}
}
Code Keyword A-Z
Keyword A-Z
Keyword
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment