CPSC 233 - Introduction to Computer Science for Computer Science Majors II Tutorials: MW 3-3.50 MS 176 CT hours: Wednesday 5-6pm, Friday 12-3pm TA: Monir Zaman (Md Moniruzzaman)
CPSC 233 - Introduction to Computer Science
for Computer Science Majors II
Tutorials: MW 3-3.50 MS 176
CT hours: Wednesday 5-6pm, Friday 12-3pm
TA: Monir Zaman
(Md Moniruzzaman)
Variable declarations
int number2, number1;
float leng= 3.4f;
double diam=54.3;
number2 = number1 = 3;
long num3=789l;
print methods
double price = 19.8;
System.out.print("$");
System.out.printf("%f", price);
System.out.println("each");
will output the line
$19.80each
printf Format Specifier
• The code double price = 19.8;
System.out.print("$");
System.out.printf("%6.2f", price);
System.out.println(" each");
will output the line $ 19.80 each
2-4 Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Right and Left Justification in printf
• The code double value = 12.123;
System.out.printf("Start%8.2fEnd", value);
System.out.println();
System.out.printf("Start%-8.2fEnd", value);
System.out.println();
will output the following
Start 12.12End
Start12.12 End
2-5 Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Multiple arguments with printf
• What is the output of the following code:
double price = 19.8;
String name = "magic apple";
System.out.printf("$%6.2f for each %s. \n" , price, name);
System.out.println("Wow");
2-6 Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
String name1=“John”;
String name2=“Smith”;
If( name1.equals(name2) ) {
System.out.printf(“Names %s and %s are equal”, name1, name2);
}
String toUpperCase()
String toLowerCase()
Example:
String a_b=“stat101”;
System.out.println(a_b.toUpperCase());
STAT101
Some Methods in the Class String (Part 4 of 8)
1-14 Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
Some Methods in the Class String (Part 5 of 8)
1-15 Copyright © 2012 Pearson Addison-Wesley. All rights
reserved.
String: immutable type
• Individual characters of a string can not be changed like we can for Arrays
• StringBuffer supports changing individual char
• No mutator method is defined in String class
• String is defined as a immutable to prevent privacy leak
String s1 = "First string"; String s2 = s1; s1 = s1 + "!";
Exercise
• Write a program that has a string variable containing a line of text and then outputs that line with the first occurrence of “hate” changed to “love”. A sample output of the program:
String value: I hate strong wind. Correct output: I love strong wind. You can have the word “hate” more than once in the line but change only its first occurrence.