Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

05 From Python To Java1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

05 From Python To Java1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

char and String

1
A string literal is a sequence of characters between
double quotes
 the characters making up a string have the primitive
type char

String s = "rub-a-dub-dub";
char c = s.charAt(0); // get first character of s

2
char literals are delimited by single quotes
 there must be exactly one character inside the quotes
 no such thing as an empty char

char c = 'a';
char blank = ' ';
char oops = ''; // does not compile, no such thing
// as an empty char

3
The type char is actually an integer type.
 a char value is an integer that is mapped to a character
 the mapping is defined by the Unicode Standard, version
6.0.0

System.out.println((int) Character.MIN_VALUE); // 0
System.out.println((int) Character.MAX_VALUE); // 65_535

char c = 65;
System.out.println(c); // 'A'
c += 25; // add 25 to c
System.out.println(c); // 'Z'

4
You can do some arithmetic with char, but the results
are unintuitive, especially when int values are involved.

char c = 'A';
c++; // ok, add 1 to c
c += 1; // ok, add 1 to c
c -= 1; // ok, subtract 1 from c
c = c + 1; // error, cannot convert from int to char

char d = 'B';
char e = c + d; // error, cannot convert from int to char

5
Arithmetic with char is useful when you want to
generate a sequence of characters.
 e.g., generate all pairs of two letter upper-case strings

for (char c = 'A'; c <= 'Z'; c++) {


for (char d = 'A'; d <= 'Z'; d++) {
String s = "" + c + d; string concatenation,
not char arithmetic
System.out.println(s);
}
}

6
Types, classes, and objects
 a type is a set of values and the operations that can be
done with those values
 a class defines a reference type in Java
 an object is an instance of a class

7
The String class
 a String object represents text (a sequence of
characters)
 very widely used in Java programs
 because they are so widely used, the Java language lets
a client perform actions with String objects that
cannot be performed with other types of objects
 e.g., string literals exist, but no literals exist for any other
reference type
 e.g., the + operator is defined for strings, but no arithmetic
or comparison operators are defined for any other reference
type

8
The String class
 documentation for the String class can be found at:
 https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

 String objects are immutable (just like in Python)


 the sequence of characters in a String object can never be
changed
 methods that seem like they change the characters of a
string actually return a new String object

9
The toUpperCase and toLowerCase methods return
uppercase and lowercase versions of a string without
modifying the original string

String s = "hello";
String up = s.toUpperCase();
System.out.println("s : " + s);
System.out.println("up : " + up);

// common error
s.toUpperCase(); // try to make "hello" be "HELLO"?

10
You require an object reference to call a non-static
method.

String s = "hello";
String up = s.toUpperCase(); // use the object referred
// to by s to call a
// non-static method

11
String does have static methods as well (see the
documentation).
 use the classname to call a static method
 e.g., to convert the value of a double to its String
representation

String s = String.valueOf(1.0);

// alternatively
String t = "" + 1.0;

12
Like in Python, a string is a numbered sequence
 each char in the sequence has an integer index
starting from zero

C I S C 1 2 4

0 1 2 3 4 5 6

13
The number of characters in a string is called its length
 returned by the method length

String courseName = "CISC124";


int len = courseName.length(); // 7

String empty = "";


len = empty.length(); // 0

14
The method charAt returns the character at a specified
index
 index must be between 0 and length() - 1,
inclusive

String courseName = "CISC124";


for (int i = 0; i < courseName.length(); i++) {
char c = courseName.charAt(i);
System.out.println(c);
}

15
Here is a method that counts the number of times a
specified character appears in a string:

public class Strings {


public static int freq(String s, char target) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == target) {
count++;
}
}
return count;
}
}

16
Here is an example of using the freq method:

public class TestStrings {


public static void main(String[] args) {
String courseName = "CISC124";
int count = Strings.freq(courseName, 'C');
System.out.println(count); // 2

count = Strings.freq(courseName, 'c');


System.out.println(count); ); // 0

count = Strings.freq(courseName, '4');


System.out.println(count); ); // 1
}
}

