OCAJP – Creating and Manipulating Strings

This post is about the OCAJP exam objective “Creating and Manipulating Strings”. You will be mainly tested in the exam about String Immutability behavior. You will also be tested in the exam about various methods and syntax related to the String class. Here we would explain about the String class and important methods. It is very important to understand the concepts of String and how it is being created and manipulated inside JVM to effectively answer the questions in the OCAJP exam.

If you are preparing for the OCAJP exam, please try our free OCAJP 8 mock exam questions. Also send your feedback to feedback@whizlabs.com.

OCAJP 8 Free Test

Here is the some important points about the String class:

  • String is a class present in java.lang package since Java 1.0 version.
  • String is a final class and implemented three interfaces CharSequence, Comparable and Serializable .
  • String class is Immutable which means once String object is created , its contents can’t be changed.
  • If you try to change string object with its methods, a new object will be created with modified content. But the original object remains same.
  • String class is not thread safe.
  • String(Ex: “Java”) is a object which contains sequence of characters in Java
  • Whatever you write within double quotes (Ex: “Java”) is a String object in Java.

Creating String Objects

There are two ways of constructing String object./strong>

1)Without new operator

You can create String object without new object.

Example :

public class StringCreation {
    public static void main(String[] args) {
	String s1 = "Java"; //Line 1
	String s2 = "Java"; //Line 1
        System.out.println(s1 == s2); //prints true 
    }
}
  • When a class is loaded, the JVM goes through the code for the class and looks for String literals. When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the String constant pool.
  • Once a reference is made to that String object, any references to that String literal throughout your program are simply replaced with the reference to the object referenced from the String Constant Pool.
  • So, in the example shown above, there would be only one entry in the String constant pool, which would refer to a String object that contained the word “Java”. Both of the local variables, s1 and s2 would be assigned a reference to that single String object.

Look at the below the diagram to understand better.

String Objects - OCAJP

2) With new operator

String class has 13 constructors. We will understand only the important constructors used in the String class.

  • String()
  • String(char[] value)
  • String(String original)
  • String(StringBuffer buffer)
  • String(StringBuilder builder)

Example :

public class StringCreation {
    public static void main(String[] args) {
	char[] ch = { 'O', 'A', 'J', 'P' };
	StringBuffer sb1 = new StringBuffer("OCAJP");
	StringBuilder sb2 = new StringBuilder("OCAJP");
	String s = "OCAJP";
	String s1= new String(ch); //Line 1
	String s2= new String(sb1); //Line 2
	String s3= new String(sb2);//Line 3
	String s4= new String(s);//Line 4
	String s5= new String("OCAJP");//Line 5

	System.out.println("String object from char array: "+s1);
	System.out.println("String object from StringBuffer: "+s2);
	System.out.println("String object from StringBuilder: "+s3);
	System.out.println("String object from String: "+s4);
	System.out.println("String object from String: "+s5);
   }
}

It outputs like:

String object from char array: OAJP
String object from StringBuffer: OCAJP
String object from StringBuilder: OCAJP
String object from String: OCAJP
String object from String: OCAJP

Difference between using new Operator and without new Operator object creation:

Example:

public class StringCreationCompare {
    public static void main(String[] args) {
	String s1 = "Java";//Line1
	String s2 = new String("Java");//Line2
	String s3 = new String("Java").intern();//Line3
	System.out.println((s1 == s2));//prints false
	System.out.println((s1 == s3)); // prints true
   }
}
  • I hope you know == operator working. == operator compares objects references and it doesn’t compare the contents. If two reference variables are referring to same object , it returns true otherwise false.
  • When a class is loaded, the JVM goes through the code for the class and looks for String literals. When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the String constant pool. Once a reference is made to that String object, any references to that String literal throughout your program are simply replaced with the reference to the object referenced from the String Constant Pool.
  • So, in the example shown above, there would be only one entry in the String constant pool, which would refer to a String object that contained the word “Java”. The local variable s1 would be assigned a reference to that single String object.
  • At line 2, there is keyword “new,” the JVM is obliged to create a new String object at run-time, rather than using the one from the String constant pool and s2 is the reference for that new object.
  • At Line 3 , there is intern() method which first checks string constant pool, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
  • String constant pool has already contained object with same content, so reference for that object will be returned.
  • So s1,s3 are referring to the same object, s2 is referring to the another object.

