top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Working with String Class

0 votes
312 views

Working with String Class

The String class provides methods for manipulating individual characters of the string, comparing strings, extracting substrings, searching strings, and for converting a string to uppercase or to lowercase. 

Some of the frequently used methods of String class are as follows:

  • Length(String str)

The length() method is used to find the length of a string. For example,

String str=”Hello”;

System.out.println(str.length());   //output: 5

 

  • charAt(int index)

The charAt() method is used to retrieve the character value at a specific index. The index ranges from zero to length() -1. The index of the first character starts at zero. For example,

System.out.println(str.charAt(2));   //output: ‘1’

 

  • concat(String str)

The concat() method is used to concatenate a string specified as argument to the end of another string. If the length of the string is zero, the original String object is returned, otherwise a new String object is returned.

System.out.println(str.concat(“World”));  //output: ‘HelloWorld’

 

  • compareTo(String str)

The compareTo() method is used to compare two String objects. The comparison returns an integer value as the result. The comparison is based on the Unicode value of each character in the strings. That’s is, the result will return a negative value, if the argument string is alphabetically greater than the original string. The result will return a positive value, if argument string alphabetically lesser than the original string and the result will return a value of zero, if both the strings are equal.

For example,

System.out.println(str. compareTo(“World”));   /output: -15

The output is 15 because, the second string “world” begins with ‘W’ which is alphabetically greater than the first character ‘H’ of the original string, str. The difference between the position of ‘H’ and ‘W’ is 15. Since, ‘H’ is smaller than ‘W’, the result will be -15.

Note: Unicode is a standard that provides a unique number for every character irrespective of the platform, program, or language. The Unicode standard has been adopted for programming by major industry leaders such as IBM, Apple, Microsoft, HP, Oracle, Sun, SAP, and several others.

 

  • indexOf(String str)

The indexOf() method returns the in dex of the first occurrence of the specified character or string within a string.

If the character or string is not found, the method returns -1. For example,

System.out.println(str.indexOf(“e”));    /output: 1

 

  • lastIndexOf(String str)

The lastIndexOf() method returns the index of the last occurrence of a specified character of string from within a string. The specified character of string is searched backwards that is the search begins from the last character. For example.

System.out.println(str.lastIndexOf(“1”));    //output: 3

 

  • toString()

The toString() method is used to return a String object. It is used to convert values of other data types into string. For example,

Integer lengh=5;

System.out.println(length.toString());   //output:5

 

  • trim()

The trim() method returns a new string by trimming the leading and trailing whitespace from the current string. For example,

String str1= “    Hello    ”;

System.out.println(str1.trim());   //output: ‘Hello’

The trim() method will return ‘Hello’ after removing the spaces.

posted Dec 11, 2017 by Frank Lee

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

Working with StringBuilder Class

StringBuilder objects are similar to String objects, except that they are mutable. Internally, the system treats these objects as a variable-length array containing a sequence of characters. The length and content of the sequence of characters can be changed through methods available in the StringBuilder class. However, developers prefer to use String class unless StringBuilder offers an advantage of simpler code in some cases. For example, for concatenating a large number of strings, using a StringBuilder object is more efficient.

The StringBuilder class also provide a length() method that returns the length of the character sequence in the class.

However, unlike strings a StringBuilder object also has a property capacity that specifies the number of character spaces that have been allocated. The capacity to hold data in the instance of the StringBuilder class will automatically expand according to the user requirement to accommodate the new strings when added to the string builder.

Thus, the StringBuilder class is used for manipulating the String object. Objects of StringBuilder class are mutable and flexible. StringBuilder object allows insertion of characters and strings as well as appending characters and string at the end.

The constructors of the StringBuilder class are as follows:

  • StringBuilder(): Default constructor that provides space for 16 characters.
  • StringBuilder(int capacity): Constructs an object without any characters in it. However, it reserves space for the number of characters specified in the argument, capacity.
  • StringBuilder(String str): Constructs an object that is initialized with the contents of the specified string, str.

Methods of StringBuilder Class

The StringBuilder class provides several methods for appending, inserting, deleting, and reversing string as follows:

  • append() : The append() method is used to append values at the end of the StringBuilder object. This method accepts different types of argument, including char, int, float, double, boolean, and so on, but the most common argument is String.
  • insert(): The insert() method is used to insert one string into another. Similar to the append() method, it calls the String.valueOf() method to obtain the string representation of the value. The new string is inserted into the invoking StringBuildr object.
  • Delete(): The delete() method deletes the specified number of characters from the invoking StringBuilder object.
  • reverse(): The reverse() method used to reverse the characters within a StringBuilder object.
READ MORE

Java Modifiers

