Strings in java :
● String in java is a class which is present in java.lang package.
● String is defined as Sequence of characters.
/* Strings in java are immutable
that means the String once defined can't be modified , if we want
any modification we need to use other String
*/
class Strings
{
public static void main(String[] args)
{
String name1 = "Ram"; // initialisation using literals
String name2 = new String("Ram"); // Initialisation with new
keyword
String fullName = name1 + " " + name2;
System.out.println("Full Name : "+fullName);
// length() function returns length of string
System.out.println("Length of full name : "+fullName.length());
// length of string
// chaeAt(index) function returns character present at specific
index
System.out.println("CHaracter at index 4 in full_name :
"+fullName.charAt(4));
/* CompareTo() function compares one string to another ,
returns 0 if both equal
return +ve value if str1 > str2
returns -ve value if str1 < str2
*/
if(name1.compareTo(name2)==0)
{
System.out.println(name1 +" is equals to "+name2);
}
// substring(starting index,ending index) functiion returns the
characters between given indexes
System.out.println("Substring in given String :
"+fullName.substring(0, 3));
/* isEmpty() function used to check that the String is empty
or not
if string is empty ist returns true , if string is not
empty it returns false
*/
if(name1.isEmpty()==false)
{
System.out.println("String is not empty");
}
// toUppercase() & toLowercase() fuctions used to convert the
given string in uppercase & lowercase
System.out.println("Uppercase : "+fullName.toUpperCase());
System.out.println("Lowercase : "+fullName.toLowerCase());
// trim() function erases whitespace from left & right side of
string
System.out.println("Trim : "+fullName.trim());
}
Output : -
Full Name : Ram Ram
Length of full name : 7
CHaracter at index 4 in full_name : R
Ram is equals to Ram
Substring in given String : Ram
String is not empty
Uppercase : RAM RAM
Lowercase : ram ram
Trim : Ram Ram