Look at the below diagram to get more clarity.

String Objects Example in OCAJP

Garbage Collection

Let’s look at the below example program.

public class StringCreationCompare {
    public static void main(String[] args) {
	String s1 = "Java";//Line1
	String s2 = new String("Java");//Line2
	String s3 = new String("Java").intern();//Line3
       	s1=s2=s3=null;
    }
}
  • How many objects are eligible for garbage collection ? Did you say 1. Yes 1 object is eligible for garbage collection.
  • Unlike most objects, String literals always have a reference to them from the String Constant Pool. That means that they always have a reference to them and are, therefore, not eligible for garbage collection.

Look at the below diagram to get more clarity.

Garbage Collection in OCAJP

String Methods

In the subsequent sections, we would look at the various important String class’s methods and how to use them. These methds are very important for preparing OCAJP exam, in the exam you will be tested to answer the questions that are related to operations using the String methods.

Concatenation

Generally Concatenation means adding two things together. In Java, concatenation means adding two String objects together. We can achieve String objects concatenation using ‘+’ operator and concat method. When you concat two string objects, a new String object will be created.But original object doesn’t get changed.

concat():
public String concat(String str)

  • This method adds the specified string to the end of this string and returns a new String object . But the original object doesn’t get changed. This concept is “Immutability”.
  • If the length of the argument string is 0, then reference to same object will be returned. Otherwise, a new String object is returned that represents a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string. But the original object doesn’t get changed
  • Keep this point in mind. Because most of the questions will test in this concept ( Immutability).
  • Look at the below example to understand the Immutability concept practically.

Example :

public class StringConcat {
	public static void main(String[] args) {
		String s1 = "OCA"; //Line 1
		String s2 = s1.concat("JP8");//Line 2
		String s3 = s1 +"JP8"; //Line 3
		System.out.println("s1 content : "+s1);
		System.out.println("s2 content : "+s2);
		System.out.println("s3 content : "+s3);
		System.out.println("s1==s2 : "+(s1==s2));
		System.out.println("s1==s3 : "+(s1==s3));
		System.out.println("s2==s3 : "+(s2==s3));		
	}
}

It outputs like:

s1 content : OCA
s2 content : OCAJP8
s3 content : OCAJP8
s1==s2 : false
s1==s3 : false
s2==s3 : false
  • At Line 1 String object is created with content OCA and s1 is the reference for that object.
  • At Line 2 , concat method adds JP8 to the s1 object and creates new object with content OCAJP8 and s2 is the reference for that object.
  • At Line 3 you are adding s1 with object “JP8” using + operator, new object will be created with content OCAJP8 and s3 is the reference for that object.
  • s1,s2 are referencing to the different objects, so s1==s2 gives false
  • s1,s3 are referencing to the different objects, so s1==s3 gives false.
  • S2,s3 are referencing to the different objects, so s2==s3 gives false.

length(),isEmpty()

  • public int length() : This method returns the number of characters present in the String object.
  • public boolean isEmpty() : This method returns true if string doesn’t contain any characters(zero characters) otherwise returns false.

Example :

public class StringLength {
   public static void main(String[] a) {
	String s = "OCAJP8";
	String s1="";
	System.out.println("Length of s: "+s.length());//prints 6 
        System.out.println("s is Empty or not: "+s.isEmpty());//prints false
        System.out.println("s1 is Empty or not: "+s1.isEmpty());//prints true
    }
}
  • Here s.length() returns 6 because object contains 6 characters.
  • s.isEmpty() returns false because object contains characters.
  • s1.isEmpty() returns true because object doesn’t contain characters.

charAt(),toCharArray()
public char charAt(int index)

  • Returns the char value at the specified index. An index ranges from 0 to length() – 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
  • It throws IndexOutOfBoundsException, but it practically throws String IndexOutOfBoundsException.

