Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
What is a Java String?
In Java, a string is an object that represents a sequence of characters or char values. The java.lang.String class is used to create a Java string object.
There are two ways to create a String object:
🔥𝐄𝐝𝐮𝐫𝐞𝐤𝐚 𝐉𝐚𝐯𝐚 𝐂𝐨𝐮𝐫𝐬𝐞 𝐓𝐫𝐚𝐢𝐧𝐢𝐧𝐠: https://www.edureka.co/java-j2ee-training-course (Use code “𝐘𝐎𝐔𝐓𝐔𝐁𝐄𝟐𝟎”)
This Edureka Java Full Course will help you understand the various fundamentals of Java programm…
Now, let us understand the concept of Java String pool.
Java String Pool: Java String pool refers to collection of Strings which are stored in heap memory. In this, whenever a new object is created, String pool first checks whether the object is already present in the pool or not. If it is present, then same reference is returned to the variable else new object will be created in the String pool and the respective reference will be returned. Refer to the diagrammatic representation for better understanding:
In the above image, two Strings are created using literal i.e “Apple” and “Mango”. Now, when third String is created with the value “Apple”, instead of creating a new object, the already present object reference is returned. That’s the reason Java String pool came into the picture.
Before we go ahead, One key point I would like to add that unlike other data types in Java, Strings are immutable. By immutable, we mean that Strings are constant, their values cannot be changed after they are created. Because String objects are immutable, they can be shared. For example:
String str =”abc”;
is equivalent to:
char data[] = {‘a’, ‘b’, ‘c’};
String str = new String(data);
Let us now look at some of the inbuilt methods in String class.
public class Example{ public static void main(String args[]{ String s1="hello"; String s2="whatsup"; System.out.println("string length is: "+s1.length()); System.out.println("string length is: "+s2.length()); }}
Here, String length() function will return the length 5 for s1 and 7 for s2 respectively.
public class CompareToExample{ public static void main(String args[]){ String s1="hello"; String s2="hello"; String s3="hemlo"; String s4="flag"; System.out.println(s1.compareTo(s2)); // 0 because both are equal System.out.println(s1.compareTo(s3)); //-1 because "l" is only one time lower than "m" System.out.println(s1.compareTo(s4)); // 2 because "h" is 2 times greater than "f" }}
This program shows the comparison between the various string. It is noticed that
if s1 > s2, it returns a positive number
if s1 < s2, it returns a negative number
if s1 == s2, it returns 0
public class ConcatExample{ public static void main(String args[]){ String s1="hello"; s1=s1.concat("how are you"); System.out.println(s1); }}
The above code returns “hellohow are you”.
public class IsEmptyExample{ public static void main(String args[]){ String s1=""; String s2="hello"; System.out.println(s1.isEmpty()); // true System.out.println(s2.isEmpty()); // false }}
public class StringTrimExample{ public static void main(String args[]){ String s1=" hello "; System.out.println(s1+"how are you"); // without trim() System.out.println(s1.trim()+"how are you"); // with trim() }}
In the above code, the first print statement will print “hello how are you” while the second statement will print “hellohow are you” using the trim() function.
public class StringLowerExample{ public static void main(String args[]){ String s1="HELLO HOW Are You?”; String s1lower=s1.toLowerCase(); System.out.println(s1lower);} }
The above code will return “hello how are you”.
public class StringUpperExample{ public static void main(String args[]){ String s1="hello how are you"; String s1upper=s1.toUpperCase(); System.out.println(s1upper); }}
The above code will return “HELLO HOW ARE YOU”.
Let’s understand this with a programmatic example:
public class StringValueOfExample{ public static void main(String args[]){ int value=20; String s1=String.valueOf(value); System.out.println(s1+17); //concatenating string with 10 }}
In the above code, it concatenates the Java String and gives the output – 2017.
Java String replace(): The Java String replace() method returns a string, replacing all the old characters or CharSequence to new characters. There are 2 ways to replace methods in a Java String.
public class ReplaceExample1{ public static void main(String args[]){ String s1="hello how are you"; String replaceString=s1.replace('h','t'); System.out.println(replaceString); }}
In the above code, it will replace all the occurrences of ‘h’ to ‘t’. Output to the above code will be “tello tow are you”. Let’s see the another type of using replace method in java string:
Java String replace(CharSequence target, CharSequence replacement) method :
public class ReplaceExample2{ public static void main(String args[]){ String s1="Hey, welcome to Edureka"; String replaceString=s1.replace("Edureka","Brainforce"); System.out.println(replaceString); }}
In the above code, it will replace all occurrences of “Edureka” to “Brainforce”. Therefore, the output would be “ Hey, welcome to Brainforce”.
class ContainsExample{ public static void main(String args[]){ String name=" hello how are you doing"; System.out.println(name.contains("how are you")); // returns true System.out.println(name.contains("hello")); // returns true System.out.println(name.contains("fine")); // returns false }}
In the above code, the first two statements will return true as it matches the String whereas the second print statement will return false because the characters are not present in the string.
public class EqualsExample{ public static void main(String args[]){ String s1="hello"; String s2="hello"; String s3="hi"; System.out.println(s1.equalsIgnoreCase(s2)); // returns true System.out.println(s1.equalsIgnoreCase(s3)); // returns false } }
public class EqualsIgnoreCaseExample{ public static void main(String args[]){ String s1="hello"; String s2="HELLO"; String s3="hi"; System.out.println(s1.equalsIgnoreCase(s2)); // returns true System.out.println(s1.equalsIgnoreCase(s3)); // returns false }}
In the above code, the first statement will return true because the content is same irrespective of the case. Then, in the second print statement will return false as the content doesn’t match in the respective strings.
StringToCharArrayExample{ public static void main(String args[]){ String s1="Welcome to Edureka"; char[] ch=s1.toCharArray(); for(int i=0;i<ch.length;i++){ System.out.print(ch[i]); }}}
The above code will return “Welcome to Edureka”.
public class StringGetBytesExample { public static void main(String args[]){ String s1="ABC"; byte[] b=s1.getBytes(); for(int i=0;i<b.length;i++){ System.out.println(b[i]); } }}
In the above code, it will return the value 65,66,67.
public class IsEmptyExample{ public static void main(String args[]) { String s1=""; String s2="hello"; System.out.prinltn(s1.isEmpty()); // returns true System.out.prinltn(s2.isEmpty()); // returns false }}
In the above code, the first print statement will return true as it does not contain anything while the second print statement will return false.
public class EndsWithExample{ public static void main(String args[]) { String s1="hello how are you”; System.out.println(s1.endsWith("u")); // returns true System.out.println(s1.endsWith("you")); // returns true System.out.println(s1.endsWith("how")); // returns false }}
This is not the end. There are more Java String methods that will help you make your code simpler.
Moving on, Java String class implements three interfaces, namely – Serializable, Comparable and CharSequence.
Since, Java String is immutable and final, so a new String is created whenever we do String manipulation. As String manipulations are resource consuming, Java provides two utility classes: StringBuffer and StringBuilder.
Let us understand the difference between these two utility classes:
I hope you guys are clear with Java String, how they are created, their different methods and interfaces. I would recommend you to try all the examples. Do read my next blog on Java Interview Questions which will help you set apart in the interview process. If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.
Now that you have understood basics of Java, check out the Java Online Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this blog and we will get back to you.
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 21st December,2024 21st December SAT&SUN (Weekend Batch) | View Details |
Java Course Online | Class Starts on 1st March,2025 1st March SAT&SUN (Weekend Batch) | View Details |
edureka.co
This is wrong information. Please correct it.
( Corrections are in bold letters)
By new keyword : Java String is created by using a keyword “new”.
For example: String s=new String(“Welcome”);
It creates two objects (
in String pool andin heap) and one reference variable where the variable ‘s’ will refer to the object in the heap.Please refer to Java 8 reference books, There are changes in version of java 8.
Hello,
Nice Blog,
But please change the image where you are comparing two string using ==
there you should modify the last image as s1 == s3
Sandeep Patidar