2c

Advanced Placement

Computer Science Lab

 

 

Introduction to the String Class

 

 

 

 

Introduction

 

In the previous exercise we talked about how variables can be primitive types, e.g. Boolean, int, double, char, etc.  Variables can also be a reference to an object.  Objects are defined by classes.  Just as with primitive types objects are usually declared.  In the example below we are declaring an object of the String class and the declaration creates a reference to a String object.

 

 

 

 

 

           

 

String progTitle;

 

 

 

 

 

 

Just as with a primitive type, once a reference is created it should be initialized to something.  For objects this is call instantiation.  For the String object it would look like this:

 

 

progTitle = new String(“A Program to Make Metric Conversions”);

 

 

 

 

 

After an object has been instantiated, we can use the dot operator to access methods of the object (class).  We have already used the dot operator in output statements like System.out.print(); of the System.out class in which we use the print method.  By instantiating a string, you can use all of the methods of the string class which includes the following:

 

 

 

 

 

           

 

String (String str)

//The string class constructor-we will talk more about constructors later

 

char charAt (int index)

//Returns the character at the specified index integer

 

int compareTo (String str)

//Returns an integer indicating if the string str is lexically before (negative), equal to (zero) of after (positive)

 

String concat (String str)

//Returns a new string concatenated with string str (similar to “str1 + str2”) to this string

 

Boolean equals (String str)

//Returns true if str contains the same letters and case as this string

 

Boolean equalsIgnoreCase (String str)

//Returns true if str contains the same letters and case as this string

 

int length()

//Returns the number of characters in the string

 

String replace (char oldChar, char newChar)

//Returns a new string with a character replaced

 

String substring(int offset, int endIndex)

//Returns a substring that is a subset of this string starting at index offset and going through endIndex-1

 

String toLowerCase()

//Returns a string with everything converted to lower case

 

String toUpperCase()

//Returns a string with everything converted to upper case

 

 

 

 

 

 

 

Programming Assignment

 

Write the following programs.  Remember to import the appropriate class at the beginning of the program.

 

Start a new project, StringTest , and write an application program in the project that will ask user to input a string . Output the string length, a lowercase version, an upper case version, and version in which all the vowels have been replaced with x’s,  Have the user input two new strings and concatenate the strings and output them.