Java is a tightly encapsulated language. This means, that no code can be written outside the class. Not even the main() method. However, even within the class, code can become vulnerable to access from external environment. For this purpose, java provides a set of access specifiers such as public , private, protected, and default that help to restrict access to class and class members. However, at time, it is required to further restrict access to the members of a class to prevent modification by unauthorized code. Java provides additional field and method modifiers for this purpose.

Also, in some cases, it may be required to have a common data member that can be shared by all objects of a class as well as other classes. Java provides the concept of class variables and methods to solve this purpose. Classes sharing common attributes and behavior can also be grouped together for better understanding of the application. Java provides packages that can be used to group related classes. Also, the entire set of packages can be combined into a single file called the .jar file for deployment on the target system.

Field and Method Modifiers

 Field and method modifiers are keywords used to identify fields and methods that provide controlled access to users. Some of these can be used in conjunction with access specifiers such as public and protected. The different field modifiers that can be used are as follows:

  • Volatile
  • Native
  • Transient
  • Final

 

1. ‘volatile’ Modifier

The volatile modifier allows the content of a variable to be synchronized across all running threads. A thread is an independent path of execution of code within a program. Many threads can run concurrently within a program. The volatile modifier is applied only to fields. Constructors, methods, classes, and interfaces cannot use this modifier. The volatile modifiers is not frequently used.

While working with a multi threaded program, the volatile keyword is used. When multiple threads of a program are using the same variable, in general, each thread has its own copy of that variable in the local cache. In such a case, if the value of the variable is updated, it updates the copy in the local cache and not the man variable present in the memory. The other thread using the same variable does not get the updated value.

To avoid this problem, a variable is declared as volatile to indicate that it will not be stored in the local cache.

Also, whenever a thread updates the values of the variable, it is updates the variable present in the main memory. This helps other thread to access the updated value.

For example,

private volatile int testValue;  // volatile variable

2. ‘native’ Modifier

In some cases, it is required to use a method in java program that resides outside JVM. For this purpose, Java provide the native modifier. The native modifier is used only with methods. It indicates that the implementation of the method is in a language other than java such as C or C++. Constructors, fields, classes, and interfaces cannot use this modifier. The methods declared using the native modifier are called native methods.

The java source file typically contains only the declaration of the native method and not its implementation. In case of the native modifiers, the implementation of the method exists in a library outside the JVM. Before invoking a native method, the library that contains the method implementation must be loaded by making the following system call.

System.loadLibrary(“libraryName”);

To declare a native method, the method is preceded with the native modifier. Also, the implementation is not provided for the method. For example,

Public native void nativeMethod();

3. ‘transient’ Modifier

When a Java application is executed, the objects are loaded in the Random Access Memory (RAM). However, objects can also be stored in a persistent storage outside the JVM so that it can be used later. This determines the scope and life span of an object. The process of storing an object in a persistent storage is called serialization. For any object to be serialized, the class must implement the Serializable interface.

However, if transient modifier is used with a variable, it will not be stored and will not become part of the object’s persistent state. The transient modifier is useful to prevent security sensitive data from being copied to a source in which no security mechanism has been implemented. Also, transient modifier reduces the amount of data being serialized, improves performance, and reduces costs.

The transient modifier can only be used with instance variable. It informs the JVM not to store the variable when the object, in which it is declared, is serialized. Thus, when the object is stored in persistent storage, the instance variable declared as transient is not persisted.

4. ‘final’ Modifier

The final modifier is used when modification of a class or data members is to be restricted. The final modifier can be used with a variable, method, and class.

A variable declared as final is a constant whose value cannot be modified. A final variable is assigned a value at the time of declaration. A compile time error is raised if a final variable is reassigned a value in a program after its declaration.

final float PI =  3.14;

The variable PI is declared final so that its value cannot be changed later.

A method declared final cannot be overridden or hidden in a java subclass. The reason for using a final method is to prevent subclasses from changing the meaning of the method and increase the efficiency of code by allowing the compiler to turn method calls into inline java code. A final method is commonly used to generate a random constant in a mathematical application.

Code snippet

final float. getCommission (float sales)

{

System.out.println(“A final method…”);

}

The method getCommission() can be used to calculate commission based on monthly sales. The implementation of the method cannot be modified by other classes as it is declared as final. A final method cannot be declared abstract. As it cannot be overridden.

Rules and Best Practices for Using Field Modifiers

 Some of the rules for using field modifiers are as follows:

  • Final fields cannot be volatile.
  • Native methods in java cannot have a body.
  • Declaring a transient held as static or final should be avoided as far as possible.
  • Native methods violate Java’s platform independence characteristic. Therefore, they should not be used frequently.
  • A transient, variable may not be declared as final or static.
READ MORE
...