Friday, 25 November 2016

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


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.

public class UsingStringMethods {

 public static void main(String[] args) {

  int n;
     String s = "Java programming", t = "", u = "";
     // 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);
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

1 comment:

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