Page 78 - CTS - CSA TP - Volume 2
P. 78

COMPUTER SOFTWARE APPLICATION - CITS



           EXERCISE 92 : Use the JAVA string class methods


            Objectives

           At the end of this exercise you shall be able to
           •    know more about  the use of string class methods in Java
           •    develop Java programs using string class methods.

           Requirements


              Tools/Materials
              •  PC/Laptop  with Windows OS
              •  JDK Software
              •  Text editor (Visual studio / Sublime / Note pad)



           Procedure


           The String class in Java provides numerous methods for working with strings. Here are a few examples
           demonstrating the use of some common methods of the String class:

           TASK 1: Concatenate Strings
           //Concatenate Strings
            public class StringExample1 {
               public static void main(String[] args) {

                   String str1 = “Hello”;
                   String str2 = “World”;
                   System.out.println(“ String 1: “ + str1);
                   System.out.println(“ String 2: “ + str2);
                   // Concatenation using the concat() method
           String result = str1.concat(“ “ + str2);

                   System.out.println(“Concatenated String: “ + result);
               }
           }
           Explanation:

              •  In Java, string concatenation is the process of combining two or more strings into a single string.
              •  The concat() method is one way to concatenate strings in Java. It appends one string to the end of
                 another string.

              •  In the example, str1.concat(“ “ + str2) concatenates str1, a space, and str2.
              •  The result is a new string “Hello World”, which is stored in the variable result.
              •  String concatenation using the concat() method creates a new string object containing the concatenated
                 result. The original strings remain unchanged.

              •  The + operator can also be used for string concatenation in Java, as demonstrated in the println()
                 statements. It works similarly to the concat() method.






                                                           63
   73   74   75   76   77   78   79   80   81   82   83