Write A Java Program To Demonstrate Use Of String Class Methods

0

Write A Java Program To Demonstrate Use Of string Class Methods

: chatat(), contains(), format(), length(), split()

Write A Java Program To Demonstrate Use Of string Class Methods : chatat(), contains(), format(), length(), split()

In this, we will create a java program which show the use of chatat(), contains(), format(), length(), split() methods of string.


Here's a program in java that defines a string and show the use of its different methods.


Program

public class StringDemo {
    public static void main(String[] args) {
        // Using charAt() method
        String str1 = "Hello World";
        char ch = str1.charAt(6);
        System.out.println("Character at index 6 in string " + str1 + " is: " + ch);

        // Using contains() method
        String str2 = "Java is a programming language";
        boolean result = str2.contains("programming");
        System.out.println("Does string " + str2 + " contain the word 'programming'? " + result);

        // Using format() method
        String str3 = "Harsh";
        int age = 18;
        float height = 5.7f;
        String formattedString = String.format("My name is %s, I am %d years old, and I am %f feet tall.", str3, age, height);
        System.out.println(formattedString);

        // Using length() method
        String str4 = "This is a test string";
        int length = str4.length();
        System.out.println("Length of string " + str4 + " is: " + length);

        // Using split() method
        String str5 = "The quick brown fox jumps over the lazy dog";
        String[] words = str5.split(" ");
        System.out.println("Words in string " + str5 + " are:");
        for (String word : words) {
            System.out.println(word);
        }
    }
}

Output
Character at index 6 in string Hello World is: W Does string Java is a programming language contain the word 'programming'? true My name is Harsh, I am 18 years old, and I am 5.700000 feet tall. Length of string This is a test string is: 21 Words in string Java Is Programming Language are: Java Is Programming Language

Explanation
In this program, we use the string class methods charat(), contains(), format(), length(), and split().

The charat() method is used to get the character at a specific index in a string.
The contains() method is used to check if a string contains a specific substring.
The format() method is used to create a formatted string using placeholders and arguments.
The length() method is used to get the length of a string.
The split() method is used to split a string into an array of substrings based on a delimiter.

❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In Java Programming.

Tags

Post a Comment

0Comments
Post a Comment (0)