SlideShare una empresa de Scribd logo
1 de 92
Nov 17.
Lab17
Recap the quiz
http://www.slideshare.net/takyeon
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
array
0 0
0
CAUGHT
FINAL
PROG END
public static int[] buildN(int n) {
int[] arr = new int[n];
for(int i=0;i<n;i++) {
arr[i] = i+1;
}
return arr;
}
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
packages
A package is a grouping of related types (classes, interfaces, enumerations, and
annotation).
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
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
/* 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.
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
Nov 10.
Lab16
Recap the quiz
http://www.slideshare.net/takyeon
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?
! 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.
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
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.
private int currFloor;
public Elevator(int currFloorIn) {
if(floorNum<1) { currFloor = 1; }
else if(floorNum>5) { currFloor = 5; }
else { currFloor=floorNum; }
}
public void setCurrFloor(int floorNum) {
if(floorNum<1) { currFloor = 1; }
else if(floorNum>5) { currFloor = 5; }
else { currFloor=floorNum; }
}
public int getCurrFloor() {
return currFloor;
}
STACK HEAP
valA 8
21
valc
valB
20
This is because valA, valB, valC are
Integer objects not primitive data
type int.
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.
Nov 5.
Lab15.
Exceptions
http://www.slideshare.net/takyeon
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"
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
RuntimeException e = new RuntimeException("ahaha");
throw e;
// same thing
throw new RuntimeException("Ooops.");
Nov 3.
Lab14.
Ternary operator (a>b ? a:b)
Switch
http://www.slideshare.net/takyeon
Disclaimer
Everything I told in the lab sessions
that are not taught in lectures
are optional.
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).
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"
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
Oct 29th
Lab13.
Mutability
Exception handling
Unit test
http://www.slideshare.net/takyeon
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.
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.
…
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.
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.
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.
Oct 27th
Lab12.
String methods
Debugging
http://www.slideshare.net/takyeon
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.
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
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.
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)
http://codingbat.com/java
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
Debugging
Conditional breakpoint
Oct 20th
Lab11.
Mid-term #1 review
Javadoc
http://www.slideshare.net/takyeon
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.
- 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
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
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..
Oct 13th
Lab09.
Stack, Heap, and Metaspace
http://www.slideshare.net/takyeon
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.
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
int x,y;
x=2; y=5;
System.out.println(x++ * y++);
System.out.println(++x * ++y);
System.out.println(++x * y++);
System.out.println(x++ * ++y);
System.out.println("1 + 2 = " + 1 + 2);
System.out.println("1 + 2 = " + (1 + 2));
1 + 2 = 12
1 + 2 = 3
year % 4 == 0 && year % 100 != 0 || year % 400 == 0
((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)
Any question?
Oct 8th
Lab08.
Quiz review
Triangle and Stripes
http://www.slideshare.net/takyeon
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
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.
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();
}
}
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
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.
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
More examples.
row>2
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
row%2 == 1
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
col%2 == 1
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
(row-col)>=0
0 -1 -2 -3 -4
1 0 -1 -2 -3
2 1 0 -1 -2
3 2 1 0 -1
4 3 2 1 0
row-col
Diagonal shapes
require both row
and col
Linear shapes require either row
or col.
Transformation > Move
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
(row+1, col)
(row+1)-col >= 0
-1 -2 -3 -4 -5
0 -1 -2 -3 -4
1 0 -1 -2 -3
2 1 0 -1 -2
3 2 1 0 -1
(row+1)-col
0,1 0,2 0,3 0,4 0,5
1,1 1,2 1,3 1,4 1,5
2,1 2,2 2,3 2,4 2,5
3,1 3,2 3,3 3,4 3,5
4,1 4,2 4,3 4,4 4,5
To move a shape to left by 1
pixel,
replace "row" with "row+1"
Transformation > Horizontal Flip.
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
0,4 0,3 0,2 0,1 0,0
1,4 1,3 1,2 1,1 1,0
2,4 2,3 2,2 2,1 2,0
3,4 3,3 3,2 3,1 3,0
4,4 4,3 4,2 4,1 4,0
Horizontal
Flip
(row, 4-col)
(row-(4-col))>=0
-4 -3 -2 -1 0
-3 -2 -1 0 1
-2 -1 0 1 2
-1 0 1 2 3
0 1 2 3 4
row-(4-col)
To flip a shape, multiple row or
column by -1, and add size
-col
size-col
col
col
4 := size of the shape – 1
Why -1? Because our row and
col index started from 0.
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
Vertical
Flip
(4-row, col)
(4-row)-col >= 0
4 3 2 1 0
3 2 1 0 -1
2 1 0 -1 -2
1 0 -1 -2 -3
0 -1 -2 -3 -4
(4-row)-col
4,0 4,1 4,2 4,3 4,4
3,0 3,1 3,2 3,3 3,4
2,0 2,1 2,2 2,3 2,4
1,0 1,1 1,2 1,3 1,4
0,0 0,1 0,2 0,3 0,4
Transformation > Vertical Flip.
(row-col)>=0
0 -1 -2 -3 -4
1 0 -1 -2 -3
2 1 0 -1 -2
3 2 1 0 -1
4 3 2 1 0
(row-(4-col))>=0
-4 -3 -2 -1 0
-3 -2 -1 0 1
-2 -1 0 1 2
-1 0 1 2 3
0 1 2 3 4
Horizontal
Flip
(4-row)-col >= 0
4 3 2 1 0
3 2 1 0 -1
2 1 0 -1 -2
1 0 -1 -2 -3
0 -1 -2 -3 -4
Vertical flip
(4-row)-(4-col) >= 0
0 1 2 3 4
-1 0 1 2 3
-2 -1 0 1 2
-3 -2 -1 0 1
-4 -3 -2 -1 0
Horizontal
Flip
col-row >= 0
Vertical flip
Oct 6th
Lab07.
Loop applications
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
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
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
Oct 1st
Lab06.
2D drawing
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
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);
}
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.
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);
}
for (int iCol=0; iCol<size; iCol++) {
grid.setColor(midRow, iCol, Color.BLUE);
}
for (int iRow=0; iRow<size; iRow++) {
grid.setColor(iRow, midCol, Color.BLUE);
}
for (int iRow=0; iRow<size; iRow++) {
grid.setColor(iRow, iRow, Color.BLUE);
}
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
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
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
for (int iCol=0; iCol<size; iCol++) {
grid.setColor(iCol, iCol, Color.BLUE);
}
or
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).
Sep 29th
Lab05.
1. Recap the quiz #1
2. String Class
3. static vs. instance method
Recap quiz #1.
PRINT your names in
the grade server.
NO nicknames.
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.
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”
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
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’);
Sep 24th
Lab04.
Loop
Flow of Control
1. Top-to-bottom statements
2. Method calls
3. Conditional statements
4. Iteration (loop)
for, while, ...
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 “*”?
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.
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
iterartor
line 1
0
value
line 2
0
target
line 4
answer
line 1
1
i
line 1
1
j
line 1
0
131 Lab slides (all in one)

Más contenido relacionado

La actualidad más candente

Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Bryan O'Sullivan
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Philip Schwarz
 
Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
 
Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Bryan O'Sullivan
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Bryan O'Sullivan
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Philip Schwarz
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Bryan O'Sullivan
 
Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Bryan O'Sullivan
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskellJongsoo Lee
 

La actualidad más candente (20)

Python
PythonPython
Python
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Python Cheat Sheet
Python Cheat SheetPython Cheat Sheet
Python Cheat Sheet
 
Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
 
Enumerable
EnumerableEnumerable
Enumerable
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Real World Haskell: Lecture 7
Real World Haskell: Lecture 7
 
C q 3
C q 3C q 3
C q 3
 
Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 

Similar a 131 Lab slides (all in one)

Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdffreddysarabia1
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................suchitrapoojari984
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework HelpC++ Homework Help
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type PatternsSimon Ritter
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Dharma Kshetri
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptxadityaraj7711
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdffantasiatheoutofthef
 
LeetCode April Coding Challenge
LeetCode April Coding ChallengeLeetCode April Coding Challenge
LeetCode April Coding ChallengeSunil Yadav
 
ObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxvannagoforth
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfinfo309708
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdfakkhan101
 

Similar a 131 Lab slides (all in one) (20)

Lezione03
Lezione03Lezione03
Lezione03
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
 
Lec2
Lec2Lec2
Lec2
 
LeetCode April Coding Challenge
LeetCode April Coding ChallengeLeetCode April Coding Challenge
LeetCode April Coding Challenge
 
CHAPTER 5
CHAPTER 5CHAPTER 5
CHAPTER 5
 
ObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docx
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
 

Más de Tak Lee

Oct13' ----
Oct13' ----Oct13' ----
Oct13' ----Tak Lee
 
Oct8 - 131 slid
Oct8 - 131 slidOct8 - 131 slid
Oct8 - 131 slidTak Lee
 
Umd신입생환영회 어디갈까
Umd신입생환영회 어디갈까Umd신입생환영회 어디갈까
Umd신입생환영회 어디갈까Tak Lee
 
Lab slides - hardware and software
Lab slides - hardware and softwareLab slides - hardware and software
Lab slides - hardware and softwareTak Lee
 
Interface project dejavu_3
Interface project dejavu_3Interface project dejavu_3
Interface project dejavu_3Tak Lee
 

Más de Tak Lee (6)

Oct27
Oct27Oct27
Oct27
 
Oct13' ----
Oct13' ----Oct13' ----
Oct13' ----
 
Oct8 - 131 slid
Oct8 - 131 slidOct8 - 131 slid
Oct8 - 131 slid
 
Umd신입생환영회 어디갈까
Umd신입생환영회 어디갈까Umd신입생환영회 어디갈까
Umd신입생환영회 어디갈까
 
Lab slides - hardware and software
Lab slides - hardware and softwareLab slides - hardware and software
Lab slides - hardware and software
 
Interface project dejavu_3
Interface project dejavu_3Interface project dejavu_3
Interface project dejavu_3
 

Último

Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 

Último (20)

Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 

131 Lab slides (all in one)

  • 1. Nov 17. Lab17 Recap the quiz http://www.slideshare.net/takyeon
  • 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
  • 3.
  • 5. public static int[] buildN(int n) { int[] arr = new int[n]; for(int i=0;i<n;i++) { arr[i] = i+1; } return arr; }
  • 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
  • 12. Nov 10. Lab16 Recap the quiz http://www.slideshare.net/takyeon
  • 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.
  • 17. private int currFloor; public Elevator(int currFloorIn) { if(floorNum<1) { currFloor = 1; } else if(floorNum>5) { currFloor = 5; } else { currFloor=floorNum; } } public void setCurrFloor(int floorNum) { if(floorNum<1) { currFloor = 1; } else if(floorNum>5) { currFloor = 5; } else { currFloor=floorNum; } } public int getCurrFloor() { return currFloor; }
  • 18. STACK HEAP valA 8 21 valc valB 20 This is because valA, valB, valC are Integer objects not primitive data type int.
  • 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.");
  • 24. Nov 3. Lab14. Ternary operator (a>b ? a:b) Switch http://www.slideshare.net/takyeon
  • 25. Disclaimer Everything I told in the lab sessions that are not taught in lectures are optional.
  • 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
  • 29.
  • 30. Oct 29th Lab13. Mutability Exception handling Unit test http://www.slideshare.net/takyeon
  • 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
  • 44. Oct 20th Lab11. Mid-term #1 review Javadoc http://www.slideshare.net/takyeon
  • 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..
  • 49. Oct 13th Lab09. Stack, Heap, and Metaspace http://www.slideshare.net/takyeon
  • 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
  • 52. int x,y; x=2; y=5; System.out.println(x++ * y++); System.out.println(++x * ++y); System.out.println(++x * y++); System.out.println(x++ * ++y); System.out.println("1 + 2 = " + 1 + 2); System.out.println("1 + 2 = " + (1 + 2)); 1 + 2 = 12 1 + 2 = 3 year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)
  • 54. Oct 8th Lab08. Quiz review Triangle and Stripes http://www.slideshare.net/takyeon
  • 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.
  • 60. 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 More examples. row>2 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 row%2 == 1 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 col%2 == 1 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 (row-col)>=0 0 -1 -2 -3 -4 1 0 -1 -2 -3 2 1 0 -1 -2 3 2 1 0 -1 4 3 2 1 0 row-col Diagonal shapes require both row and col Linear shapes require either row or col.
  • 61. Transformation > Move 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 (row+1, col) (row+1)-col >= 0 -1 -2 -3 -4 -5 0 -1 -2 -3 -4 1 0 -1 -2 -3 2 1 0 -1 -2 3 2 1 0 -1 (row+1)-col 0,1 0,2 0,3 0,4 0,5 1,1 1,2 1,3 1,4 1,5 2,1 2,2 2,3 2,4 2,5 3,1 3,2 3,3 3,4 3,5 4,1 4,2 4,3 4,4 4,5 To move a shape to left by 1 pixel, replace "row" with "row+1"
  • 62. Transformation > Horizontal Flip. 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 0,4 0,3 0,2 0,1 0,0 1,4 1,3 1,2 1,1 1,0 2,4 2,3 2,2 2,1 2,0 3,4 3,3 3,2 3,1 3,0 4,4 4,3 4,2 4,1 4,0 Horizontal Flip (row, 4-col) (row-(4-col))>=0 -4 -3 -2 -1 0 -3 -2 -1 0 1 -2 -1 0 1 2 -1 0 1 2 3 0 1 2 3 4 row-(4-col) To flip a shape, multiple row or column by -1, and add size -col size-col col col 4 := size of the shape – 1 Why -1? Because our row and col index started from 0.
  • 63. 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 Vertical Flip (4-row, col) (4-row)-col >= 0 4 3 2 1 0 3 2 1 0 -1 2 1 0 -1 -2 1 0 -1 -2 -3 0 -1 -2 -3 -4 (4-row)-col 4,0 4,1 4,2 4,3 4,4 3,0 3,1 3,2 3,3 3,4 2,0 2,1 2,2 2,3 2,4 1,0 1,1 1,2 1,3 1,4 0,0 0,1 0,2 0,3 0,4 Transformation > Vertical Flip.
  • 64. (row-col)>=0 0 -1 -2 -3 -4 1 0 -1 -2 -3 2 1 0 -1 -2 3 2 1 0 -1 4 3 2 1 0 (row-(4-col))>=0 -4 -3 -2 -1 0 -3 -2 -1 0 1 -2 -1 0 1 2 -1 0 1 2 3 0 1 2 3 4 Horizontal Flip (4-row)-col >= 0 4 3 2 1 0 3 2 1 0 -1 2 1 0 -1 -2 1 0 -1 -2 -3 0 -1 -2 -3 -4 Vertical flip (4-row)-(4-col) >= 0 0 1 2 3 4 -1 0 1 2 3 -2 -1 0 1 2 -3 -2 -1 0 1 -4 -3 -2 -1 0 Horizontal Flip col-row >= 0 Vertical flip
  • 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
  • 69.
  • 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); }
  • 75. for (int iCol=0; iCol<size; iCol++) { grid.setColor(midRow, iCol, Color.BLUE); } for (int iRow=0; iRow<size; iRow++) { grid.setColor(iRow, midCol, Color.BLUE); } for (int iRow=0; iRow<size; iRow++) { grid.setColor(iRow, iRow, Color.BLUE); } 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 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 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 for (int iCol=0; iCol<size; iCol++) { grid.setColor(iCol, iCol, Color.BLUE); } or
  • 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).
  • 77.
  • 78. Sep 29th Lab05. 1. Recap the quiz #1 2. String Class 3. static vs. instance method
  • 79. Recap quiz #1. PRINT your names in the grade server. NO nicknames.
  • 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