Strings in Java
Strings in Java
Strings in Java are Objects that are backed internally by a char array.
Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created
Syntax:
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:-
String str = "hii";
Memory allotment of String:-
Whenever a String Object is created, two objects will be created- one in the Heap Area and one in the String constant pool and the String object reference always points to heap area object.
Example:-
String str = "hii";
Example:-
// Java code to illustrate String
import java.io.*;
import java.lang.*;
class Test {
public static void main(String[] args)
{
// Declare String without using new operator
String s = "welcome";
// Prints the String.
System.out.println("String s = " + s);
// Declare String using new operator
String s1 = new String("welcome");
// Prints the String.
System.out.println("String s1 = " + s1);
}
}
Output:
String s = welcome
String s1 = welcome
Interfaces and Classes in Strings in Java
Char Buffer:This class implements the Char Sequence interface. This class is used to allow character buffers to be used in place of Char Sequences. An example of such usage is the regular-expression package java.util.regex.
String:String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once create
Creating a String (There are two ways to create string in Java)
String literal:- String s = “welcome ”;
Using new keyword:- String s = new String (“welcome”);
String obj=new String(“”);
String s=”Hii”;
String str =new String(“Welcome”);
Method in String class
Length -str.length()- length & String
INDEXof - indexof(str) -indexvalue & first char in string
CHARAT - str.charAt(index)-char at given index
Replace-str.replace(old string,new string)
To lower case- str.toLowerCase()
Upper case -str.toUpperCase()
Compareto str.comparezto(str) “ hiii “
str. trim()
str.concat(str)
Comments
Post a Comment