String Handling in Java
String Handling in Java
The String class is immutable (constant), i.e. Strings in java, once created and
initialized, cannot be changed.
The String is a final class, no other class can extend it, and you cannot change the
state of the string.
String values cannot be compare with '==', for string value comparison, use equals()
method.
String class supports various methods, including comparing strings, extracting
substrings, searching characters & substrings, converting into either lower case or
upper case, etc.
The string examples given below describes more on string functionality.
Description:
Here you can see example for different ways of initializing string. You can create and
initialize string object by calling its constructor, and pass the value of the string. Also you can
pass character array to the string constructor. You can also directly assign string value to the
string reference, which is equals to creating string object by calling constructor. The empty
string constructor will create string object with empty value.
char[] c = {'a','b','c','d'};
1
How to convert Character array to String object?
Description:
Below example shows how to convert character array to a string object. By using
String.copyValueOf() method you can convert char array to string object. Also you can copy
range of character array to string.
/**
* copyValueOf() method.
*/
System.out.println(chStr);
/**
*/
System.out.println(subStr);
Description:
Below example shows different ways of append or concat two string objects. You can append
two strings by just using "+" sign. Also you can concatenate two string objects by calling
concat() method.
2
/**
*/
String d = b+c;
System.out.println(d);
/**
*/
d = b.concat(c);
System.out.println(d);
String x = "JUNK";
String y = "junk";
/**
*/
if(x.equals(y)){
} else {
3
}
/**
*/
if(x.equalsIgnoreCase(y)){
} else {
StringBuffer sb =
/**
*/
if(c.contentEquals(sb)){
} else {
4
StringBuffer asb =
if(c.contentEquals(asb)){
} else {
byte[] b = str.getBytes();
5
String str = "Use this string for testing this";
/**
*/
+str.indexOf('s',4));
+str.indexOf("this",6));
/**
6
* searching backward starting at the specified index.
*/
+str.lastIndexOf('s',24));
+str.lastIndexOf("this",26));
}}
+str.startsWith("This"));
+str.startsWith("is"));
+str.startsWith("is", 5));
7
public static void main(String a[]){
if(str.endsWith("example")){
} else {
if(str.endsWith("java")){
} else {
for(String s:tokens){
System.out.println(s);
8
tokens = str.split("\\s+");
/**
* char array.
*/
System.out.println(ch);
9
public static void main(String a[]){
+str.replace('s', 'o'));
+str.replaceFirst("is", "ui"));
+str.replaceAll("is", "no"));
10
public static void main(String a[]){
System.out.println(str.trim());
import java.util.Locale;
System.out.println(String.format(str, "string"));
System.out.println(String.format(str1, 10));
/**
*/
11
Below example shows how to match a string pattern with a regular expression.
String.matches() method helps to match the string with a regex. Below example checkes
weather given string starts with "www" or not.
public class MyStrMatches {
if(str[i].matches("^www\\.(.+)")){
} else {
while(st.hasMoreElements()){
sb.append(st.nextElement()).append(" ");
System.out.println(sb.toString().trim());
12
Program: How to remove non-ascii characters from a string?
Description:
Some times we need to handle text data, wherein we have to handle only ascii characters.
Below example shows how to remove non-ascii characters from the given string by using
regular expression.
public class MyNonAsciiString {
System.out.println(str);
System.out.println(str);
System.out.println(text);
System.out.println(text);
13
expression [\n|\r]. It will split the string based on the new line char and carriage return char.
After the split, we will get string array, and returning length of the array.
return text.split("[\n|\r]").length;
System.out.println(str);
/*
This Java ArrayList to String Array example shows how to convert ArrayList to String array
in Java.
*/
import java.util.ArrayList;
import java.util.Arrays;
14
public class ArrayListToStringArrayExample {
aListDays.add("Sunday");
aListDays.add("Monday");
aListDays.add("Tuesday");
/*
* Please note that toArray method returns Object array, not String array.
*/
System.out.println(strDays[i]);
15
Java String Reverse Example
/*
*/
/*
*/
/*
16
Java String to Date Example.
This Java String to Date example shows how to convert Java String to Date
object.
*/
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
*/
try{
/*
*/
17
//convert Java String to Date using parse method of SimpleDateFormat
//Please note that parse method throws ParseException if the String date could not be
parsed.
}catch(ParseException e){
import java.util.ArrayList;
import java.util.Arrays;
/*
This Java String to ArrayList example shows how to convert Java String containing values to
Java ArrayList.
*/
/*
* To convert Java String to ArrayList, first split the string and then
18
* use asList method of Arrays class to convert it to ArrayList.
*/
/*
* Use asList method of Arrays class to convert Java String array to ArrayList
*/
Substring Example
/*
This Java substring example describes how substring method of java String class can
*/
/*
Java String class defines two methods to get substring from the given
19
This method returns new String object containing the substring of the
This method returns new String object containing the substring of the
*/
/*
*/
System.out.println(name.substring(6));
/*
This will print the substring starting from index 0 upto 4 not 5.
*/
System.out.println(name.substring(0,5));
20
public static void main(String[] args) {
if(compare == 0)
else
21
System.out.println("Converting "+str1+" to lower case : "+str1.toLowerCase());
22