public char[] toCharArray()

This method converts string object into char array.

Example:

import java.util.Arrays;
public class StringLength {
	public static void main(String[] a) {
		String s = "OCAJP8";
		System.out.println("char At 2 : " + s.charAt(2));
		char[] ch = s.toCharArray();
		System.out.println("char array from string object : "
				+ Arrays.toString(ch));
	}
}

It outputs like

char At 2 : A
char array from string object : [O, C, A, J, P, 8]

trim(),toString(),toUpperCase,toLowerCase,valueOf(),toCharArry()

  • public String toLowerCase() : This method converts string objects characters into lower case and returns new String object.
  • public String toUpperCase() : This method converts string objects characters into upper case and returns new String object.
  • public String trim() : It removes any leading and trailing whitespace in string object and returns new String object. It means, It will removes spaces at the starting and ending of character sequence in the string object.
  • public String toString() : It returns the string object with the same content as the original content.
  • public String ValueOf : This method is overloaded.valueOf method takes either boolean value or char value or double value or float value or int value or long value or char array or Object (you can pass any object) as argument and returns new String object with the particular content.
  • public char[] toCharArray() : This method converts the string to a new character array and returns that character array.

Example:

class Test{
	String name;
	Test(String name){
		this.name=name;
	}
	@Override
	public String toString() {
		return "[name=" + name + "]";
	}
	
}
public class StringOperations {
	public static void main(String[] a) {
		String s1 = "OCAJP8";
		String s2 = "  OCA  ";
		char [] c = s1.toCharArray(); 
		System.out.println("Without Spaces : "+s2.trim());
		System.out.println("s1 toString : "+s1.toString());
		System.out.println("s1 to lower case : "+s1.toLowerCase());
		System.out.println("s1 to upper case : "+s1.toUpperCase());
                System.out.println("s1 to char array : "+Arrays.toString(c));
	     int i=10;
	     char[] ch = {'O','C','A'};
	     Test t = new Test("OCA");
	     System.out.println("int to String : "+String.valueOf(i));
	     System.out.println("char to String : "+String.valueOf(ch));
	     System.out.println("Test to String : "+String.valueOf(t));
	}
}

It outputs like

Without Spaces : OCA
s1 toString : OCAJP8
s1 to lower case : ocajp8
s1 to upper case : OCAJP8
s1 to char array : [O, C, A, J, P, 8]
int to String : 10
char to String : OCA
Test to String : [name=OCA]

equals(),equalsIgnoreCase()

  • public boolean equals(Object anObject) : This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object other wise false. It is case sensitive.
  • public boolean equalsIgnoreCase(String anotherString) : This method compares this String to another String, ignoring case considerations. It returns true if two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case otherwise false.

Example:

public class StringEquals {
	public static void main(String[] args) {
		String s1 = "OCA";
		String s2 = "OCA";
		String s3 = "oca";
		System.out.println(s1.equals(s2));//Line 1
		System.out.println(s1.equals(s3));//Line 2
                System.out.println(s1.equalsIgnoreCase(s3));//Line 3
     }
}

It outputs like:

true
false
true
  • Line 1 prints true because s1, s2 contains same character sequence and letters case is also matched.
  • Line 2 prints false because s1, s3 contains same character sequence but the letters case is not matched.Since equals method is case sensitive , it returns false.
  • Line 3 prints true because s1, s3 contains same character sequence. So equalsIgnoreCase returns true, because it is not case sensitive.

contains(),replace()

contains() : public boolean contains(CharSequence s)

  • This method returns true if and only if this string contains the specified sequence of char values otherwise false.
  • You can pass string object or StringBuilder or StringBuffer as arguments to this method.
  • This method is case sensitive.

Example:

