Core Java

OCA Java 8 Preparation : Strings

Believe me, Strings is one of the core topics in Core Java as well as for OCA Java Certification exam.If you prepare this topic well, it gives you an extra edge to score a lot better at your Oracle Associate exam.

In this post, we’ll try to cover all you need to know about Strings as far as OCA Java Certification is concerned.

Let’s get started.

Introduction :

String is the one of the most used classes in Java API. It is available in java.lang package.Following are some available constructors, you need to know for the exam :

new String(String value)      //Passing a String argument
new String()                  //creates an empty string
new String(char[] array)      //Passing a char array
new String(byte[] array)      //Passing a byte array
new String(StringBuilder sbr) //Passing StringBuilder object
new String(StringBuffer sbr)  //Passing StringBuffer object

String Constant Pool :

String pool is an interesting concept in Java. The main idea involved behind it is to promote re-usability of String objects as we can see Strings being used heavily in any Java application.

You can create a String reference using a new keyword with one of the available constructors, or using a String literal.Each time you instantiate a String using ‘new’ keyword, you are creating a new String object on the heap and the reference to this newly created object is returned.This isn’t the case when using String literals.

I.  String str1 = new String("abc"); // using new operator. 
II. String str2 = "abc";             //using a String literal

For instance ,in the first case,we are explicitly creating a String object on the heap and str1 will refer to this newly created object on the heap.However, in the second case, we are using String literals. Here, first of all a check will be made to see if there exists a String object with value “abc” in the String pool . If yes, the reference to this existing object will be returned or else a new object with value “abc” will be created in the String pool .

To test your understanding, you can try guessing the outputs in the below mentioned code:

String str1 = new String("abc");  
String str2 = "abc";            
System.out.println(str1 == str2);  //prints false
String str3 = "abc";
System.out.println(str1 == str3); //prints false
System.out.println(str2 == str3); //prints true
System.out.println("abc"== str3); //prints true

The last line of code might be a little confusing. Although the value “abc” isn’t assigned to an reference, but even in this case it is a String literal and will refer to the object with the value “abc” in the String pool.

To make it more clear, the below code will also create a String object with value “Hello World!” in the String pool.

System.out.println("Hello World!");

String is Immutable

String is immutable which means we can never modify a String object. Then you might think, how are we allowed to perform the operations on Strings ? Whenever you perform any operation on a String object , a new String object is generated as an output and the original String object remains untouched.

The immutability provides Strings with a great performance and re-usability advantage. To make String immutable, the inner implementation of String involves :

  • a private and final character array to hold the value of the String.
  • String class being marked final to avoid overriding its default behavior.
  • No setters exposed to prevent value being overwritten.
  • None of the methods of String class manipulate the elements of char[] array.
//String class partial Implementation
public final String implements Serializable, Comparable, CharSequence {
 private final char[] value;
----
}

String Concatenation

There are some rules to live-by as far as String concatenation is concerned .

  1. If both operands are numeric , ‘+’ means addition.
  2. If either of the operands is a String , ‘+’ means concatenation.
  3. The expression is always evaluated left to right.

That’s all you need to know to answer an related question. Try answering the questions below to help you practice the concept.

System.out.println(1 + 3);   //prints "4" , Rule 1
System.out.println(1 + "3");   //prints "13" , Rule 2
System.out.println(1 + 3 + "Hello"); //prints "4Hello"

String Methods

Below are the methods in the String class , you are expected to know for OCA Java certification exam.

  1. length() :This method returns the total count of characters in a string.
    int length()
  2. charAt() :This method returns a character at a given index. If the index value is < 0 or >= the length of String i.e for invalid index values , it throws a StringIndexOutofBoundException.
    char charAt(int index)
  3. indexOf() :There are couple of variants available for this method. You can pass either a String or a char to this method. Both works fine. As the name suggests, it returns the index of that particular char or String .Below are some available constructs :
    int indexOf(char ch)          
    int indexOf(String str)
    int indexOf(char ch, int fromIndex)
    int indexOf(String str, int fromIndex)

    fromIndex refers to the index from which the search for that particular char or String within a given string will start. indexOf() method returns -1 in case the match is not found.

  4. substring() : Substring method extracts a substring out of a string based on the parameters passed to this method. You can use any of the below constructs to do so.
    /*returns substring from specific index(incl.) to the end of the string*/
    String substring(int begIndex)
    /*returns substring from begIndex(incl.) to stopPos(excl.)*/
    String substring(int begIndex, int stopPos)

    Note that in the second construct, the returned value doesn’t includes the character at stopPos. Try predicting the outputs for the below mentioned code.

    String str = "Hello";
    System.out.println(str.substring(1));    //prints "ello"
    System.out.println(str.substring(1,3));  //prints "el"
    System.out.println(str.substring(1,1));  //empty string
    System.out.println(str.substring(2,1));  // throws exception
    System.out.println(str.substring(1,7));  // throws exception
    String val = null;
    val + = str;
    System.out.println(val);                 //prints "nullHello"
    
  5. toUpperCase() & toLowerCase() : These two methods need no introduction. They do exactly what their name suggests.
  6. equals()& equalsIgnoreCase() :These methods are used for String value comparison. equalsIgnoreCase() is case-insensitive.
    boolean equals(String str)
    boolean equalsIgnoreCase(String str)
  7. contains() : This method returns a boolean value and is used to check if a particular String value is contained in another string or not.
    boolean contains(String str)
  8. startsWith() & endsWith() :These methods also are the easy ones to use and looks for a given string to be a prefix or a suffix within another string.It also returns a boolean value.
    boolean startsWith(String prefix)
    boolean endsWith(String suffix)
    boolean startsWith(String prefix, int offset)
    boolean endsWith(String suffix, int offset)
    //offset here specifies the position from which to start looking for the prefix or a suffix in a given string
  9. replace() : This method replaces all the occurrences of a given char or string with another char or string based on its arguments.This method can accept char or any class which implements CharSequence (like String, StringBuffer or StringBuilder) as its arguments.
    String replace(char oldChar, char newChar)
    String replace(CharSequence seqOld, CharSequence seqNew)
  10. trim() : Thankfully, you have moved towards knowing the last method of String class for this exam and it is an easy one. This method trims or chops all whitespaces (including tabs,”\n”,”\t”,”/r”) from the front and end of the string.
    String str = "        Hello World\n";
    System.ou.println(str); // outputs "Hello World!"

     

Strings Comparison :  ‘==’ vs equals()

== is used for comparing the references where as equals() method is used for comparing the value of String literals.

String obj1 = new String("Hello");
String obj2 = new String("Hello");
System.out.println(obj1==obj2);//prints false
System.out.println(obj1.equals(obj2)); //prints true

One important point to note here is that the Strings that are returned by the available methods in the String class ,for eg : result of “Hello”.substring(1) , are not stored in the String constant pool. The output values returned by any of the available String methods are created using new operator.

Examiners might try to trick you on this concept. Try and answer the question below to solidify your understanding.

String val1 = "Jake";
String val2 = "Jacky";

String out1 = val1.substring(0,2);
String out2 = val2.substring(0,2);
System.out.println(out1==out2); //prints false
System.out.println(out1.equals(out2)); //prints true

 

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *