You are on page 1of 9

M.

El Dick - I2211 1

Class String
2

 Creates object that represents a string of characters

 Belongs to java.lang package

 Like other classes, has constructors and methods

 Unlike other classes, has 2 operators: + and += (for


concatenation)

STRINGS
Chapter 4 M. El Dick - I2211

Literal Strings Literal Strings (cont’d)


3 4

 Can be assigned to string variables


 Anonymous constant objects of the String class
 Can be passed to methods and constructors as
 Defined as text in double quotes parameters
 “java”, “hello\n”  Have methods you can call:

 Don’t have to be constructed: they are “just there”


String word = “start";
if ("Start".equals(word)) ...

M. El Dick - I2211 M. El Dick - I2211


Immutability Immutability (cont’d)
5 6

 Once created, a string cannot be changed:  Advantage: more efficient, no need to copy
 No methods changes the string
String s1 = "Sun"; String s1 = "Sun";
String s2 = s1; String s2 = new String(s1);
 Such objects are called immutable

s1 s1 "Sun"
"Sun"
s2 s2 "Sun"

OK Less efficient: wastes


memory
M. El Dick - I2211 M. El Dick - I2211

Immutability (cont’d) Empty Strings


10-7 10-8

 Disadvantage: less efficient  An empty string has no characters, length = 0


 Need to create a new string and throw away the old one
for every small change String s1 = ""; Empty strings
String s2 = new String();
String s = "sun";
char ch = Character.toUpperCase(s.charAt (0));
s = ch + s.substring (1);

 Not to be confused with an uninitialized string:

s "sun" String errorMsg; errorMsg is


null
"Sun"
M. El Dick - I2211 M. El Dick - I2211
Constructors Methods — length, charAt
10-9 10

 No-args and copy constructors are not used much  int length ();
 returns the number of characters in the string

String s1 = new String (); String s1 = "";


String s2 = new String (s1); String s2 = s1;  char charAt (k);
Character positions are
 returns the k-th char numbered starting from 0

 Other constructors convert arrays into strings Returns:


”Flower".length(); 6
”Wind".charAt (2);
’n'

M. El Dick - I2211 M. El Dick - I2211

Methods — substring Methods — Concatenation


10-11 10-12

 String s2 = s.substring (i, k);  String result = s1 + s2;


 concatenates s1 and s2
 returns the substring of chars in positions from i to k-1

 String result = s1.concat (s2);


 String s2 = s.substring (i);  the same as s1 + s2
 returns the substring from the i-th char to the end

 result += s3;
Returns:
 concatenates s3 to result
”strawberry".substring (2,5); "raw"
"unhappy".substring (2); "happy"
"emptiness".substring (9); "" (empty string)  result += num;
 converts num to String and concatenates it to result

M. El Dick - I2211 M. El Dick - I2211


Methods — Find (indexOf) Methods — Comparisons
10-13 10-14

0 8 11 15  boolean b = s1.equals(s2);
 returns true if the string s1 is equal to s2
 String date ="July 5, 2012 1:28:19 PM";
Returns:
 boolean b = s1.equalsIgnoreCase(s2);
 date.indexOf ('J'); 0
 returns true if the string s1 matches s2, case-blind
 date.indexOf ('2'); 8
 date.indexOf ("2012"); 8  int diff = s1.compareTo(s2);
 date.indexOf ('2', 9); 11 Starts searching at
position 9  returns the “difference” s1 - s2

 date.indexOf ("2020"); -1 Not found  int diff = s1.compareToIgnoreCase(s2);


 date.lastIndexOf ('2'); 15  returns the “difference” s1 - s2, case-blind

M. El Dick - I2211 M. El Dick - I2211

Methods — Replacements Replacements (cont’d)


10-15 10-16

 String s2 = s1.trim ();  Example: how to convert s1 to upper case


 returns a new string formed from s1 by removing white space at
both ends s1 = s1.toUpperCase();

 String s2 = s1.replace(oldCh, newCh);  A common bug:


 returns a new string formed from s1 by replacing all occurrences of
oldCh with newCh s1 remains
s1.toUpperCase();
unchanged
 String s2 = s1.toUpperCase();
 String s2 = s1.toLowerCase();
 returns a new string formed from s1 by converting its characters to
upper (lower) case

M. El Dick - I2211 M. El Dick - I2211


Numbers to Strings Numbers to Strings (cont’d)
10-17 10-18

 3 ways to convert a number into a string:  The DecimalFormat class can be used for formatting
 String s = "" + num; numbers into strings
import java.text.DecimalFormat;
...
 String s = Integer.toString (i); DecimalFormat money = new DecimalFormat("0.00");
String s = Double.toString (d); ...
double amt = 56.7381;
...
String s = money.format (amt);
 String s = String.valueOf (num); 56.7381

"56.74"

M. El Dick - I2211 M. El Dick - I2211

Numbers to Strings (cont’d) Numbers from Strings


10-19 10-20

 Java 5.0 added printf and format methods: if s not a valid number (integer, real number), ERROR
int m = 5, d = 19, y = 2007;
double amt = 123.5;
String s1 = "-123", s2 = "123.45";
System.out.printf (
int n = Integer.parseInt(s1);
"Date: %02d/%02d/%d Amount = %7.2f\n", m,
d, y, amt); double x = Double.parseDouble(s2);

String s = String. format(


"Date: %02d/%02d/%d Amount = %7.2f\n", m,
d, y, amt);

"Date: 05/19/2007 Amount 123.50"


M. El Dick - I2211 M. El Dick - I2211
Character Methods (cont’d) Character methods (cont’d)
10-21 10-22

if (Character.isDigit (ch)) ...  char ch2 = Character.toUpperCase (ch1);


.isLetter... .toLowerCase (ch1);
.isLetterOrDigit...  if ch1 is a letter, returns its upper (lower) case; otherwise
returns ch1
.isUpperCase...
Whitespace is  etc.
.isLowerCase... space, tab,
.isWhitespace... newline, etc.
return true if ch belongs to the corresponding
category

M. El Dick - I2211 M. El Dick - I2211

Exercise 1
24

23 Exercises Hexadecimal digits : digits '0' through '9' + letters 'A' through 'F'
Write a function hexValue that uses a switch statement to find the
hexadecimal value of a given character
 Character is a parameter to the function
 Hexadecimal value of character is the return value of the function
 If parameter is not one of the legal hexadecimal digits, return -1

M. El Dick - I2211 M. El Dick - I2211


boolean valid;
valid = true; // Assume that the input is valid, and change our mind if we find an invalid

Exercise 2
character.
for ( i = 0; i < hex.length(); i++ )
25 if ( hexValue(hex.charAt(i)) == -1 ) { // Character number i is bad.
valid = false ;
Hexadecimal integer = sequence of hexadecimal digits
break; // Leave the for loop, since we are now sure of the answer.
 If str is a string containing a hexadecimal integer, then its }
decimal integer is computed : if ( valid ) { // If the input is valid, compute and print base-10 value
value = 0; dec = 0 ;
for ( i = 0; i < str.length(); i++ ) for ( i = 0 ; i < hex.length() ; i++ )
dec = 16*dec + hexValue( hex.charAt(i) );
value = value*16 + hexValue( str.charAt(i) );
System.out.println("Base-10 value is: " + dec);
}
 Write a program that reads a string from the user. else { // Input is not valid, print an error message

 If all the characters in the string are hexadecimal digits, System.out.println("Error: Input is not a hexadecimal number.");
print out the corresponding decimal value. }

 If not, print out an error message.


M. El Dick - I2211 26 M. El Dick - I2211

dec = 0;
for ( i = 0; i < hex.length(); i++) {
Exercise 3
28

int digit = hexValue( hex.charAt(i) );


 Write a program that can:
if (digit == -1) {
 Remove the 1st three occurrences of the character ‘m’
System.out.println("Error: Input is not a hexadecimal number.");
(capital or small) from “I’m a JaVa PrOgRaMmEr” string
return;
 Display the resulting string to the screen
}
dec = 16*dec + digit;
}
 NOTE: Your program should work for any string having
at least 3 ‘m’ characters
System.out.println("Base-10 value: " + dec);

27 M. El Dick - I2211 M. El Dick - I2211


Exercise 4 Exercise 5
29 30

 Write a program that splits then prints the 3 components of  Write a function that generates a password for a
the following course description: person using its initials and age given as parameters
INFO 311 : Java Programming
 as shown below:
Course Name: INFO  Use this function in a main method and print the result to
Course Number: 311 the screen
Course Description: Java Programming

 NOTE: Your program should work for any course description


following the above format

M. El Dick - I2211 M. El Dick - I2211

public class PasswordMaker {

public String generatePassword(String firstName, String lastName, int Exercise 6


age){ 32
String initials = firstName.substring(0,1) + lastName.substring(0,1);
String password = initials.toLowerCase() + age;  Modify the previous exercise in such a way that instead
return password; of taking the name initials, it takes the middle letter
} from the first and last name
public static void main(String[] args) {
String newPassword = generatePassword(“John”, “Smith”, 20);
 The obtained letters will be concatenated along with
System.out.println("Your Password = " + newPassword);
} age which is multiplied by 100
}

31 M. El Dick - I2211 M. El Dick - I2211


Exercise 7 Exercise 8
33 34

 Write a program that can exchange the last  Write a class that contains :
names of 2 persons a static method findMin(String[] set) that returns the
minimum of a set of positive integers given as an
argument
 a method main() defined as follows :
public static void main(String[] arg){
String[] t = {“16”, “2”, “36”, “-64”};
System.out.println(“The minimum is : “ +findMin(t));
}

M. El Dick - I2211 M. El Dick - I2211

You might also like