module1 String handling-AJ-BIS402
module1 String handling-AJ-BIS402
Strings in java
String class constructors
-- To create and initialize string objects based on the various types of arguments.
String(): default constructor used to create an empty string
Syntax: String s = new String();
It will create a string object in the heap area with no value.
String(String str): to create a string initialized by an array of characters
Syntax : String st = new String(String str);
Example:
String s2 = new String("Hello Java");
String(char chs[ ])
--Creates a string object and stores the array of characters in it.
Syntax:
String str = new String(char ch[])
Example:
char ch [] = { 'a', 'b', 'c', 'd' };
String s3 = new String(ch);
String(String Stringobj)
-- Create a string object that contains the same characters sequence as another string object.
char chars[] = { 'F', 'A', 'N' };
String s1 = new String(chars);
// Driver Class
class C_ARRAY { G
// main function O
public static void main(String args[]) G
{ R
String s = "GOGREEN"; E
char[] gfg = s.toCharArray(); E
N
for (int i = 0; i < gfg.length; i++) {
System.out.println(gfg[i]);
}
}
}
Example
Example
System.out.println(str.substring(0, index)+"F"+str.substring(index+1));
lastIndexOf(int
ch) str = "012301230123";
String lastIndexOf(String
str.lastIndexOf('0') str)
8 String str = "Hello Jello Trello";
str.lastIndexOf(48)
8 str.lastIndexOf("llo")
str.lastIndexOf('a') 15
-1
lastIndexOf(int ch, int fromIndex) str.lastIndexOf("Jello")
String str = "Hello World"; 6
str.lastIndexOf('l', 7)
3 str.lastIndexOf("123")
str.lastIndexOf('l', 50) -1
9
str.lastIndexOf('l', -5)
-1
str.lastIndexOf('l', 1)
-1
String Str = new String("Welcome to green
palace"); Output
Green palace
System.out.print("The extracted substring green
is : ");
System.out.println(Str.substring(10));
System.out.println(Str.substring(10,16));
class ValueOfExa {
public static void main(String arg[])
{
int iNum = 30;
System.out.println(sample); 30
3091
// concatenating string with iNum
System.out.println(sample + s); 4.56789
914.56789
// Returns the string representation of the float
// fnum.
sample = String.valueOf(fNum);
System.out.println(sample);
class A {
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
} }
Character
Example
Output
a=42!
StringBuffer is synchronized, meaning its methods are thread-safe and can be
safely used in a multithreaded environment.
StringBuilder is not synchronized, which makes it faster than StringBuffer, but it is
not thread-safe and should not be used in a multithreaded environment.
End of the I Module
Queries
???...