Java Technology - 2018 - String
String is basically an object that represents sequence of char values. An array of characters works same as java string.
char[] ch = {'m','a','n'};
String str = new String(ch);
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

The CharSequence interface is used to represent sequence of characters

The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new instance is created. For mutable string, you can use StringBuffer and StringBuilder classes.
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 string object.
How to create String object?
There are two ways to create String object:
String str = "everest";
ava String literal is created by using double quotes. For Example:
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 string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//will not create new instance
String objects are stored in a special memory area known as string constant pool.Why java uses concept of string literal?To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).String str = new String("everest"); ////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 "everest" will be placed in the string constant pool. The variable str will refer to the object in heap(non pool). package com.practice; public class StringPractice { public static void main(String[] args) { char[] ch = { 'm', 'a', 'n', 'd', 'i', 'p' }; String str = new String(ch); System.out.println(str); char ch1 = str.charAt(1); System.out.println(ch1); System.out.println(str.length()); String name = "sonoo"; String sf1 = String.format("name is %s", name); String sf2 = String.format("value is %f", 32.33434); String sf3 = String.format("value is %45.12f", 32.33434);// returns 12 // char // fractional // part // filling // with 0 System.out.println(sf1); System.out.println(sf2); System.out.println(sf3); System.out.println(str.substring(3, 6));// dip System.out.println(str.substring(2));// ndip System.out.println(str.subSequence(3, 6));// and //same as substring, // there is some difference System.out.println(str.contains("man"));// true System.out.println(String.join("", "a", "b"));// ab String name1 = String.join(" ", "mandip", "Shrestha"); // mandip // Shrestha System.out.println(name1); String joinString1 = String.join("-", "welcome", "to", "javatpoint"); // welcome-to-javatpoint System.out.println(joinString1); System.out.println("mandip".equals("man")); // false System.out.println("mandip".equals("Mandip")); // false System.out.println("".isEmpty());// true System.out.println(str.concat(" Shrestha")); // mandip Shrestha System.out.println("I go to School".replace("go", "went")); // I went to // school System.out.println("I go sto School".replace("s", "W"));// I go Wto // School System.out.println("mandip".equalsIgnoreCase("MANdip"));// true String[] splitedWord = "mandip shrestha nepal".split("\\s"); // based on // WhiteSpace for (String ii : splitedWord) { System.out.println(ii); } System.out.println(str.indexOf('d')); // 2 System.out.println("Mandip".toLowerCase());// mandip System.out.println(" Mandip Shrestha a".trim());// Mandip Shrestha a // //eliminates // leading and // trailing spaces. int value=30; String s1=String.valueOf(value); System.out.println(s1+10);//concatenating string with 10 } } 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. Why string objects are immutable in java?
public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
}}
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
}
}
class TestStringConcatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
}
}
After a string literal, all the + will be treated as string concatenation operator.
Example of java substring
public class TestSubstring{
public static void main(String args[]){
String s="SachinTendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}
Test it Now
Tendulkar
Sachin
The java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can perform operations on string such as trimming, concatenating, converting, comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a string if you submit any form in window based, web based or mobile application.
Let's see the important methods of String class.
Java String toUpperCase() and toLowerCase() method
The java string toUpperCase() method converts this string into uppercase letter and string toLowerCase() method into lowercase letter.
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
Test it Now
SACHIN
sachin
Sachin
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
Test it Now
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
Test it Now
true
true
Java String charAt() method
The string charAt() method returns a character at specified index.
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
Test it Now
S
h
Java String length() method
The string length() method returns length of the string.
String s="Sachin";
System.out.println(s.length());//6
Test it Now
6
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
Test it Now
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.
Java StringBuffer class
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.
Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order.
Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str) creates a string buffer with the specified string.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.
StringBuffer and StringBuilder classes are used for creating mutable string.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
//if sb was just a String, then it was immutable.
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
The replace() method replaces the given string from the specified beginIndex and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
The reverse() method of StringBuilder class reverses the current string.
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Java StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.
Constructor Description
StringBuilder() creates an empty string Builder with the initial capacity of 16.
StringBuilder(String str) creates a string Builder with the specified string.
StringBuilder(int length) creates an empty string Builder with the specified capacity as length.
Difference between StringBuffer and StringBuilder
No. StringBuffer StringBuilder
1) StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
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() methodBy 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 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.
Main difference between .equals() method and == operator is that one is method and other is operator.
We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
If a class does not override the equals method, then by default it uses equals(Object o) method of the closest parent class that has overridden this method. See this for detail
Coding Example:
// Java program to understand
// the concept of == operator
public class Test {
public static void main(String[] args)
{
String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2); //False
System.out.println(s1.equals(s2)); //True
}
}
Yes,
StringBuilder does not override Object's .equals() function , which means the two object references are not the same and the result is false.
For
StringBuilder , you could use s1.toString().equals(s2.toString()) |
String s11 = new String("Mandip");
String s12 = new String("Mandip");
System.out.println(s11 == s12); // false
System.out.println(s11.equals(s12)); // true
String s111 = "Mandip";
String s122 = "Mandip";
System.out.println(s111 == s122); // true
System.out.println(s111.equals(s122)); // true
StringBuffer sb1 = new StringBuffer("Mandip");
StringBuffer sb2 = new StringBuffer("Mandip");
System.out.println(sb1 == sb2); // false
System.out.println(sb1.equals(sb2)); // false
StringBuilder sb11 = new StringBuilder("Mandip");
StringBuilder sb22 = new StringBuilder("Mandip");
System.out.println(sb11 == sb22); // false
System.out.println(sb11.equals(sb22)); // false
System.out.println("-------------");
StringBuilder s1a = new StringBuilder("Test");
StringBuilder s2b = new StringBuilder("Test");
System.out.println(s1a);
System.out.println(s2b);
System.out.println(s1a == s2b); // false
System.out.println(s1a.equals(s2b)); // false
System.out.println(s1a.toString() == s2b.toString()); // false
System.out.println(s1a.toString().equals(s2b.toString()));//true
As you apparently already know,
StringBuilder
inherits equals()
from java.lang.Object
, and as such StringBuilder.equals()
returns true only when passed the same object as an argument. It does not compare the contents of two StringBuilder
s!3) Is String class final?
Answer: Yes.
4) How to reverse String in java?
Input:
this is javatpoint
Output:
tnioptavaj si siht
StringBuilder sb=new StringBuilder(str);
sb.reverse();
Or, StringBuffer
How to check Palindrome String in java?
Input:
nitin
Output:
true
//Using StringBuilder/StringBuffer reverse() operation.
Comments
Post a Comment