Program to show use of some of 'String' class methods

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are immutable. Strings are constant; their values cannot be changed after they are created. For example:
String str = "abc";    // Creates a string literal
OR
String str = new String("abc");

In this program we have used the following methods of String class:
  • length( ) : It returns the length of this string.
  • replace(CharSequence target, CharSequence replacement) : It replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. :
  • concat(String str) : It concatenates the specified string to the end of this string.


PROGRAM
public class UsingStringMethods {

 public static void main(String[] args) {

  int n;
     String s = "Java programming", t = "", u = "";
  
     System.out.println(s);
  
     // Find length of string
  
     n = s.length();
     System.out.println("Lenght of String = " + n);
  
     // Replace characters in string
  
     t = s.replace("Java", "C++");
     System.out.println("Before replacing 'Java' by 'C++':" + s);
     System.out.println("After replacing 'Java' by 'C++':" + t);
  
     // Concatenating string with another string
  
     u = s.concat(" is fun");
     System.out.println("Before concate : " + s);
     System.out.println("After concate : " + u);
 }
}
OUTPUT
C:\>javac UsingStringMethods.java
C:\>java UsingStringMethods
Java programming
Lenght of String = 16
Before replacing 'Java' by 'C++':Java programming
After replacing 'Java' by 'C++':C++ programming
Before concate : Java programming
After concate : Java programming is fun

Comments

  1. If you really desire to get such type of information, visit this blog quickly.
    tops sites people look for agents

    ReplyDelete
  2. Your contents are too straightforward to browse and easy to understand.
    UI design firm

    ReplyDelete
  3. Continue the good work; keep posting more n more n more.
    design firms

    ReplyDelete

Post a Comment

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Program to input age from user and throw user-defined exception if entered age is negative

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.