prev: [[Basic_Java]]
next: [[61B_Part_2_LinkList]]

Compiling system

Java source code –> (compiler) .class –> (interpreter) running file

why .class?

  1. no need to open sourcecode

  2. easier for computer to run

(more to explain in 61C)

Java compiling

1
2
javac Dog.java
java Dog

Class in Java

in java, “self” in python is “this”.

Static vs. Non-Static Methods

1
2
3
4
5
public class Dog {
public static void makeNoise() {
System.out.println("Bark!");
}
}

Error!

(There must be main classes)

instances

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Dog {
public int weightInPounds;

public void makeNoise() {
if (weightInPounds < 10) {
System.out.println("yipyipyip!");
} else if (weightInPounds < 30) {
System.out.println("bark. bark.");
} else {
System.out.println("woof!");
}
}
}

in the main function:

1
2
3
4
5
6
7
8
public class DogLauncher {
public static void main(String[] args) {
Dog d;
d = new Dog(); /** new is a way to introduce 实例 */
d.weightInPounds = 20;
d.makeNoise();
}
}

another way to build the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Dog {
public int weightInPounds; /** varibles */

public Dog(int w) { /** constructor */
weightInPounds = w;
}

public void makeNoise() { /** non-static method or instance method*/
if (weightInPounds < 10) {
System.out.println("yipyipyip!");
} else if (weightInPounds < 30) {
System.out.println("bark. bark.");
} else {
System.out.println("woof!");
}
}
}

(very similar to __init__ method in Python)

(then you can: Dog d = new Dog(21); instead of Dog d = new dog(); d.weightInPounds = 21;)

arrays

you are also able to apply arrays in dog Class, like Dog[] dogs = new dog[2]

Why static methods?

some methods are never 变成实例.

static methods usage: Dog.method()

(never use this in non-static method!!!)

Lecture 2 testing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class TestSort {
/** Tests the sort method of the Sort class. */
public static void testSort() {
String[] input = {"i", "have", "an", "egg"};
String[] expected = {"an", "egg", "have", "i"};
Sort.sort(input);
for (int i = 0; i < input.length; i += 1) {
if (!input[i].equals(expected[i])) {
System.out.println("Mismatch in position " + i + ", expected: " + expected + ", but got: " + input[i] + ".");
break;
}
}
}

public static void main(String[] args) {
testSort();
}
}

another method:(junit)

1
2
3
4
5
6
7
8
9
10
@org.junit.Test
public void testSort() {
String[] input = {"i", "have", "an", "egg"};
String[] expected = {"an", "egg", "have", "i"};
Sort.sort(input);
org.junit.Assert.assertArrayEquals(expected, input);
}
public void sort(String[] input){
...
}

in java, no a[1:]!!!

to avoid using org.junit.Assert. and @org.junit.Test, you can import them like:

1
2
3
import org.junit.Test; /** then just @Test */
import static org.junit.Assert.*;
...

lecture 3-5

bits

1
2
3
4
Walrus a = new Walrus(1000, 8.3);
Walrus b;
b = a;
b.weight = 5;

a’s weight is 5!

However:

1
2
3
4
int a = 1000;
int b;
b = a;
b = 5;

b = 5, a = 1000!

why different?

In Walrus, a and b points to the same index of value

However, int is different.

In computer, data stored in memory. 8 java primary data types are 8 ways to interpret them.(byte, short, int, long, float, double, boolean, char)

varible declearation

declear a varible: 先申请一个box,然后 create a interal table that match each value into the location

for this primary datatypes: varibles just match a box with sth. in it.

golden rule of equals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

#### class instantitations

(the 9th basic type in Java: arrow)

when we first call a expression:

Java first allocates a box of bits for each instance variable of the class and fills them with a default value (e.g. 0, null).

The constructor then usually fills every such box with some other value.

Example(实例): record the address(64bit in java) of the classes (```new``` return the address)

| weight | 1000 |
|-------------|----------------|
| tuskSize | 8.3 |

```Walrus a;``` just define a box with 64 bits

```b = a;``` make the arrow in the box b the same as a. (just pass the bits into the new scope)

Arrays are also objects!

## Lab6: File systems in Java
### Current working dictionary
 the directory from where you execute that Java program
use `System.getProperty("user.dir")` to access
in Bash or the terminal, `cwd` would give you the CWD.
### Absolute & Relative Paths
`.` refers to CWD.
`..` refers to the parent of CWD.
parent's parent dictionary: `cd ../..`
### File & Directory Manipulation in Java
#### files
DO NOT create the new file. Just say: when we changed `f`, we refers to the `dummy.txt`.
```java
File f = new File("dummy.txt");

create the new file:

1
f.createNewFile();

check if dummy.txt exists:

1
f.exists()

Writing the file in java is pretty ugly, so the class Utils.java was applied in this lab and Gitlet.
For example, write a string to the file:

1
Utils.writeContents(f, "Hello World");

Directories

it also represents as File objects.

1
File d = new File("dummy");

to create:

1
d.mkdir();

Serializable

How to save more complicated state in our program? such as the Model object in our 2048 program?
we can use java.io.Serializable interface to translate an object to a series of bytes that can then be stored in the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.io.Serializable;

public class Model implements Serializable {
...
}
Model m = ....;
File outFile = new File(saveFileName);
try {
ObjectOutputStream out =
new ObjectOutputStream(new FileOutputStream(outFile));
out.writeObject(m);
out.close();
} catch (IOException excp) {
...
}

serialize:

1
2
3
4
5
Model m;
File outFile = new File(saveFileName);

// Serializing the Model object
writeObject(outFile, m);

deserialize:

1
2
3
4
5
Model m;
File inFile = new File(saveFileName);

// Deserializing the Model object
m = readObject(inFile, Model.class);