The document discusses various String methods in Java:
- The charAt() method returns the character at a given index in the String.
- The compareTo() method compares two Strings lexicographically and returns an integer indicating their relative ordering.
- The indexOf() method returns the index of the first occurrence of a character or substring in the given String. It has overloads to specify a starting index for the search.
2. String
Immutable
Every time you alter String values, it will
allocate another exact amount of space in
the heap. The previous value in the memory
will be garbage-collected later.
Mutable
When created it reserves a certain amount of
space in the heap, which can be larger than the
value. Within that space, values can be
modified without additional memory use.
When the value requires more space, the space
will automatically grow larger.
StringBuffer
String s = "a";
s += "b";
s += "c";
ab
abc
a
s
StringBuffer s = new StringBuffer("a");
s.append("b");
s.append("c");
a
s
…
buffer size: 1+16
b c
6. public class BreakAndContinue {
public static void main(String[] args) {
int i;
System.out.println("Example 1");
for (i = 1; i <= 5; i++) {
System.out.print(i);
if (i == 3) {
break;
}
System.out.println(" " + i);
}
System.out.println("nThe value of i after the loop is: " + i);
System.out.println("nExample 2");
for (i = 1; i <= 5; i++) {
System.out.print(i);
if (i == 3) {
continue;
}
System.out.println(" " + i);
}
System.out.println("nThe value of i after the loop is: " + i);
}
}
We will jump out in the middle of a
for loop meant for 5 iterations
We will skip over part of iteration #3
break and continue
7. packages
A package is a grouping of related types (classes, interfaces, enumerations, and
annotation).
8. packages
/* File name : Animal.java */
package animals;
public class Mammals {
public void eat();
public void travel();
}
- Create a package at the top of the
source code.
- lowercase.
/* File name : oneDriver.java */
…
animals.Mammals m1 = new animals.Mammals();
…
/* File name : anotherDriver.java */
import animals.*;
Mammals m1 = new Mammals();
…
- After import, we can call any
public classes inside the animals
package without full path.
- In other packages, without
import, you need to specify full
package path
Using it
Creating package
9. import java.util.Date;
import my.own.Date;
class Test{
public static void main(String [] args){
// how can I use both Date types??? namespace conflict!
}
}
packages
class Test{
public static void main(String [] args){
my.own.Date myDate = new my.own.Date();
java.util.Date javaDate = new java.util.Date();
}
}
Instead of importing both, use full-path to the
type
10. /* Animal.java */
package interfaceExample;
public interface Animal {
public String getName();
public void setName(String s);
public String makeSound();
public String toString();
}
/* Cat.java */
package interfaceExample;
public class Cat implements Animal {
private String animalName;
public Cat(String nameIn) { animalName = nameIn; }
public String getName() { return animalName; }
public void setName(String nameIn) {
animalName = nameIn;
}
public String makeSound() {
return "meow";
}
public String toString() { return animalName; }
…
/* Dog.java */
package interfaceExample;
public class Dog implements Animal {
private int burriedBonesCount;
private String animalName;
public Dog(String nameIn) {
animalName = nameIn;
burriedBonesCount = 0;
}
public
…
interfaceExample
Animal
Cat
Dog
interface
Cat and Dog classes
must have every
method defined in
the Animal
interface.
11. package interfaceExample;
public class PetDriver {
public static void main(String [] args) {
Animal[] pets = new Animal[3];
pets[0] = new Cat("Neko");
pets[1] = new Dog("Fluffy");
pets[2] = new Cat("Crookshanks");
Animal temp;
for (int i=0; i<pets.length; i++) {
temp = pets[i];
System.out.println(temp.getName() + " says " + temp.makeSound());
}
}
}
interfaceExample
Animal
Cat
Dog
13. When can we access private fields?
1) In the same class or
2) when the object is passed as a parameter.
Question. Can we access private fields of an
object in JUnit test?
14. ! No button in debugger makes the program "skip" code.
! They all run the following code, but pause at different positions.
[step over] "run the current line, and pause at the next line."
[step into] "go into the first method that will be invoked in the current line, and pause at the first line
of the method. If there's no method to go into, then pause at the next line."
[step return] "run the following lines of code, and pause after returning."
public int met() {
long startTime = new Date().getTime();
System.out.print("Current Time: "+startTime.toString());
for (int i = 0; i < 50000; i++) {
startTime++;
}
return startTime;
}
step into will go into
java.lang.Long.toString()
method.
step over will run the
current line and pause at
the next line.
step return will run the
remaining lines and pause
after returning.
15. Rational r = new Rational(8,3);
assertEquals(r.getNumer(), 8);
assertEquals(r.getDenom(), 3);assertEquals is
a static
method of
jnit.assert
class
numer and denom
are private fields.
You cannot access
them with
r.numer or r.demon
16. assertEquals(r.getNumer(), 8);
assertEquals(r.getDenom(), 3);
assertTrue(r.getNumer() == 8 && r.getDenom() == 3);
if(r.getNumer()==8 && r.getDenom() == 3) {
assertTrue(true);
} else {
assertFalse(false);
}
Are these all same? Then which one is the best practice?
Different codes, same test
Compact, but
cannot tell which
one failed.
Unnecessarily
complicated code.
19. Card deck exercise
1. Make a group of four people (with at least one
card deck)
2. Shuffle the deck
3. Deal out 5 cards to each, and discuss which wacky
hands each have.
4. Deal out two cards to each and three as
community cards. Discuss who got the best hand.
21. CVS / Lab08
public static int[] tallyArray(int[] arrayIn) throws RuntimeException {
int[] retArr = new int[10];
//Your code goes here…
}
It will return
an int array.
It will accept
an int array.
input array output array
# of occurrances of the value i+1
exception
[1,10,1,9,9] [2,0,0,0,0,0,0,0,2,1]
[1,2,3] [1,1,1,0,0,0,0,0,0,0]
[10] [0,0,0,0,0,0,0,0,0,1]
null [0,0,0,0,0,0,0,0,0,0]
[1,10,1,9,11] RuntimeException: "Ooops. Sorry about that"
[1,10,1,9,0] RuntimeException: "Ooops. Sorry about that"
22. Use exceptions instead of if-conditionals
for(int i=0;i<arrayIn.length;i++) {
retArr[arrayIn[i]-1]++;
}
Basic code without handling exceptional cases
There are two exceptions can be thrown.
1. when arrayIn is null
NullPointerException will be thrown
should return [0,0,0,0,0,0,0,0,0,0]
2. when arrayIn contains a number <1 or >10
ArrayIndexOutOfBoundsException will be thrown
should throw RuntimeException: "Ooops. Sorry about
that."
Catch and handle these exceptions individually.
DO NOT USE IF-CONDITIONALS
23. RuntimeException e = new RuntimeException("ahaha");
throw e;
// same thing
throw new RuntimeException("Ooops.");
26. Ternary operator
if (a>b) {
result = "ha";
else {
result = "ho";
}
result = a > b ? "ha" : "ho";
=
If condition is true, then the expression is evaluated to
value_if_true, otherwise it will be
value_if_false.
condition ? value_if_true : value_if_false
Practice.
Write a method that accepts an int parameter "numCookies"
and prints out
(if numCookies is 1) "There is 1 cookie in the jar."
(if numCookies is n) "There are n cookies in the jar."
* Do not use if-else. Use ternary operator.
* Assume numCookies is a positive number (>0).
27. Switch
Simpler and more readible version of if-then-else statements
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
…
default: monthString = "Invalid month";
break;
}
int month = 8;
String monthString;
if (month == 1) {
monthString = "January";
} else if (month == 2) {
monthString = "February";
} else if (month == 3) {
…
} else {
monthString = "Invalid month";
}
... // and so on
=
Why should I break?
"default" is like "else"
28. Practice.
Write a method that accepts a char parameter, which will be an
uppercase letter, and then uses a switch statement to return an
int based on the number of "pen strokes" to draw the letter. If
the parameter is not an uppercase letter, return -1.
e.g. If 'C' is given, then it should return 1.
e.g. If 'D' is given, then it should return 2.
Characters with 1 stroke : C,L,M,N,O,S,U,V,W,Z
Characters with 2 strokes : D,G,J,P,Q,T,X
Characters with 3 strokes : A,B,F,H,I,K,R,Y
Characters with 4 strokes : E
* Do not use if-else. Use switch
* You can combine multiple cases in a single line like below
case 'C': case 'L': case 'M' …
Switch
31. Further readings on "Why String is immutable in Java?"
http://www.programcreek.com/2013/04/why-string-is-immutable-in-java/
Mutable objects Immutable objects
Contains setter methods
e.g. photo.setPixel(row,col,pixel)
No setter methods
e.g. pixel object had no setRed(value)
Not all data fields are final All data fields are final
StringBuffer, MutableInt,
Photo class in Project 3
String, Integer,
Pixel class in Project 3
(+) Fast when updating data fields
(-) Must use deep copy
(-) 1000 times slower than mutable ojb
(+) Shallow copy is okay
(+) Create once and use multiple times
e.g. You could use one black pixel to paint
weirdCombination's background in black.
32. Deep copy Shallow copy
(+) Changing Peggy(b1)'s information
will not affect Peggy(b2)
(+) Changing Peggy(b1)'s information
will affect Peggy(b2)
public Bag(Bag other) {
this.p1 = other.p1;
this.p2 = other.p2;
this.p3 = other.p3;
this.p4 = other.p4;
}
Bag b2 = new Bag(b1);
public Bag(Bag other) {
this.p1 = new Person(other.p1);
this.p2 = new Person(other.p21);
this.p3 = new Person(other.p3);
this.p4 = new Person(other.p4);
}
Bag b2 = new Bag(b1);
Shallow copy is safe if Person objects
are immutable.
Deep copy is safe if Person objects are
mutable.
33. …
public Rational(int numberIn, int denomIn) {
if (denomIn==0) throw new
ArithmeticException("Divide by Zero");
numer = numerIn;
denom = denomIn;
}
…
public Rational divide(Rational other) {
try {
return multiply(this, other.reciprocal());
} catch(ArithmeticException e) {
System.out.println("An exception caught at
divide.");
}
}
…
public Rational reciprocal() {
return new Rational(denom, number);
}
…
Exceptions // in testDivide() method
Rational r2 = new Rational(5,11);
Rational s2 = new Rational(0, 9);
try {
r2.divide(s2);
assertTrue(false);
}
catch (ArithmeticException e) {
assertTrue(true);
}
testDivide()
divide()
reciprocal multiply
Constructor
throw
Do not catch
Catch and print out
"An exception caught at divide."
Nothing to catch.
Will fail the test.
34. How to design unit test
public void testDivide() {
Rational r1 = new Rational(7,11);
Rational s1 = new Rational(5, 3);
Rational p1 = r1.divide(s1);
assertEquals(21, p1.getNumer());
assertEquals(55, p1.getDenom());
Rational r2 = new Rational(5,11);
Rational s2 = new Rational(0, 9);
try {
r2.divide(s2);
assertTrue(false);
}
catch (ArithmeticException e) {
assertTrue(true);
}
}
Test a common use case.
Test an exceptional case.
1. Manual test
If ArithmeticException is thrown
by divde method, it will pass the
test.
This line will throw an exception
If executed, this line will always fail the test.
35. 2. Using an oracle
How to design unit test
public void add() {
Random rnd = new Random(7);
Rational rationalValueA;
Rational rationalValueB;
Rational rationalAnswer;
int v1, v2, v3, v4;
for (int i=0; i<1000; i++) {
v1 = rnd.nextInt(500);
v2 = rnd.nextInt(500);
v3 = rnd.nextInt(500);
v4 = rnd.nextInt(500);
rationalValueA = new Rational(v1, v2);
rationalValueB = new Rational(v3, v4);
rationalAnswer = rationalValueA.add(rationalValueB);
assertEquals("Trying " + rationalValueA + " plus " + rationalValueB,
v1*v4 + v2*v3, rationalAnswer.getNumer());
assertEquals("Trying " + rationalValueA + " plus " + rationalValueB,
v2 * v4, rationalAnswer.getDenom());
}
}
This is how the add method is supposed to work.
Repeat 1000 times with random settings.
37. String methods
String str = "studytonight";
System.out.println(str.charAt(2)); // => u
charAt(int i) returns the character at the index i position
String a = "a";
String b = "b";
System.out.println(a.compareTo(b)); // => -1
System.out.println(b.compareTo(a)); // => 1
System.out.println(a.compareTo(a)); // => 0
a.compareTo(b) compares a and b lexicographically.
38. String methods
String str = "The quick brown fox jumps over the lazy dog";
System.out.println(str.indexOf('u')); // => 5
System.out.println(str.indexOf('&')); // => -1
System.out.println(str.indexOf(' ')); // => 3
System.out.println(str.indexOf(' ',3)); // => 3
System.out.println(str.indexOf(' ',4)); // => 9
a.indexOf(int ch) returns the first index of ch within a
a.indexOf(String s) returns the first index of s within a
a.indexOf(int ch, int fromIndex)
returns the first index of ch within a, starting search at the fromIndex
39. String methods
String str = "1-2-3-4-5";
System.out.println(str.replace('-',' ')); // => "1 2 3 4 5"
a.replace(char oldCh, char newCh)
returns a new string resulting from replacing all oldCh in a with newCh
String str = "aaaaa";
System.out.println(str.replace('a','b')); //=> "bbbbb"
System.out.println(str.replace("aa","b")); //=> "bba"
System.out.println(str.replace("aaa","a")); //=> "aaa"
a.replace(CharSequence o, CharSequence n)
returns a new string resulting from replacing all o in a with n
Can be CharBuffer, Segment, String, StringBuffer, StringBuilder
Newly added string will not be evaluated.
40. String methods
String str = "0-2-4-6-8";
System.out.println(str.substring(4)); // => "4-6-8"
a.substring(int beginIndex)
returns a new string from beginIndex till the end
String str = "0-2-4-6-8";
System.out.println(str.substring(4,8)); // => "4-6-"
a.substring(int beginIndex, int endIndex)
returns a new string from beginIndex (inclusive) till endIndex (exclusive)
42. Debugging
Trace program's behavior line-by-line
Step 1. Set "break point" at the suspicious line
Step 2. Run the debugger
next line into
Step 3.
- Examine the contents of memory
- Decide how to proceed with running/debugging the program by either
stepping "over", "into", or "out of" code segments
out of
45. Midterm review
Regrading request
- Write it on a separate sheet of paper
- Hand it in to professor with your exam.
- The entire exam will be regraded.
46. - Will our culture really be defined by interfaces?
- What "uses" are there for information visualization in
terms of explaining things to the general public.
- Mechanical Turk
* ethics (pay is below US minimum wage)
* what would they want to do using Mechanical Turk
* origins of the name (interesting con around a chess playing
machine around 200 years ago)
- Art and Computer Science
* can CS people create art? can Art people create CS?
* what ideas do they have in terms of CS changing the Art world
* ask if any of them have been to the 3rd floor of CSIC and seen
the Treemap art gallery
47. Javadoc: Java Documentation Comments
Javadoc is a tool which comes with JDK and it is used for generating Java code
documentation in HTML format from Java source code which has required
documentation in a predefined format.
source code
generated documentation web page
block comment that starts with /**
@tagName to add special tags
48. Javadoc: Java Documentation Comments
@param Adds a parameter with the specified parameter-name followed by the
specified description to the "Parameters" section.
@return Adds a "Returns" section with the description text. @return description
@see Adds a "See Also" heading with a link or text entry that points to reference.
@throws Adds a Throws subheading to the generated documentation, with the class-
name and description text..
50. public class Student {
public String name;
public int tokenLevel;
private static int currentCount = 0;
private static final int DEFAULT_TOKENS = 3;
public Student() {
name = "unknown";
tokenLevel = DEFAULT_TOKENS;
currentCount++;
}
}
Student s1 = new Student();
s1.name = "Tak";
STACK HEAP META SPACE
DEFAULT_TOKENS
0
3
currentCount 1 X
s1
name
tokenLevel 3
"unknown"
"Tak"
constructor
All static fields of a class live in
Metaspace.
All local variables (both
primitives and references)
live on the stack. Non-
primitive data objects are
stored in the heap, and
referenced by variables on
the stack.
All non-primitive objects live on the heap.
Primitive instance variables of those objects
are stored inside the object. Non-primitive
variables are stored outside of the object,
and referenced by the instance variable.
51. Size? 5
*
***
*****
*******
*********
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
for(int row=0; row<size; row++) {
for(int col=0;col<4-row;col++) {
System.out.print(" ");
}
for(int col=0;col<row*2+1;col++) {
System.out.print("*");
}
System.out.println();
}
sc.close();
row col : 1st
spaces before *
col : 2nd
number of *
0 4 1
1 3 3
2 2 5
3 1 7
4 0 9
55. Quiz review
No
i++
++i
Use and then increase
int i = 3;
int a = i++; // a = 3, i = 4
int b = ++a; // b = 4, a = 4
Increase and then use
56. Quiz review
maxCount 100
str
"Hello"
"HELLO"
• Whenever a new variable is declared, it is
added to STACK.
• Primitive data types are stored in STACK
• byte, short, int, long, float, double, boolean, char
• Other data types are stored in HEAP.
• String, Integer, Scanner, …
• Data in HEAP are not immediately
deleted but unlinked, and will be
garbage-collected.
57. public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
for(int row=1;row<=size;row++) {
for(int col=1;col<=size;col++) {
System.out.print(row*col + " ");
}
System.out.println();
}
}
58. Lab – 2D drawing
Two methods.
0,0 0,1 0,2 0,3 0,4
1,0 1,1 1,2 1,3 1,4
2,0 2,1 2,2 2,3 2,4
3,0 3,1 3,2 3,3 3,4
4,0 4,1 4,2 4,3 4,4
M1. Iterate pixels to paint
for (int i=0; i<size; i++) {
grid.setColor(i, i, Color.BLUE);
}
Intuitive and efficient
M2. Iterate every pixel, use if conditionals to
check pixels to paint
for (int row=0; row<size; row++) {
for (int col=0; col<size; col++) {
if(row==col) {
grid.setColor(row, col, Color.BLUE);
}
}
}
Complex and inefficient
BUT! More generalizable
59. Lab – 2D drawing
Two methods.
0,0 0,1 0,2 0,3 0,4
1,0 1,1 1,2 1,3 1,4
2,0 2,1 2,2 2,3 2,4
3,0 3,1 3,2 3,3 3,4
4,0 4,1 4,2 4,3 4,4
M2. Iterate every pixel, use if conditionals to
check pixels to paint
for (int row=0; row<size; row++) {
for (int col=0; col<size; col++) {
if(row!=col) {
grid.setColor(row, col, Color.BLUE);
}
}
}
You can simply inverse the conditional logic
M1. Iterate pixels to paint
Very difficult
Now you want to
paint all the pixels
except the diagonal
line.
66. public void commonFactor(int n1, int n2) {
for(int i=1; i<=min(n1,n2); i++) {
if(n1%i==0 && n2%i==0) {
System.out.println(i);
}
}
}
Finding common factors of two numbers
Common factors can divide both numbers.
E.g. Common factors of 9 and 12 1 and 3
Common factors of 24 and 78 1, 2, 3, and 6
67. compareTo method
String s1 = "aaa";
String s2 = "aac";
int k = s1.compareTo(s2); // k => -2
Compares s1 and s2 lexicographically.
Negative if s1 precedes s2
Positive if s1 follows s2
Zero if s1 is equal to s2
68. Get multiple words, find the first and the last words
1) Using while loop, keep asking words until "STOP"
2) Using compareTo, update the first and the last words
3) Print out
71. SquareGrid.java
ExampleDriver.java
• Prompt a shape question
• Create an empty grid
• Draw the requested shape
OperatorMaker.java
drawOp (SquareGrid grid, int symbol)
minus, plus, divide, multiply (SquareGrid grid)
You will change only these methods
Drawing shapes on 2D grid
72. Single loop for drawing a line
1) How can we get the middle row number?0
size : 7
3
0,0 0,1 0,2 0,3 0,4
1,0 1,1 1,2 1,3 1,4
2,0 2,1 2,2 2,3 2,4
3,0 3,1 3,2 3,3 3,4
4,0 4,1 4,2 4,3 4,4
int size = grid.getHt();
int midRow = size / 2;
2) How to draw a line?
• Iterate over columns (0 – 4)
• Paint the middle cell
for (int iCol=0; iCol<size; iCol++) {
grid.setColor(midRow, iCol, Color.BLUE);
}
73. Single loop for drawing a line
1) How can we get the middle column number?0,0 0,1 0,2 0,3 0,4
1,0 1,1 1,2 1,3 1,4
2,0 2,1 2,2 2,3 2,4
3,0 3,1 3,2 3,3 3,4
4,0 4,1 4,2 4,3 4,4
int size = grid.getWd();
int midCol = size / 2;
2) How to draw a line?
• Iterate over rows (0 – 4)
• Paint the middle cell
for (int iRow=0; iRow<size; iRow++) {
grid.setColor(iRow, midCol, Color.BLUE);
}
Notice that drawing horizontal and vertical lines are quite similar.
We just switched row and column variables.
74. Single loop for drawing a line
0,0 0,1 0,2 0,3 0,4
1,0 1,1 1,2 1,3 1,4
2,0 2,1 2,2 2,3 2,4
3,0 3,1 3,2 3,3 3,4
4,0 4,1 4,2 4,3 4,4
1) How to draw a line?
• Iterate over rows or columns (0-4)
• Paint diagonal cells.
for (int iRow=0; iRow<size; iRow++) {
grid.setColor(iRow, iRow, Color.BLUE);
}
76. Single loop for drawing a line
Iterating over
the columns,
paint the middle
cell.
Iterating over
the columns,
paint the middle
cell.
Iterating over
the rows,
paint the center
cell.
Iterating over
the columns,
paint i-th cell.
Draw Plus,
Divide,
and Divide (rotated).
80. Recap quiz #1.
Use specific technical keywords
e.g. What does CVS “do” for us?
1. Check out / Download the starter files
2. Store / Save multiple versions of the source code
share, deliver, get, access, connected people, ...
Penalties for inaccurate extra info
e.g. CVS runs our code and give us grades. -1 for incorrect extra info.
81.
82. String Class
String s = “hello”;
Create a new String object with an
initial value “hello”
String objects have many convenient methods,
upperS = s.toUpperCase(); // will set upperS to “HELLO”
whereIsl= s.indexOf(‘l’); // will find the position of the first ‘l’
newS = s.replace(‘e’,’a’); // will set newS to “hallo”
83. int type vs. Integer Class
int i=0;
Primitive data type
Integer i = 17;
Wrapper Class
don’t have much method provide methods
- convert to string
- generate hash codes
Faster A little slower
84. Static vs. Instance method
Intance methods need a sheep as a subject.
bob.eat();
bob.smileTo(clara);
bob.getPenNumber();
Static methods are about all the sheeps.
Sheep.getTotalSheep();
Sheep.removeAll();
Sheep.addSheep(‘evan’);
86. Flow of Control
1. Top-to-bottom statements
2. Method calls
3. Conditional statements
4. Iteration (loop)
for, while, ...
87. Two goals of iteration
1. Automation
Reduce repetition of code
System.out.println(“****”);
System.out.println(“****”);
System.out.println(“****”);
How can we reduce?
for(int i=0;i<3;i++) {
System.out.println(“****”);
}
2. Abstraction
Code for various situations
System.out.println(“****”);
How can we print n-number of “*”?
88. From manual & concrete to automatic & abstract
Level 1. Draw 30 by 10 rectangle (hard-coded)
System.out.println(“**********”);
System.out.println(“**********”);
System.out.println(“**********”);
... 27 more lines
Level 2. Draw 30 by 10 rectangle (single-loop)
Too many copy & paste. Hard to modify.
int row=0;
while(row<30) {
System.out.println(“**********”);
row++;
}
A little more compact.
Still too many * for each line.
89. From manual & concrete to automatic & abstract
Level 3. Draw 30 by 10 rectangle (nested-loop)
int row=0, col=0;
while(row<30) {
while(col<10) {
System.out.print(“*”);
}
System.out.println();
}
Much compact.
Cannot change # of row and col
Level 4. Draw height by width (nested-loop, parameterized)
int row=0, col=0;
int height=30, width=10;
while(row<height) {
while(col<width) {
System.out.print(“*”);
}
System.out.println();
}
Compact
Can draw any sized rectangle