public class StringEquals {
	public static void main(String[] args) {
		String s1 = "OCAJP8";
		String s2 = "OCA";
		StringBuilder sb1 = new StringBuilder("OCA");
		StringBuffer sb2 = new StringBuffer("jp8");
		StringBuffer sb3 = new StringBuffer("JP8");
		System.out.println(s1.contains(s2));//Line1
		System.out.println(s1.contains(sb1));//Line2
		System.out.println(s1.contains(sb2));//Line3
		System.out.println(s1.contains(sb3));//Line4

	}

}

It outputs like:

true
true
false
true
  • Line 1 prints true because s1 contains s2 character sequence
  • Line 2 prints true because s1 contains sb1 character sequence.
  • Line 3 prints false because s1 contains sb2 character sequence.But the letters case is not matched.
  • Line 4 prints true because s1 contains sb2 character sequence.Here,the letters case is matched.

replace()

  • replace method is overloaded.
  • It is also case sensitive.
  • public String replace(char oldChar, char newChar)
  • This method replaces all occurrences of oldChar in this string with newChar and returns new String object with modified content.
  • If oldChar is not occurred in this String object, a reference to the original object will be returned.

Example:

public class StringReplace {
	public static void main(String[] args) {
		String s1 = "OCAJP8";
		String s2 = s1.replace('A', 'a');
		String s3 = s1.replace('Z', 'a');
                String s4 = s1.replace('a', 'x');

		System.out.println(s1);
		System.out.println(s2);
		System.out.println(s1 == s2);
		System.out.println(s3);
		System.out.println(s1 == s3);
        System.out.println(s4);
       System.out.println(s1 == s4);
	}
}

It outputs like

OCAJP8
OCaJP8
false
OCAJP8
true
OCAJP8
true

public String replace(CharSequence target, CharSequence replacement)

  • This method replaces all occurrences of target character sequence in this string with replacement character sequence and returns new String object with modified content.
  • If target character sequence is not occurred in this String object, a reference to the original object will be returned

Example:

public class StringReplace {
    public static void main(String[] args) {
	String s1 = "OCAJP8";
	String s = "a";
	StringBuilder sb1 = new StringBuilder("A");
	StringBuilder sb2 = new StringBuilder("a");
	StringBuffer sb3 = new StringBuffer("Z");
	String s2 = s1.replace(sb1, s);
	String s3 = s1.replace(sb2, s);
	String s4 = s1.replace(sb3, s);

	System.out.println(s1);
	System.out.println(s2);
	System.out.println(s1 == s2);
	System.out.println(s3);
	System.out.println(s1 == s3);
	System.out.println(s4);
	System.out.println(s1 == s4);
   }
}

It outputs like

OCAJP8
OCaJP8
false
OCAJP8
true
OCAJP8
true

startsWith(), endsWith()
startsWith()

  • public boolean startsWith(String prefix) : This method returns true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise. Note also that true will be returned if the argument is an empty string or is equal to this String object.

Example:

public class StringStarts {
    public static void main(String[] args) {
	String s1 = "OCAJP8";
	boolean b1 = s1.startsWith("OC");
	boolean b2 = s1.startsWith("");
	boolean b3 = s1.startsWith("OCAJP8");
	boolean b4 = s1.startsWith("OCP");
		
	System.out.println(b1);
	System.out.println(b2);
	System.out.println(b3);
	System.out.println(b4);
    }
}

It outputs like:

true
true
true
False
  • public boolean endsWith(String suffix) : This method returns true if the character sequence represented by the argument is a suffix of the character sequence represented by this object; false otherwise. Note that the result will be true if the argument is the empty string or is equal to this String object.

Example:

public class StringEnds {
     public static void main(String[] args) {
	String s1 = "OCAJP8";
	boolean b1 = s1.endsWith("JP8");
	boolean b2 = s1.endsWith("");
	boolean b3 = s1.endsWith("OCAJP8");
	boolean b4 = s1.endsWith("OC");
	System.out.println(b1);
	System.out.println(b2);
	System.out.println(b3);
	System.out.println(b4);
    }
}

It outputs like:

true
true
true
false

substring()

  • This method is overloaded.

public String substring(int beginIndex)

  • This method returns a new string object that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
  • If beginIndex is invalid(negative number or greater than string length), it throws IndexOutOfBoundsException.But practically it throws StringIndexOutOfBoundsException.