17
The contains method returns true if a string contains
a specified substring

String courseName = "CISC124";


boolean boo = courseName.contains("CISC"); // true
boo = courseName.contains("cisc"); // false
boo = courseName.contains("4"); // true

// search for a char?


boo = courseName.contains('C'); // error
boo = courseName.contains("" + 'C'); // true

18
The method indexOf returns the first location of a
specified character in a string
 returns -1 if the character is not in the string

String courseName = "CISC124";


int index = courseName.indexOf('C');
System.out.println(index); // 0

index = courseName.indexOf('S');
System.out.println(index); // 2

index = courseName.indexOf('4');
System.out.println(index); // 6

index = courseName.indexOf('z');
System.out.println(index); // -1

19
The method lastIndexOf returns the last location of a
specified character in a string
 returns -1 if the character is not in the string

String courseName = "CISC124";


int index = courseName.lastIndexOf('C');
System.out.println(index); // 3

index = courseName.lastIndexOf('S');
System.out.println(index); // 2

index = courseName.lastIndexOf('4');
System.out.println(index); // 6

index = courseName.lastIndexOf('z');
System.out.println(index); // -1

20
The equals method tests if a string is equal to a
specified string
 do not use == to compare two strings for equality

String cisc = "CISC124";


String math = "MATH124";
boolean eq = cisc.equals(math); // false

// case matters
eq = cisc.equals("cisc124"); // false

21
The + operator is the concatenation operation
 joins the characters of two strings to create a new
string

String name1 = "James Bond 007";


String name2 = "James " + "Bond " + "007";
boolean eq = name1.equals(name2); // true

22
Primitive values can also be concatenated onto a string

String name1 = "James Bond 007";


String name2 = "James " + "Bond " + "007";
boolean eq = name1.equals(name2); // true

String name3 = "James Bond " + 0 + 0 + 7;


eq = name1.equals(name3); // true

23
But beware of the order of the operands:

String laugh = 'h' + 'a' + "ha"; // 201ha

The expression 'h' + 'a' + "ha" involves operators all having the same
precedence, so it is evaluated from left to right:

1. 'h' + 'a' is the sum of two char literals; addition is not defined for
char so both operands are promoted to int and then summed to yield
201
2. 201 + "ha" involves a string so string concatenation is performed to
yield "201ha"

24
Python allows the programmer to slice a string to obtain
a substring:

s = 'abcdefg'
t = s[1:] # 'bcdefg'
u = s[3:4] # 'd'
v = s[5:7] # 'fg'

25
The substring methods allow the programmer to slice
a string in Java
 but negative indexes are not allowed

String s = "abcdefg";
String t = s.substring(1); // "bcdefg"
String u = s.substring(3, 4); // "d"
String v = s.substring(5, 7); // "fg"

26
Python allows the programmer to compare the
lexicographical order of two strings using <, >, and ==

s = 'a'
t = 'z'
print(s < t) # true
print(s > t) # false
print(s == 'a') # true

27
Use the compareTo method to compare two strings by
lexicographical order
 for two string references s and t

if s precedes t
s.compareTo(t) returns an integer less than zero
lexicographically

if s.equals(t) is
s.compareTo(t) returns zero
true

if s follows t
returns an integer greater than
s.compareTo(t) lexicographically
zero

28
String s = "aardvark";
String t = "zebra";

Expression Return value

s.compareTo(t) less than zero

s.compareTo(s) zero

t.compareTo(s) greater than zero

29
The replace methods will replace all occurrences of a
char or substring with a specified char or substring

String s = "sparring with a purple porpoise";


String t = s.replace('p', 't');
// starring with turtle tortoise

s = "hiho, hiho, it's off to work we go";


t = s.replace("hiho", "ohno");
// ohno, ohno, it's off to work we go

30

You might also like