Java String
In Java, string is basically an object that represents sequence of char values. An array of characters works
same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on string such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and
StringBuilder classes implement it. It means, we can create strings in java by using these three classes.
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new
instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes. We will discuss
immutable string later. Let's first understand what is String in Java and how to create the String object.
What is String in java
Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of
characters. The java.lang.String class is used to create a string object.
How to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already
exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string object with the
value "Welcome" in string constant pool that is why it will create a new object. After that it will find the
string with the value "Welcome" in the pool, it will not create a new object but will return the reference to
the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it exists already in the string
constant pool).
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-
pool).
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new
keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
java
strings
example
Creating a String
There are two ways to create string in Java:
1. String literal
String s = “Academy of Technology”;
2. Using new keyword
String s = new String (“Academy of Technology”);
Constructors
1. String(byte[] byte_arr) – Construct a new String by decoding the byte array. It uses the
platform’s default character set for decoding.
Example:
byte[] b_arr = {65, 66, 67, 68, 69};
String s_byte =new String(b_arr); //ABCDE
2. String(byte[] byte_arr, Charset char_set) – Construct a new String by decoding the byte
array. It uses the char_set for decoding.
Example:
byte[] b_arr = {65, 66, 67, 68, 69};
Charset cs = Charset.defaultCharset();
String s_byte_char = new String(b_arr, cs); //ABCDE
3. String(byte[] byte_arr, String char_set_name) – Construct a new String by decoding the byte
array. It uses the char_set_name for decoding.
It looks similar to the above constructs and they before similar functions but it takes the
String(which contains char_set_name) as parameter while the above constructor takes CharSet.
Example:
byte[] b_arr = {65, 66, 67, 68, 69};
String s = new String(b_arr, "US-ASCII"); //ABCDE
4. String(byte[] byte_arr, int start_index, int length) – Construct a new string from the bytes
array depending on the start_index(Starting location) and length(number of characters from
starting location).
Example:
byte[] b_arr = {65, 66, 67, 68, 69};
String s = new String(b_arr, 1, 3); // BCD
5. String(byte[] byte_arr, int start_index, int length, Charset char_set) – Construct a new
string from the bytes array depending on the start_index(Starting location) and length(number
of characters from starting location).Uses char_set for decoding.
Example:
byte[] b_arr = {65, 66, 67, 68, 69};
Charset cs = Charset.defaultCharset();
String s = new String(b_arr, 1, 3, cs); // BCD
6. String(byte[] byte_arr, int start_index, int length, String char_set_name) – Construct a new
string from the bytes array depending on the start_index(Starting location) and length(number
of characters from starting location).Uses char_set_name for decoding.
Example:
byte[] b_arr = {65, 66, 67, 68, 69};
String s = new String(b_arr, 1, 4, "US-ASCII"); // BCDE
7. String(char[] char_arr) – Allocates a new String from the given Character array
Example:
char char_arr[] = {'A', 'B', 'C', 'D', 'E'};
String s = new String(char_arr); //ABCDE
8. String(char[] char_array, int start_index, int count) – Allocates a String from a given
character array but choose count characters from the start_index.
Example:
char char_arr[] = {'A', 'B', 'C', 'D', 'E'};
String s = new String(char_arr , 1, 3); //BCD
9. String(int[] uni_code_points, int offset, int count) – Allocates a String from a
uni_code_array but choose count characters from the start_index.
Example:
int[] uni_code = {65, 66, 67, 68, 69};
String s = new String(uni_code, 1, 3); //BCD
10. String(StringBuffer s_buffer) – Allocates a new string from the string in s_buffer
Example:
String s_buffer = "ABCDE";
String s = new String(s_buffer); //ABCDE
11. String(StringBuilder s_builder) – Allocates a new string from the string in s_builder
Example:
String s_builder = "ABCDE";
String s = new String(s_builder); //ABCDE
String Methods
int length(): Returns the number of characters in the String.
"Academy of Technology".length(); // returns 21
Char charAt(int i): Returns the character at ith index.
"Academy of Technology".charAt(3); // returns „d‟
String substring (int i): Return the substring from the ith index character to end.
"Academy of Technology".substring(8); // returns “of Technology”
String substring (int i, int j): Returns the substring from i to j-1 index.
"Academy of Technology".substring(3, 7); // returns “demy”
String concat( String str): Concatenates specified string to the end of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”
int indexOf (String s): Returns the index within the string of the first occurrence of the specified
string.
String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6
int indexOf (String s, int i): Returns the index within the string of the first occurrence of the
specified string, starting at the specified index.
String s = ”Learn Share Learn”;
int output = s.indexOf(„a‟,3);// returns 8
Int lastindexOf( int ch): Returns the index within the string of the last occurrence of the specified
string.
String s = ”Learn Share Learn”;
int output = s.lastindexOf(„a‟); // returns 14
boolean equals( Object otherObj): Compares this string to the specified object.
Boolean out = “Geeks”.equals(“Geeks”); // returns true
Boolean out = “Geeks”.equals(“geeks”); // returns false
boolean equalsIgnoreCase (String anotherString): Compares string to another string,
ignoring case considerations.
Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true
int compareTo( String anotherString): Compares two string lexicographically.
int out = s1.compareTo(s2);
// where s1 ans s2 are strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out >0 // s1 comes after s2.
int compareToIgnoreCase( String anotherString): Compares two string lexicographically,
ignoring case considerations.
int out = s1.compareToIgnoreCase(s2);
// where s1 ans s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out >0 // s1 comes after s2.
Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase
or lowercase).
String toLowerCase(): Converts all the characters in the String to lower case.
String word1 = “HeLLo”;
String word3 = word1.toLowerCase(); // returns “hello"
String toUpperCase(): Converts all the characters in the String to upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”
String trim(): Returns the copy of the String, by removing whitespaces at both ends. It does not
affect whitespaces in the middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”
String replace (char oldChar, char newChar): Returns new string by replacing all occurrences
of oldChar with newChar.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(„f‟ ,‟g‟); // returns “geeksgorgeeks”
Note:- s1 is still feeksforfeeks and s2 is geeksgorgeeks
Immutable String in Java
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable
objects
}
}
Output: Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is
created with sachintendulkar. That is why string is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still refers to
"Sachin" not to "Sachin Tendulkar".
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar" object.
For example:
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not modified.
Why string objects are immutable in java?
Because java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one
object "sachin".If one reference variable changes the value of the object, it will be affected to all the
reference variables. That is why string objects are immutable in java.
Java String compare
We can compare string in java on the basis of content and reference.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching
(by == operator) etc.
There are three ways to compare string in java:
1. By equals() method
2. By = = operator
3. By compareTo() method
1) String compare by equals() method
The String equals() method compares the original content of the string. It compares values of string for
equality. String class provides two methods:
public boolean equals(Object another) compares this string to the specified object.
public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring
case.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Output:true
true
false
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}
Output:
false
true
2) String compare by == operator
The = = operator compares references not values.
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same
instance)
System.out.println(s1==s3);//false(because s3 refers to instance
created in nonpool)
}
}
Output: true
false
3) String compare by compareTo() method
The String compareTo() method compares values lexicographically and returns an integer value that
describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output:0
1
-1
String Concatenation in Java
In java, string concatenation forms a new string that is the combination of multiple strings. There are two
ways to concat string in java:
1. By + (string concatenation) operator
2. By concat() method
1) String Concatenation by + (string concatenation) operator
Java string concatenation operator (+) is used to add strings. For Example:
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
Output: Sachin Tendulkar
The Java compiler transforms above code to this:
String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();
In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and its
append method. String concatenation operator produces a new string by appending the second operand onto
the end of the first operand. The string concatenation operator can concat not only string but primitive values
also. For Example:
class TestStringConcatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
}
}
80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation operator.
2) String Concatenation by concat() method
The String concat() method concatenates the specified string to the end of current string. Syntax:
1. public String concat(String another)
Let's see the example of String concat() method.
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
Sachin Tendulkar
Java String trim() method
The string trim() method eliminates white spaces before and after string.
String s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin
Sachin
Sachin
Java String startsWith() and endsWith() method
String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true
true
true
Java String intern() method
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as
determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String
object is added to the pool and a reference to this String object is returned.
String s=new String("Sachin");
String s2=s.intern();
System.out.println(s2);//Sachin
Sachin
Java String valueOf() method
The string valueOf() method coverts given type such as int, long, float, double, boolean, char and char array
into string.
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
Output:
1010
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with second sequence of
character.
String s1="Java is a programming language. Java is a platform. Java
is an Island.";
String replaceString=s1.replace("Java","Kava");//replaces all
occurrences of "Java" to "Kava"
System.out.println(replaceString);
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
How to create Immutable class?
There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In
short, all the wrapper classes and String class is immutable. We can also create immutable class by creating
final class that have final data members as the example given below:
Example to create Immutable class
In this example, we have created a final class named Employee. It have one final datamember, a
parameterized constructor and getter method.
public final class Employee{
final String pancardNumber;
public Employee(String pancardNumber){
this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
}
}
The above class is immutable because:
The instance variable of the class is final i.e. we cannot change the value of it after creating an
object.
The class is final so we cannot create the subclass.
There is no setter methods i.e. we have no option to change the value of the instance variable.
These points makes this class as immutable.
Java toString() method
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding
the toString() method, returns the desired output, it can be the state of an object etc. depends on your
implementation.
Advantage of Java toString() method
By overriding the toString() method of the Object class, we can return values of the object, so we don't need
to write much code.
Understanding problem without toString() method
Let's see the simple code that prints reference.
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here
s1.toString()
System.out.println(s2);//compiler writes here
s2.toString()
}
}
Output:Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I want
to print the values of these objects. Since java compiler internally calls toString() method, overriding this
method will return the specified values. Let's understand it with the example given below:
Example of Java toString() method
Now let's see the real example of toString() method.
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public String toString(){//overriding the toString() method
return rollno+" "+name+" "+city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here
s1.toString()
System.out.println(s2);//compiler writes here
s2.toString()
}
}
Output:101 Raj lucknow
102 Vijay ghaziabad
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break
string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer
class. We will discuss about the StreamTokenizer class in I/O chapter.
Constructors of StringTokenizer class
There are 3 constructors defined in the StringTokenizer class.
Constructor Description
StringTokenizer(String str) creates StringTokenizer with specified string.
StringTokenizer(String str,
creates StringTokenizer with specified string and delimeter.
String delim)
StringTokenizer(String str, creates StringTokenizer with specified string, delimeter and returnValue.
String delim, boolean If return value is true, delimiter characters are considered to be tokens. If
returnValue) it is false, delimiter characters serve to separate tokens.
Methods of StringTokenizer class
The 6 useful methods of StringTokenizer class are as follows:
Public method Description
boolean hasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type is Object.
int countTokens() returns the total number of tokens.
Simple example of StringTokenizer class
Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan" on the basis
of whitespace.
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is
khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output: my
name
is
khan
Example of nextToken(String delim) method of StringTokenizer class
import java.util.*;
public class Test {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,khan");
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
}
}
Output:Next token is : my
StringTokenizer class is deprecated now. It is recommended to use split() method of String class or
regex (Regular Expression).
Java String FAQs or Interview Questions
1) How many objects will be created in the following code?
String s1="javatpoint";
String s2="javatpoint";
Answer: Only one.
2) What is the difference between equals() method and == operator?
The equals() method matches content of the strings whereas == operator matches object or reference of the
strings.
3) Is String class final?
Answer: Yes.
4) How to reverse String in java?
Input:
this is javatpoint
Output:
tnioptavaj si siht
There are many ways to reverse String in Java. We can reverse String using StringBuffer, StringBuilder,
iteration etc. Let's see the ways to reverse String in Java.
i) By StringBuilder / StringBuffer
File: StringFormatter.java
public class StringFormatter {
public static String reverseString(String str){
StringBuilder sb=new StringBuilder(str);
sb.reverse();
return sb.toString();
}
}
File: TestStringFormatter.java
public class TestStringFormatter {
public static void main(String[] args) {
System.out.println(StringFormatter.reverseString("my name is khan"));
System.out.println(StringFormatter.reverseString("I am sonoo jaiswal"));
}
}
Output:
nahk si eman ym
lawsiaj oonos ma I
ii) By Reverse Iteration
File: StringFormatter.java
public class StringFormatter {
public static String reverseString(String str){
char ch[]=str.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
}
File: TestStringFormatter.java
public class TestStringFormatter {
public static void main(String[] args) {
System.out.println(StringFormatter.reverseString("my name is khan"));
System.out.println(StringFormatter.reverseString("I am sonoo jaiswal"));
}
}
Output:
nahk si eman ym
lawsiaj oonos ma I
5) How to check Palindrome String in java?
Input:
nitin
Output:
true
Input:
jatin
Output:
false
We can check palindrome string by reversing string and checking whether it is equal to original string or not.
Let's see the example code to check palindrome string in java.
File: PalindromeChecker.java
public class PalindromeChecker {
public static boolean isPalindrome(String str){
StringBuilder sb=new StringBuilder(str);
sb.reverse();
String rev=sb.toString();
if(str.equals(rev)){
return true;
}else{
return false;
}
}
}
File: TestPalindrome.java
public class TestPalindrome {
public static void main(String[] args) {
System.out.println(PalindromeChecker.isPalindrome("nitin"));
System.out.println(PalindromeChecker.isPalindrome("jatin"));
}
}
Output:
true
false
6) Write a java program to capitalize each word in string?
Input:
this is javatpoint
Output:
This Is Javatpoint
We can capitalize each word of a string by the help of split() and substring() methods. By the help of
split("\\s") method, we can get all words in an array. To get the first character, we can use substring() or
charAt() method.
Let's see the example to capitalize each word in a string.
File: StringFormatter.java
public class StringFormatter {
public static String capitalizeWord(String str){
String words[]=str.split("\\s");
String capitalizeWord="";
for(String w:words){
String first=w.substring(0,1);
String afterfirst=w.substring(1);
capitalizeWord+=first.toUpperCase()+afterfirst+" ";
}
return capitalizeWord.trim();
}
}
File: TestStringFormatter.java
public class TestStringFormatter {
public static void main(String[] args) {
System.out.println(StringFormatter.capitalizeWord("my name is khan"));
System.out.println(StringFormatter.capitalizeWord("I am sonoo jaiswal"));
}
}
Output:
My Name Is Khan
I Am Sonoo Jaiswal
7) Write a java program to reverse each word in string?
Input:
this is javatpoint
Output:
siht si tnioptavaj
We can reverse each word of a string by the help of reverse(), split() and substring() methods. By using
reverse() method of StringBuilder class, we can reverse given string. By the help of split("\\s") method, we
can get all words in an array. To get the first character, we can use substring() or charAt() method.
Let's see the example to reverse each word in a string.
File: StringFormatter.java
public class StringFormatter {
public static String reverseWord(String str){
String words[]=str.split("\\s");
String reverseWord="";
for(String w:words){
StringBuilder sb=new StringBuilder(w);
sb.reverse();
reverseWord+=sb.toString()+" ";
}
return reverseWord.trim();
}
}
File: TestStringFormatter.java
public class TestStringFormatter {
public static void main(String[] args) {
System.out.println(StringFormatter.reverseWord("my name is khan"));
System.out.println(StringFormatter.reverseWord("I am sonoo jaiswal"));
}
}
Output:
ym eman si nahk
I ma oonos lawsiaj
8) Write a java program to tOGGLE each word in string?
Input:
this is javatpoint
Output:
tHIS iS jAVATPOINT
We can tOGGLE each word of a string by the help of split(), toLowerCase(), toUpperCase() and substring()
methods. By the help of split("\\s") method, we can get all words in an array. To get the first character, we
can use substring() or charAt() method.
Let's see the example to tOGGLE each word in a string.
File: StringFormatter.java
public class StringFormatter {
public static String toggle(String str){
String words[]=str.split("\\s");
String toggle="";
for(String w:words){
String first=w.substring(0,1);
String afterfirst=w.substring(1);
toggle+=first.toLowerCase()+afterfirst.toUpperCase()+" ";
}
return toggle.trim();
}
}
File: TestStringFormatter.java
public class TestStringFormatter {
public static void main(String[] args) {
System.out.println(StringFormatter.toggle("my name is khan"));
System.out.println(StringFormatter.toggle("I am sonoo jaiswal"));
}
}
Output:
mY nAME iS kHAN
i aM sONOO jAISWAL
9) Write a java program reverse tOGGLE each word in string?
Input:
this is javatpoint
Output:
sIHT sI tNIOPTAVAJ
We can reverse tOGGLE each word of a string by the help of reverse(), split(), toLowerCase(),
toUpperCase() and substring() methods. By the help of split("\\s") method, we can get all words in an array.
To get the first character, we can use substring() or charAt() method.
Let's see the example to reverse tOGGLE each word in a string.
File: StringFormatter.java
public class StringFormatter {
public static String reverseToggle(String str){
String words[]=str.split("\\s");
String reverseToggle="";
for(String w:words){
StringBuilder sb=new StringBuilder(w);
sb.reverse();
String first=sb.substring(0,1);
String afterfirst=sb.substring(1);
reverseToggle+=first.toLowerCase()+afterfirst.toUpperCase()+" ";
}
return reverseToggle.trim();
}
}
File: TestStringFormatter.java
public class TestStringFormatter {
public static void main(String[] args) {
System.out.println(StringFormatter.reverseToggle("my name is khan"));
System.out.println(StringFormatter.reverseToggle("I am sonoo jaiswal"));
}
}
Output:
yM eMAN sI nAHK
i mA oONOS lAWSIAJ
10) What is the difference between String and StringBuffer in java?
11) What is the difference between StringBuffer and StringBuilder in java?
12) What does intern() method in java?
The java string intern() method returns the interned string. It returns the canonical representation of string.
It can be used to return string from memory, if it is created by new keyword. It creates exact copy of heap
string object in string constant pool.
Signature
The signature of intern method is given below:
public String intern()
Returns
interned string
Java String intern() method example
public class InternExample{
public static void main(String args[]){
String s1=new String("hello");
String s2="hello";
String s3=s1.intern();//returns string from pool, now it will be same as
s2
System.out.println(s1==s2);//false because reference variables are
pointing to different instance
System.out.println(s2==s3);//true because reference variables are pointing
to same instance
}
}
Output:
false
true
Java String intern() Method Example 2
Let's see one more example to understand the string intern concept.
public class InternExample2 {
public static void main(String[] args) {
String s1 = "Javatpoint";
String s2 = s1.intern();
String s3 = new String("Javatpoint");
String s4 = s3.intern();
System.out.println(s1==s2); // True
System.out.println(s1==s3); // False
System.out.println(s1==s4); // True
System.out.println(s2==s3); // False
System.out.println(s2==s4); // True
System.out.println(s3==s4); // False
}
}
true
false
true
false
true
false
13) How to convert String to int in java?
We can convert String to an int in java using Integer.parseInt() method. To convert String into Integer, we
can use Integer.valueOf() method which returns instance of Integer class.
Scenario
It is generally used if we have to perform mathematical operations on the string which contains a number.
Whenever we receive data from TextField or TextArea, entered data is received as a string. If entered data is
in number format, we need to convert the string to an int. To do so, we use Integer.parseInt() method.
Signature
The parseInt() is the static method of Integer class. The signature of parseInt() method is given below:
public static int parseInt(String s)
Java String to int Example: Integer.parseInt()
Let's see the simple code to convert a string to an int in java.
int i=Integer.parseInt("200");
Let's see the simple example of converting String to int in Java.
//Java Program to demonstrate the conversion of String into int
//using Integer.parseInt() method
public class StringToIntExample1{
public static void main(String args[]){
//Declaring String variable
String s="200";
//Converting String into int using Integer.parseInt()
int i=Integer.parseInt(s);
//Printing value of i
System.out.println(i);
}
}
Output:
200
Understanding String Concatenation Operator
//Java Program to understand the working of string concatenation operator
public class StringToIntExample{
public static void main(String args[]){
//Declaring String variable
String s="200";
//Converting String into int using Integer.parseInt()
int i=Integer.parseInt(s);
System.out.println(s+100);//200100, because "200"+100, here + is a string
concatenation operator
System.out.println(i+100);//300, because 200+100, here + is a binary plus
operator
}
}
Output:
200100
300
Java String to Integer Example: Integer.valueOf()
The Integer.valueOf() method converts String into Integer object. Let's see the simple code to convert String
to Integer in Java.
//Java Program to demonstrate the conversion of String into Integer
//using Integer.valueOf() method
public class StringToIntegerExample2{
public static void main(String args[]){
//Declaring a string
String s="200";
//converting String into Integer using Integer.valueOf() method
Integer i=Integer.valueOf(s);
System.out.println(i);
}
}
Output:
300
14) How to convert int to String in java?
We can convert int to String in java using String.valueOf() and Integer.toString() methods. Alternatively,
we can use String.format() method, string concatenation operator etc.
Scenario
It is generally used if we have to display number in textfield because everything is displayed as a string in
form.
String.valueOf()
The String.valueOf() method converts int to String. The valueOf() is the static method of String class. The
signature of valueOf() method is given below:
public static String valueOf(int i)
Java int to String Example using String.valueOf()
Let's see the simple code to convert int to String in java.
int i=10;
String s=String.valueOf(i);//Now it will return "10"
Let's see the simple example of converting String to int in java.
public class IntToStringExample1{
public static void main(String args[]){
int i=200;
String s=String.valueOf(i);
System.out.println(i+100);//300 because + is binary plus operator
System.out.println(s+100);//200100 because + is string concatenation
operator
}
}
Output:
300
200100
2) Integer.toString()
The Integer.toString() method converts int to String. The toString() is the static method of Integer class. The
signature of toString() method is given below:
public static String toString(int i)
Java int to String Example using Integer.toString()
Let's see the simple code to convert int to String in java using Integer.toString() method.
int i=10;
String s=Integer.toString(i);//Now it will return "10"
Let's see the simple example of converting String to int in java.
public class IntToStringExample2{
public static void main(String args[]){
int i=200;
String s=Integer.toString(i);
System.out.println(i+100);//300 because + is binary plus operator
System.out.println(s+100);//200100 because + is string concatenation
operator
}
}
Output:
300
200100
3) String.format()
The String.format() method is used to format given arguments into String. It is introduced since Jdk 1.5.
public static String format(String format, Object... args)
Java int to String Example using String.format()
Let's see the simple code to convert int to String in java using String.format() method.
public class IntToStringExample3{
public static void main(String args[]){
int i=200;
String s=String.format("%d",i);
System.out.println(s);
}
}
Output:
200
15) How to convert String to Date in java?
We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.
To learn this concept well, you should visit DateFormat and SimpleDateFormat classes.
Java String to Date Example
Let's see the simple code to convert String to Date in java.
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateExample1 {
public static void main(String[] args)throws Exception {
String sDate1="31/12/1998";
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);
System.out.println(sDate1+"\t"+date1);
}
}
Output:
31/12/1998 Thu Dec 31 00:00:00 IST 1998
Let's see another code to convert different types of Strings to Date in java. Here, we have used different date
formats using SimpleDateFormat class.
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateExample2 {
public static void main(String[] args)throws Exception {
String sDate1="31/12/1998";
String sDate2 = "31-Dec-1998";
String sDate3 = "12 31, 1998";
String sDate4 = "Thu, Dec 31 1998";
String sDate5 = "Thu, Dec 31 1998 23:37:50";
String sDate6 = "31-Dec-1998 23:37:50";
SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat formatter2=new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat formatter3=new SimpleDateFormat("MM dd, yyyy");
SimpleDateFormat formatter4=new SimpleDateFormat("E, MMM dd yyyy");
SimpleDateFormat formatter5=new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss");
SimpleDateFormat formatter6=new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
Date date1=formatter1.parse(sDate1);
Date date2=formatter2.parse(sDate2);
Date date3=formatter3.parse(sDate3);
Date date4=formatter4.parse(sDate4);
Date date5=formatter5.parse(sDate5);
Date date6=formatter6.parse(sDate6);
System.out.println(sDate1+"\t"+date1);
System.out.println(sDate2+"\t"+date2);
System.out.println(sDate3+"\t"+date3);
System.out.println(sDate4+"\t"+date4);
System.out.println(sDate5+"\t"+date5);
System.out.println(sDate6+"\t"+date6);
}
}
Output:
31/12/1998 Thu Dec 31 00:00:00 IST 1998
31-Dec-1998 Thu Dec 31 00:00:00 IST 1998
12 31, 1998 Thu Dec 31 00:00:00 IST 1998
Thu, Dec 31 1998 Thu Dec 31 00:00:00 IST 1998
Thu, Dec 31 1998 23:37:50 Thu Dec 31 23:37:50 IST 1998
31-Dec-1998 23:37:50 Thu Dec 31 23:37:50 IST 1998
Java Convert Date to String
We can convert Date to String in java using format() method of java.text.DateFormat class.
format() method of DateFormat
The format() method of DateFormat class is used to convert Date into String. DateFormat is an abstract
class. The child class of DateFormat is SimpleDateFormat. It is the implementation of DateFormat class.
The signature of format() method is given below:
String format(Date d)
Java Date to String Example
Let's see the simple code to convert Date to String in java.
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String strDate = dateFormat.format(date);
Example:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class DateToStringExample1 {
public static void main(String args[]){
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String strDate = dateFormat.format(date);
System.out.println("Converted String: " + strDate);
}
}
Output:
Converted String: 2017-24-28 04:24:27
Let's see the full example to convert date and time into String in java using format() method of
java.text.SimpleDateFormat class.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateToStringExample2 {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
System.out.println("Date Format with MM/dd/yyyy : "+strDate);
formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
strDate = formatter.format(date);
System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
strDate = formatter.format(date);
System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDate);
}
}
Output:
Date Format with MM/dd/yyyy : 04/13/2015
Date Format with dd-M-yyyy hh:mm:ss : 13-4-2015 10:59:26
Date Format with dd MMMM yyyy : 13 April 2015
Date Format with dd MMMM yyyy zzzz : 13 April 2015 India Standard Time
Date Format with E, dd MMM yyyy HH:mm:ss z : Mon, 13 Apr 2015 22:59:26 IST
16) How to Optimize Java String Creation?
By using string literals.
Ex:
File: StringPerformance .java
public class StringPerformance {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
String str1 = "India";
String str2= "India";
}
long endTime = System.currentTimeMillis();
System.out.println("Time taken to create literal String : " + (endTime -
startTime) + " ms");
long startTime1 = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
String str1 = new String("India");
String str2 = new String("India");
}
long endTime1 = System.currentTimeMillis();
System.out.println("Time taken to create Object String : " + (endTime1 -
startTime1) + " ms");
}
}
Output:
Time taken to create literal String : 9 ms
Time taken to create Object String : 11 ms
Hence, String creation using literals take less time.
17) Java Program to check whether two Strings are anagram or not
Two strings are called anagrams if they contain same set of characters but in different order.
"keep ? peek", "Mother In Law - Hitler Woman".
File: AnagramString .java
import java.util.Arrays;
public class AnagramString {
static void isAnagram(String str1, String str2) {
String s1 = str1.replaceAll("\\s", "");
String s2 = str2.replaceAll("\\s", "");
boolean status = true;
if (s1.length() != s2.length()) {
status = false;
} else {
char[] ArrayS1 = s1.toLowerCase().toCharArray();
char[] ArrayS2 = s2.toLowerCase().toCharArray();
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
status = Arrays.equals(ArrayS1, ArrayS2);
}
if (status) {
System.out.println(s1 + " and " + s2 + " are anagrams");
} else {
System.out.println(s1 + " and " + s2 + " are not anagrams");
}
}
public static void main(String[] args) {
isAnagram("Keep", "Peek");
isAnagram("Mother In Law", "Hitler Woman");
}
}
Output:
Keep and Peek are anagrams
MotherInLaw and HitlerWoman are anagrams
18) Java program to find the percentage of uppercase, lowercase, digits and special characters in a
String
File: CharacterPercentage .java
import java.text.DecimalFormat;
public class CharacterPercentage {
static void charPercentage(String input) {
int totalChar = input.length();
int upperCase = 0;
int lowerCase = 0;
int digits = 0;
int others = 0;
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (Character.isUpperCase(ch)) {
upperCase++;
}
else if (Character.isLowerCase(ch)) {
lowerCase++;
}
else if (Character.isDigit(ch)) {
digits++;
}
else {
others++;
}
}
double upperCaseLetterPercentage = (upperCase * 100) / totalChar;
double lowerCaseLetterPercentage = (lowerCase * 100) / totalChar;
double digitsPercentage = (digits * 100) / totalChar;
double otherCharPercentage = (others * 100) / totalChar;
DecimalFormat format = new DecimalFormat("##.##");
System.out.println("In '" + input + "' : ");
System.out.println("Uppercase letters" +
format.format(upperCaseLetterPercentage) + "% ");
System.out.println("Lowercase letters" +
format.format(lowerCaseLetterPercentage) + "%");
System.out.println("Digits Are " + format.format(digitsPercentage) + "%");
System.out.println("Other Characters Are " +
format.format(otherCharPercentage) + "%");
}
public static void main(String[] args) {
charPercentage("India is my country 100%");
}
}
Output:
In 'India is my country 100%' :
Uppercase letters are 4%
Lowercase letters are 62%
Digits Are 12%
Other Characters Are 20%
19) How to convert String to Integer and Integer to String in Java
Following is the program to demonstrate it.
File: ConvertStringToInteger.java
public class ConvertStringToInteger {
public static void main(String[] args) {
String str1 = "5"; //1st way
int result = Integer.parseInt(str1); // Using Integer.parsrInt()
System.out.println(result);
String str2 = "5"; //2nd way
Integer result2 = Integer.valueOf(str2); // Using Integer.valueOf()
System.out.println(result2);
}
}
Output:
5
5
File: ConvertIntegerToString.java
public class ConvertIntegerToString{
public static void main(String[] args) {
int x = 5;
//1st way
String str = Integer.toString(x); // using Integer.toString()
System.out.println(str);
//2nd way
String str2 = String.valueOf(x); // using String.valueOf()
System.out.println(str2);
}
}
Output:
5
5
20) Java Program to find duplicate characters in a String
Following program demonstrate it.
File: DuplicateCharFinder .java
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class DuplicateCharFinder {
public void findIt(String str) {
Map<Character, Integer> baseMap = new HashMap<Character, Integer>();
char[] charArray = str.toCharArray();
for (Character ch : charArray) {
if (baseMap.containsKey(ch)) {
baseMap.put(ch, baseMap.get(ch) + 1);
} else {
baseMap.put(ch, 1);
}
}
Set<Character> keys = baseMap.keySet();
for (Character ch : keys) {
if (baseMap.get(ch) > 1) {
System.out.println(ch + " is " + baseMap.get(ch) + " times");
}
}
}
public static void main(String a[]) {
DuplicateCharFinder dcf = new DuplicateCharFinder();
dcf.findIt("India is my country");
}
}
Output:
is 3 times
i is 2 times
n is 2 times
y is 2 times
21) Java Program to prove that strings are immutable in java
File: ProveStringImmutable .java
public class ProveStringImmutable {
public static void referenceCheck(Object x, Object y) {
if (x == y) {
System.out.println("Both pointing to the same reference");
} else {
System.out.println("Both are pointing to different reference");
}
}
public static void main(String[] args) {
String st1 = "Java";
String st2 = "Java";
System.out.println("Before Modification in st1");
referenceCheck(st1, st2);
st1 += "ava";
System.out.println("After Modification");
referenceCheck(st1, st2);
}
}
Output:
Before Modification in st1
Both pointing to the same reference
After Modification
Both are pointing to different reference
22) Java Program to remove all white spaces from a String
File: RemoveAllSpace .java
public class RemoveAllSpace {
public static void main(String[] args) {
String str = "India Is My Country";
//1st way
String noSpaceStr = str.replaceAll("\\s", ""); // using built in method
System.out.println(noSpaceStr);
//2nd way
char[] strArray = str.toCharArray();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < strArray.length; i++) {
if ((strArray[i] != ' ') && (strArray[i] != '\t')) {
stringBuffer.append(strArray[i]);
}
}
String noSpaceStr2 = stringBuffer.toString();
System.out.println(noSpaceStr2);
}
}
Output:
IndiaIsMyCountry
IndiaIsMyCountry
23) Java Program to check whether one String is a rotation of another
File: RotationString .java
public class RotationString {
public static boolean checkRotation(String st1, String st2) {
if (st1.length() != st2.length()) {
return false;
}
String st3 = st1 + st1;
if (st3.contains(st2))
return true;
else
return false;
}
public static void main(String[] args) {
String str1 = "avajava";
String str2 = "javaava";
System.out.println("Checking if a string is rotation of another");
if (checkRotation(str1, str2)) {
System.out.println("Yes " + str2 + " is rotation of " + str1);
} else {
System.out.println("No " + str2 + " is not rotation of " + str1);
}
}
}
Output:
Checking if a string is rotation of another
Yes javaava is rotation of avajavaw
24) Java Program to count the number of words in a String
File: WordCount .java
public class WordCount {
static int wordcount(String string)
{
int count=0;
char ch[]= new char[string.length()];
for(int i=0;i<string.length();i++)
{
ch[i]= string.charAt(i);
if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!='
')&&(i==0)) )
count++;
}
return count;
}
public static void main(String[] args) {
String string =" India Is My Country";
System.out.println(wordcount(string) + " words.");
}
}
Output:
4 words.
25) Java Program to reverse a given String with preserving the position of space
File: RemoveChar .java
public class ReverseStringPreserveSpace {
static void reverseString(String input) {
char[] inputArray = input.toCharArray();
char[] result = new char[inputArray.length];
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] == ' ') {
result[i] = ' ';
}
}
int j = result.length - 1;
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] != ' ') {
if (result[j] == ' ') {
j--;
}
result[j] = inputArray[i];
j--;
}
}
System.out.println(input + " --> " + String.valueOf(result));
}
public static void main(String[] args) {
reverseString("India Is my country");
}
}
Output:
India Is my country --> yrtnu oc ym sIaidnI
26) How to swap two String variables without third variable
File: SwapWithoutTemp .java
public class SwapWithoutTemp {
public static void main(String args[]) {
String a = "Love";
String b = "You";
System.out.println("Before swap: " + a + " " + b);
a = a + b;
b = a.substring(0, a.length() - b.length());
a = a.substring(b.length());
System.out.println("After : " + a + " " + b);
}
}
Output:
Before swap: Love You
After : You Love
27) How to remove a particular character from a String
File: RemoveChar .java
public class RemoveChar {
public static void main(String[] args) {
String str = "India is my country";
System.out.println(charRemoveAt(str, 7));
}
public static String charRemoveAt(String str, int p) {
return str.substring(0, p) + str.substring(p + 1);
}
}
Output:
India i my country