0% found this document useful (0 votes)
28 views

String Handling in Java

An introduction about String handling in Java

Uploaded by

Nathali Rodrigo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

String Handling in Java

An introduction about String handling in Java

Uploaded by

Nathali Rodrigo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

String handling in Java - Examples

 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.

String Initialization Sample Code

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.

public class MyStringInitialization {

public static void main(String a[]){

String abc = "This is a string object";

String bcd = new String("this is also string object");

char[] c = {'a','b','c','d'};

String cdf = new String(c);

String junk = abc+" This is another String object";

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.

public class MyArrayCopy {

public static void main(String a[]){

char ch[] = {'M','y',' ','J','a','v','a',' ','e','x','a','m','p','l','e'};

/**

* We can copy a char array to a string by using

* copyValueOf() method.

*/

String chStr = String.copyValueOf(ch);

System.out.println(chStr);

/**

* We can also copy only range of charactors in a

* char array by copyValueOf() method.

*/

String subStr = String.copyValueOf(ch,3,4);

System.out.println(subStr);

How to append or concat two Strings in java?

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.

public class MyStringConcat {

public static void main(String a[]){

String b = "jump ";

String c = "No jump";

2
/**

* We can do string concatination by two ways.

* One is by using '+' operator, shown below.

*/

String d = b+c;

System.out.println(d);

/**

* Another way is by using concat() method,

* which appends the specified string at the end.

*/

d = b.concat(c);

System.out.println(d);

How to compare two String objects in java?


Description:
The below example shows how to compare two string objects in java. You can not use "=="
operator to compare two strings. String provides equals() method to compare two string
objects. Also you can ignore case during string compare by calling equalsIgnoreCase()
method. '==' operator compares the object reference but not the string value.
public class MyStringEquals {

public static void main(String a[]){

String x = "JUNK";

String y = "junk";

/**

* We cannot use '==' operator to compare two strings.

* We have to use equals() method.

*/

if(x.equals(y)){

System.out.println("Both strings are equal.");

} else {

System.out.println("Both strings are not equal.");

3
}

/**

* We can ignore case with equalsIgnoreCase() method

*/

if(x.equalsIgnoreCase(y)){

System.out.println("Both strings are equal.");

} else {

System.out.println("Both strings are not equal.");

How to compare StringBuffer object to String object in java?


Description:
The below example shows how to compare StringBuffer object with String object. String
object provides contentEquals() method to compare content with a StringBuffer object.
public class MyStringComp {

public static void main(String a[]){

String c = "We are comparing the content with a StringBuffer content";

StringBuffer sb =

new StringBuffer("We are comparing the content with a StringBuffer content");

/**

* We can use contentEquals() method to compare content with a StringBuffer.

* It returns boolean value.

*/

if(c.contentEquals(sb)){

System.out.println("The content is equal");

} else {

System.out.println("The content is not equal");

4
StringBuffer asb =

new StringBuffer("You cannot compare the content with a String content");

if(c.contentEquals(asb)){

System.out.println("The content is equal");

} else {

System.out.println("The content is not equal");

How to get byte array from a string object in java?


Description:
Sometimes we have to convert string object into byte array. You can use getBytes() methode
to convert string object to byte array.
public class MyStringBytes {

public static void main(String a[]){

String str = "core java api";

byte[] b = str.getBytes();

System.out.println("String length: "+str.length());

System.out.println("Byte array length: "+b.length);

How to get index of a character or string from another String in java?


Description:
Below method shows how to get index of a specified character or string from the given
string. By using indexOf() method you get get the position of the sepcified string or char
from the given string. You can also get the index strting from a specified position of the
string.
public class MyStringIndexOf {

public static void main(String[] a){

5
String str = "Use this string for testing this";

System.out.println("Basic indexOf() example");

System.out.println("Char 's' at first occurance: "+str.indexOf('s'));

System.out.println("String \"this\" at first occurance: "+str.indexOf("this"));

/**

* Returns the first occurance from specified start index

*/

System.out.println("First occurance of char 's' from 4th index onwards : "

+str.indexOf('s',4));

System.out.println("First occurance of String \"this\" from 6th index onwards: "

+str.indexOf("this",6));

Java String lastIndexOf() Sample Code


Description:
Below example shows how to get index of a given character or string from a string in the
reverse order, means last occuring index. By using lastIndexOf() method you can get last
occurence of the the reference string or character. Also lastIndexOf() method gives last
occurence based on a specific position.

public class MyStrLastIndexOf {

public static void main(String a[]){

String str = "Use this string for testing this";

System.out.println("Basic lastIndexOf() example");

System.out.println("Char 's' at last occurance: "+str.lastIndexOf('s'));

System.out.println("String \"this\" at last occurance: "+str.lastIndexOf("this"));

/**

* Returns the last occurance from specified start index,

6
* searching backward starting at the specified index.

*/

System.out.println("first occurance of char 's' from 24th index backwards: "

+str.lastIndexOf('s',24));

System.out.println("First occurance of String \"this\" from 26th index backwards: "

+str.lastIndexOf("this",26));

}}

How to find a string start with another string value in java?


Description:
Below example shows how to find whether a string value start with another string value. By
using startsWith() method, you can get whether the string starts with the given string or not.
Also this method tells that the string occurence at a specific position.

public class MyStrStartsWith {

public static void main(String a[]){

String str = "This is an example string.";

System.out.println("Is this string starts with \"This\"? "

+str.startsWith("This"));

System.out.println("Is this string starts with \"is\"? "

+str.startsWith("is"));

System.out.println("Is this string starts with \"is\" after index 5? "

+str.startsWith("is", 5));

How to find a string ends with another string value in java?


Description:
Below example shows how to find whether a string value ends with another string value. By
using endsWith() method, you can get whether the string ends with the given string or not.
Also this method tells that the string occurrence at a specific position.
public class MyStringEnd {

7
public static void main(String a[]){

String str = "This is a java string example";

if(str.endsWith("example")){

System.out.println("This String ends with example");

} else {

System.out.println("This String is not ending with example");

if(str.endsWith("java")){

System.out.println("This String ends with java");

} else {

System.out.println("This String is not ending with java");

How to break or split a string with a delimiter in java?


Description:
Below example shows how to split or brake a string. The split() method splits the string based
on the given regular expression or delimiter, and returns the tokens in the form of array.
Below example shows splitting string with space, and second split is based on any kind of
spaces that includes tab, enter, line breaks, etc.
public class MyStrSplit {

public static void main(String a[]){

String str = "This program splits a string based on space";

String[] tokens = str.split(" ");

for(String s:tokens){

System.out.println(s);

str = "This program splits a string based on space";

8
tokens = str.split("\\s+");

How to extract Char Array from String in Java?


Description:
Below example shows how to copy range of characters from the given string to another
character array. By suing getChars() method, you can copy range of characters from the given
string.
public class MyCharArrayCopy {

public static void main(String a[]){

String str = "Copy chars from this string";

char[] ch = new char[5];

/**

* The getChars() method accepts 4 parameters

* first one is the start index from string

* second one is the end index from string

* third one is the destination char array

* forth one is the start index to append in the

* char array.

*/

str.getChars(5, 10, ch, 0);

System.out.println(ch);

How to replace string characters in java?


Description:
Below example shows how to get replace character or a string into a string with the given
string. String provides replace() method to replace a specific character or a string which
occures first. replaceAll() method replaces a specific character or a string at each occurence.
public class MyStringReplace {

9
public static void main(String a[]){

String str = "This is an example string";

System.out.println("Replace char 's' with 'o':"

+str.replace('s', 'o'));

System.out.println("Replace first occurance of string\"is\" with \"ui\":"

+str.replaceFirst("is", "ui"));

System.out.println("Replacing \"is\" every where with \"no\":"

+str.replaceAll("is", "no"));

How to change case of a string characters in Java?


Description:
Below example shows how to convert the case of a given string. toUpperCase() method
converts all string characters to upper case. toLowerCase() method converts all string
characters to lower case.
public class MyStringCase {

public static void main(String a[]){

String str = "Change My Case";

System.out.println("Upper Case: "+str.toUpperCase());

System.out.println("Lower Case: "+str.toLowerCase());

How to trim spaces in the given string in java?


Description:
Below example shows how to trim spaces in the given string. The trim() function removes all
kind of space characters at both ends, means removes starting and trailing spaces. These
space characters includes normal space, enter, new line, tab, etc.
public class MyStringTrim {

10
public static void main(String a[]){

String str = " Junk ";

System.out.println(str.trim());

How to format given string in java?


Description:
String.format() method helps us to format the given string. It replaces each format item in a
specified string with the text equivalent of a corresponding object's value. Example can
explain more:

import java.util.Locale;

public class MyStringFormatter {

public static void main(String a[]){

String str = "This is %s format example";

System.out.println(String.format(str, "string"));

String str1 = "We are displaying no %d";

System.out.println(String.format(str1, 10));

/**

* String format by specifying Locale details

*/

System.out.println("String format with Locale info:");

System.out.println(String.format(Locale.US, str1, 10));

How to match a format in string using regular expression?


Description:

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 {

public static void main(String a[]){

String[] str = {"www.java2novice.com", "http://java2novice.com"};

for(int i=0;i < str.length;i++){

if(str[i].matches("^www\\.(.+)")){

System.out.println(str[i]+" Starts with 'www'");

} else {

System.out.println(str[i]+" is not starts with 'www'");

How to remove multiple spaces in a string in Java?


Description:
Below example shows how to remove multiple spaces from the given string.
import java.util.StringTokenizer;

public class MyStrRemoveMultSpaces {

public static void main(String a[]){

String str = "String With Multiple Spaces";

StringTokenizer st = new StringTokenizer(str, " ");

StringBuffer sb = new StringBuffer();

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 {

public static void main(String a[]){

String str = "Bj��rk����oacute�";

System.out.println(str);

str = str.replaceAll("[^\\p{ASCII}]", "");

System.out.println("After removing non ASCII chars:");

System.out.println(str);

Program: How to remove html tags from a string?


Description:
In case if a string contains html tags, then below example helps to trim the html tags from the
string. The example uses regular expression to trim the html tags from the string.

public class MyHtmlTagRemover {

public static void main(String a[]){

String text = "<B>I don't want this to be bold<\\B>";

System.out.println(text);

text = text.replaceAll("\\<.*?\\>", "");

System.out.println(text);

Program: How to get line count from a string?


Description:
This example shows how to get line count from a string. Assuming that we have read the file
and keeping the content in string. We are using String.split() method with the use of regular

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.

public class MyStringLineCounter {

public static int getLineCount(String text){

return text.split("[\n|\r]").length;

public static void main(String a[]){

String str = "line1\nline2\nline3\rline4";

System.out.println(str);

int count = getLineCount(str);

System.out.println("line count: "+count);

Java ArrayList to String Array Example

/*

Java ArrayList to String Array Example

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 {

public static void main(String args[]){

//ArrayList containing string objects

ArrayList<String> aListDays = new ArrayList<String>();

aListDays.add("Sunday");

aListDays.add("Monday");

aListDays.add("Tuesday");

/*

* To convert ArrayList containing String elements to String array, use

* Object[] toArray() method of ArrayList class.

* Please note that toArray method returns Object array, not String array.

*/

//First Step: convert ArrayList to an Object array.

Object[] objDays = aListDays.toArray();

//Second Step: convert Object array to String array

String[] strDays = Arrays.copyOf(objDays, objDays.length, String[].class);

System.out.println("ArrayList converted to String array");

//print elements of String array

for(int i=0; i < strDays.length; i++){

System.out.println(strDays[i]);

15
Java String Reverse Example

/*

Java String Reverse example.

This example shows how to reverse a given string

*/

public class StringReverseExample {

public static void main(String args[]){

//declare orinial string

String strOriginal = "Hello World";

System.out.println("Original String : " + strOriginal);

/*

The easiest way to reverse a given string is to use reverse()

method of java StringBuffer class.

reverse() method returns the StringBuffer object so we need to

cast it back to String using toString() method of StringBuffer

*/

strOriginal = new StringBuffer(strOriginal).reverse().toString();

System.out.println("Reversed String : " + strOriginal);

/*

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;

public class JavaStringToDate {

public static void main(String args[]){

//Java String having date

String strDate = "21/08/2011";

/*

* To convert Java String to Date, use

* parse(String) method of SimpleDateFormat class.

* parse method returns the Java Date object.

*/

try{

/*

* Create new object of SimpleDateFormat class using

* SimpleDateFormat(String pattern) constructor.

*/

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

17
//convert Java String to Date using parse method of SimpleDateFormat

Date date = sdf.parse(strDate);

//Please note that parse method throws ParseException if the String date could not be
parsed.

System.out.println("Date is: " + date);

}catch(ParseException e){

System.out.println("Java String could not be converted to Date: " + e);

import java.util.ArrayList;

import java.util.Arrays;

/*

Java String to ArrayList Example.

This Java String to ArrayList example shows how to convert Java String containing values to

Java ArrayList.

*/

public class JavaStringToArrayList {

public static void main(String args[]){

//String object having values, separated by ","

String strNumbers = "1,2,3,4,5";

/*

* To convert Java String to ArrayList, first split the string and then

18
* use asList method of Arrays class to convert it to ArrayList.

*/

//split the string using separator, in this case it is ","

String[] strValues = strNumbers.split(",");

/*

* Use asList method of Arrays class to convert Java String array to ArrayList

*/

ArrayList<String> aListNumbers = new ArrayList<String>(Arrays.asList(strValues));

System.out.println("Java String converted to ArrayList: " + aListNumbers);

Substring Example

/*

Java substring example.

This Java substring example describes how substring method of java String class can

be used to get substring of the given java string object.

*/

public class JavaSubstringExample{

public static void main(String args[]){

/*

Java String class defines two methods to get substring from the given

Java String object.

1) public String substring(int startIndex)

19
This method returns new String object containing the substring of the

given string from specified startIndex (inclusive).

IMPORTANT : This method can throw IndexOutOfBoundException if startIndex

is negative or grater than length of the string.

2) public String substring(int startIndex,int endIndex)

This method returns new String object containing the substring of the

given string from specified startIndex to endIndex. Here, startIndex is

inclusive while endIndex is exclusive.

IMPORTANT: This method can throw IndexOutOfBoundException if startIndex

is negative and if startIndex of endIndex is grater than the string length.

*/

String name="Hello World";

/*

This will print the substring starting from index 6

*/

System.out.println(name.substring(6));

/*

This will print the substring starting from index 0 upto 4 not 5.

IMPORTANT : Here startIndex is inclusive while endIndex is exclusive.

*/

System.out.println(name.substring(0,5));

public class StringFunctionsExample {

20
public static void main(String[] args) {

String str1 = "RoseIndia";

String str2 = "roseIndia";

String str3 = "Delhi";

String str4 = "india";

System.out.println("1. Third character of String '"+str1+"' : "+str1.charAt(2));

System.out.println("2. Length of String '"+str1+"' : "+str1.length());

System.out.println("3. Unicode of "+str1.charAt(str1.length()-1)+" :


"+str1.codePointAt(str1.length()-1));

int compare = str1.compareToIgnoreCase(str2);

if(compare == 0)

System.out.println("4. "+str1+" and "+str2+" both string is same when


compare them and ignoring case differences");

else if(compare > 0 )

System.out.println("4. "+str1+" is less than "+str2);

else

System.out.println("4. "+str1+" is greater than "+str2);

System.out.println("5. After Concating "+str1+" and "+str3+" : "+str1.concat(str3));

boolean bol = str1.endsWith("India");

System.out.println("6. Whether the string '"+str1+"' has suffix '"+str4+"' : "+bol);

System.out.println("7. Index of character "+str1.charAt(str1.length()-2)+" in String


'"+str1+"' : "+str1.indexOf(str1.charAt(str1.length()-2)));

21
System.out.println("Converting "+str1+" to lower case : "+str1.toLowerCase());

System.out.println("Converting "+str2+" to upper case : "+str1.toUpperCase());

22

You might also like