Practical-31
Write a Java Program to implement the methods of String Class.
Introduction
This Java Program implements the methods of the String class. A string is an array of characters stored in memory. There are multiple methods in the string class such as strings to numbers and vice vers[BC[BCA, Cyber Security]yber Security]onverting strings to upper and lower case, comparing strings, and many other methods for manipulating strings. This program also covers the various utility methods associated with the string class such as manipulating whitespace, trimming strings, and re-arranging words. Generally speaking, strings can be thought of as a powerful and versatile tool for handling character data.
Code
public class StringMethods {
public static void main(String[] args)
{
String str1 = "Hello World!";
String str2 = "Hey everyone";
// Check if string contains a certain substring
boolean result = str1.contains("World");
System.out.println("String contains World :" + result);
// Concatenates two strings and returns the result
String str3 = str1.concat(str2);
System.out.println("Concatenated string: "+ str3);
// Returns the substring before the specified index
String result1 = str1.substring(4);
System.out.println("Substring = " + result1);
// Compare two strings lexicographically
int result2 = str2.compareTo(str1);
System.out.println("str2 and str1 comparison: "+ result2);
// Replace thecharacter with a new one
String str4 = str1.replace('l', 'd');
System.out.println("String after replacement = " + str4);
}
}
Output
String contains World :true
Concatenated string: Hello World!Hey everyone
Substring = lo World!
str2 and str1 comparison: -5
String after replacement = Heddo Word!
This Java Program implements the methods of the String class. It contains various utility methods such as checking for a certain substring within a string, concatenating two strings, extracting a substring prior to an index, comparing two strings lexicographically, and replacing a character with a new one.