public String substring(int beginIndex, int endIndex)

  • This method returns a new string object that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex – 1 .
  • If beginIndex or endIndex or both invalid(if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex) , it throws IndexOutOfBoundsException.But practically it throws StringIndexOutOfBoundsException.

Example:

public class StringSub {
    public static void main(String[] args) {
	String s1 = "OCAJP8";
	String s2 =	s1.substring(3);
	String s3 =	s1.substring(1,5);
	System.out.println(s2);//prints JP8
	System.out.println(s3);//prints CAJP
    }
}

indexOf(),lastIndexOf()

  • indexOf() : It is overloaded method.
  • public int indexOf(int ch) : This method returns the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.Pay attention to the method signature , it takes int parameter. But you need to pass char value. Because char can be converted into int.
  • public int indexOf(int ch, int fromIndex) : This method returns the index of the first occurrence of the character in the character sequence represented by this object and search start from fromIndex. It returns -1 if the character does not occur.Pay attention to the method signature , it takes int parameter. But you need to pass char value. Because char can be converted into int
  • public int indexOf(String str) : This method returns the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.
  • public int indexOf(String str, int fromIndex) : This method returns the index of the first occurrence of the specified substring, starting at the specified index, or -1 if there is no such occurrence.
  • public int lastIndexOf(int ch) : This method returns the index of the last occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
  • public int lastIndexOf(int ch,int fromIndex) : This method returns the index of the last occurrence of the character in the character sequence represented by this object that is less than or equal to fromIndex, or -1 if the character does not occur before that point.
  • int lastIndexOf(String str) : This method returns the index of the last occurrence of the specified substring, or -1 if there is no such occurrence.The last occurrence of the empty string “” is considered to occur at the index value this.length().
  • public int lastIndexOf(String str, int fromIndex) : This method returns the index of the last occurrence of the specified substring, searching backward from the specified index, or -1 if there is no such occurrence.

Example:

public class StringSearch {
    public static void main(String[] args) {
	String s1 = "OCAJP8OCPJP8OCAJP8OCPJP8";
	int i1 = s1.indexOf('A');
	int i2 = s1.indexOf('P', 3);
	int i3 = s1.indexOf("OCP");
	int i4 = s1.indexOf("JP8", 4);
	System.out.println(i1);//prints 2
	System.out.println(i2);//prints 4
	System.out.println(i3);//prints 6
	System.out.println(i4);//prints 9
	int i5 = s1.lastIndexOf('A');
	int i6 = s1.lastIndexOf('P', 6);
	int i7 = s1.lastIndexOf("OCP");
	int i8 = s1.lastIndexOf("JP8", 4);
	System.out.println(i5);//prints 14
	System.out.println(i6);//prints 4
	System.out.println(i7);//prints 18
	System.out.println(i8);//prints 3
   }
}

Conclusion

For the OCAJP, Make sure you have clear understanding about String immutability concept. Remember the important String class methods declarations and their functionality. Be able to identify the correct output when multiple methods are chaining. Important methods for OCAJP is concat(), charAt(), length(), indexOf, lastIndexOf, substring(), trim(), equals(), equalsIgnoreCase(), toUpperCase(), toLowerCase(), startsWith(), endsWith(), contains(),replace().

References

We have published few useful articles for preparing OCAJP Exams. Please read the below articles for effective preparation.

Practice Tests

If you are looking for any support for Java certification preparation or purchasing our OCAJP Certification Kit, please send us a mail or call to our support.

 

About Aditi Malhotra

Aditi Malhotra is the Content Marketing Manager at Whizlabs. Having a Master in Journalism and Mass Communication, she helps businesses stop playing around with Content Marketing and start seeing tangible ROI. A writer by day and a reader by night, she is a fine blend of both reality and fantasy. Apart from her professional commitments, she is also endearing to publish a book authored by her very soon.

1 thought on “OCAJP – Creating and Manipulating Strings”

Leave a Comment

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


Scroll to Top