Java Strings

Strings

  • A string is an array of characters

  • Each element in the array is some sort of character


Java and Strings

  • Strings are a built in class type

    • Not primitive

  • They can contain any numeric and alphanumeric values

  • Always initialize Strings to something

    • String name = ““;

  • In Java, strings know their size

    • No need to calculate every time

  • Since strings are char arrats, the indexing starts from zero


public class Sample
{
    public static void main(String [] args)
    {
        String myString = "HarryPotter";
    }
}


What do you think happens in memory when the following three lines are executed?

String name;
name = "COP330";
name - "X";



Immutable vs Mutable Objects

  • Based on the pass example, you have witnessed that Strings are immutable

    • Immutable means that you cannot change anything about the object!

    • Even if you were to try to update a character index, Java will not compile

  • Mutable objects are the opposite of immutable


String Initialization

Some escape sequences to use:

  • \n: newline

  • \t: tab

  • \\: single slash

  • \\\\: double slash

  • \”: double quote

→ Backslash means operate the next char differently


length()

  • A get method that retrieves the length attribute of a String object

  • Runs in O(1) as it is only a lookup method

    • The size of the string is written on somewhere

    • It is being checked whenever we need the length of the string

  • Java Strings are char arrays, does not end with Null character!

package stringTest;

public class StringTest{
    public static void main(String[] args){
        String name = "test101\nThis";
        System.out.println("string is "+name +" length is " +name.length());
    }
}

→ Output: string is test101

                  This length is 12


equals

String name = "COP3330";
String anotherName = "COP3330";
System.out.println(name == name);
System.out.println(name.equals(anotherName));
  • If you want to compare the contents of strings, use the equals method!


String Concatenation

  • We can use the + operator to append a String to another String

    • Something to think about?

    • Are there runtime restrictions?

package stringTest;

public class StringTest{
    public static void main(String[] args){
        String name = "java";
        name = name + " is " + name; // name reference is changed
        System.out.println(name);// java is java
    }
}


String Tokenizer

package splittest;
import java.util.StringTokenizer;
public class splitTest{
    public static void main(String[] args){
        String sentence = "This.is.an.example.sentence";
        StringTokenizer st= new StringTokenizer(sentence, ".");
        while(st.hasMoreTokens()){
            String text=st.nextToken();
            // do NOT call nextToken again!
            System.out.print(text+" ");
        }//end of while
}//end of main

→ Output: This is an example sentence


split

package splittest;
// No need to import anything
public class splitTest{
    public static void main(String[] args){
        String sentence= "ThisXisXanXexampleXsentence";
        String[] arr= sentence.split("X");
        System.out.println(arr[0]);//first token
        System.out.println(arr[arr.length-1]); // last token
    }
}

→ Output: This

                  sentence


charAt()

  • Returns the char value at the specified index

  • No negative index in strings! 0 <= index < length()

  • What happens if the index is out of bounds?

    • For the below code, change the upper and lower limits of i and see what happens

String name= "Test";
//Traversing the string, character by character
for(int i=0;i<name.length();i++){
    char myChar = name.charAt(i);
    System.out.print(myChar);
}


compareTo()

  • Compares two Strings

  • Returns the value 0 if the argument string is equal to this string

    • A value less than 0 if this string is lexicographically less than the string argument

    • A value greater than 0 if this string is lexicgraphically greater than the string argument

package stringTest;

public class CompareToExample{
    public static void main(String args[]){
        String s1="hello";
        String s2="hello";
        String s3="meklo";
        String s4="hemlo";
        String s5="flag";

        System.out.println(s1.compareTo(s2));
        //0 because both are equal

        System.out.println(s1.compareTo(s3));
        //-5 because "h" is 5 times lower than "m"

        System.out.println(s1.compareTo(s4));
        //-1 because "l" is 1 times lower than "m"

        System.out.println(s1.compareTo(s5));
        //2 because "h" is 2 times greater than "f"
    }//end of main
} //end of class


Generating Substrings in Java

  • String class has a method called substring(x,y)

    • Two parametes

    • x is the first position of the original substring (inclusive)

    • y is the last position of original substring to go up to (exclusive)

  • Example

    • String str1 = “Java is Fun!”;

    • String str2 = str1.substring(0,3); // [0,3)

    • What will str2 store?

  • Can we give negative index number to substring method? No


concat()

  • Concatenates a string to another string

  • Prefer using +

  • Concat returns a new string, doesn’t modify the parameters