String in Java with example
For Video Tutorial: Move on Youtube Channel
Note: Select the playlist as per your need & move with number sequence.
Video for this tutorial : CLICK HERE
Strings are a sequence of characters, but in Java, Strings are objects. A Java string is a sequence of characters that exist as an object of the class java.lang.String.
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.
String Example: Below example has most types of string creation methods:
public class csc_string1 {
public static void main(String args[]) {
String s1 = "chandan";
String s2 = "chandan";
String s3 = new String("chandan");
String s4 = new String("chandan");
String s5 = new String(s1);
char arr[] = {'h','e','l','1','0','w', 'o','r', 'l', 'd'};
String s6 = new String(arr);
String s7 = new String(arr, 0, 4);
System.out.println(s1==s2);
System.out.println(s3==s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7);
int x = s3.length();
System.out.println(x);
}
}
Output :
true
false
chandan
hel10world
hel1
7
String In Java : String is a sequence of characters & in java, string is an object that represents a sequence of characters. Or STRING is a character array.
Now the question comes: why is a Java string immutable?
Answer : Immutable means unmodified or unchangeable. Better understood by example:
public static void main(String args[]) {
String a = "chandan";
a.concat("singh"); // concat() method appends the string at the end
System.out.println(a);
}
}
Output : chandan
How to create a string object?
There are two ways to create a String object:
1) By string literal: String a = "welcome at iamchandan.com";
2) By new keyword: String a = new String("welcome at iamchandan.com");
String Builder and String Buffer in JAVA
public static void main(String args[]) {
String str = String.join("--", "Chandan", "Singh");
System.out.println(str);
StringBuffer sbf = new StringBuffer("way2testing");
sbf.append(".com");
System.out.println(sbf);
StringBuilder sbd = new StringBuilder("Software testing");
sbd.append("way2testing");
System.out.println(sbd);
}
}
| StringBuffer | StringBuilder |
|---|---|
| String buffer is synchronized i.e. thread safe. | StringBuilder is non-synchronized i.e. not thread safe. |
| Less efficient than string builder. | More efficient than stringbuffer. |
No comments:
Post a Comment