String class in Java with Example
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created.
String buffers support mutable strings. 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);
Here are some more examples of how strings can be used:
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);
- -string is an array of collections.
- -a collection of characters.
- -sequence of characters.
- -string handling is a sequence of characters.
- -the array is only one way to put the character in the sequence.
- -java represents a string in a form of an object.
- -in string handling six classes use
- new always create new memory allocation
Packages :
- java.lang.string
- java.lang.StringBuffer
- java.lang.StringBuilder
- java.io.stringreader
- java.io.stringwriter
- java.util.StringTokenizer
Example: Creating a String Object
1) String s=new String("hello"); //hello - save inside string constant pool and create object in heap memory .
sop(s.length()); //output 5 bacause five char in hello word
2) String s="hello";//string leatral
sop(s.length());//output 5 five char in hello word
Whenever you want to share the string class object then always create the string class lateral:
string s1="hello";
string s1"heloo "; // leatral
When you want to create the new object of the string class then always create the string class object via a new operator :
string s1=new string ("new ")// it can not be shared .
public class StringExample1 {
public static void main(String... s) {
String s1 = "hello";
String s2 = new String("hello");
String s3 = new String("hello");
String s4 = "hello";
if (s1 == s4) {
System.out.println("both references point to the same string object");
}
if (s2 == s3)// false
{
System.out.println("same");
// creating object lateral all string lateral are store in a
//special memory area
// Called string constant pool.
} else {
System.out.println("not same");
}
}
}
Output :
both references point to the same string object
not same
Comments
Post a Comment