This is the course notes of cs61b of the University of Berkeley.
Definations:
Object: A reposityory of data
Class: Type of object
Method: Procedure/function that operates on an object or class
e.g. additem: adds an item to any shoppinglist object
Inheritance: A class may inherit properties from a more general class
e.g. shoppinglist inherits from list the property of storing a sequence of items
Polymorphism: One method works on several classes, even if the classes need different implementations
e.g. “additem” method on every kind of list, though adding item to a shoppinglist is different from a shopping cart
Object-Oriented: Each object knows its own class&method
e.g. each shoppinglist&shoppingcart knows which implementation applies to it
Java:
Variables: must declare them and their type
python: x = 1
java: int x;
x = 1;
# line 1 in java code does 2 things:
# 1, allocate a chunk of memory to store an integer, type “int”
# 2, names variable “x”
2 ways to get classes:
1, use one defined by somebody else (standard java library)
2, define your own
variables also used to reference objects
myString []
myString = new String();
# 2 steps:
# “new String()” is a constructor, constructor call
# assignment “=” causes myString to reference the object
Java programs must be compiled before you can run them
Java program(.java) — javac → class files — java → answer
Objects & Constructors:
String s; //step 1: declare a string variable
s = new String(); //step 2, 3: construct empty string, assign it to sString s = new String(); //step 1, 2, 3 combined
s = “Yow!”
String constructors
1, String s2 = s; // now s&s2 reference same object2, s2 = new String(s); // makes a new string instead of reference
// Look where s points
// Follows reference to string object
// Read string
// Constructs new string copy the characters
// Makes s2 reference to new string3, String s;
String s2 = s;
s = “Yow!” // s2 is Null, s is “Yow!”
Constructors always have the same name as their class, except “stuffinquotes”
Methods:
s2 = s.touppercase();
String s3 = s2.concat(“!!”); // s3 = s2 + “!!”;
String s4 = “*”.concat(s2).concat(“*”); // s4 = “*” + s + “*”;
The object “Yow!” did not change. s2 changed
Strings are immutable
I/O classes & objects:
- Objects in System class for interacting with a user
- System.out is a PrintStream object that outputs to the screen
- System.in is an InputStream object that reads from the keyboard
- readLine is defined on bufferedReader objects
How do we construct a bufferedReader? With an InputStreamReader
— bufferedReader composes into entire lines of text
How do we construct an InputStreamReader? With an InputStream
— InputStreamReader composes into characters (2 bytes long)
How do we construct an InputStream? With Systemin
— InputStream reads raw data
look into online JAVA API to figure them out! — java.io
import java.io.*;
class SimpleIO {
public static void main(String[] arg) throws Exception{
BufferedReader keybd =
new BufferedReader(new InputStreamReader(System.in));
System.out.println(keybd.readLine());
}
}
To use Java libraries, other than java.lang, you “import” them.
java.io includes InputStreamReader, BufferedReader, etc.
Java program always begins at a method called “main”
Defining Classes:
Fields: Variables stored in objects.
aka instance variables
amanda.age -> field
amanda.introduce() -> method callclass Human{
public int age; // other classes can read the age
public String name;
public void introduce(){
System.out.println(“I’m “+name+” and I’m “+age+” years old.”);
}
public void copy(Human original){
age = original.age;
name = original.name;
}
public Human(String givenName){
age = 6;
name = givenName
}
public void change(int age){
String name = “Tom”;
this.age = age;
this.name = name;
}
public Human(){
numberOfHumans++;
}
}
Each human object can have different values of age, name.
Human amanda = new Human(“Amanda”);
Human amanda = new Human();
amanda.age = 6;
amanda.name = “Amanda”;
amanda.introduce();amanda.copy(rishi);amanda.change(11)
Default constructor takes no paramaters, does no initializing
e.g.
public Human(){}
Keyword:
The “this” keyword:
- “amanda.introduce()” implicitly passes an object(amanda) as a parameter called “this”
- YOU CANNOT change the value of “this”, will result Compile-time error.
The “static” keyword:
- static field: a single variable shared by a whole class of objects.
aka class variables
int kids = Human.numberOfHumans/4
- static method: doesnot implicitly pass an object as a parameter
System.in & System.out are static fields - main() is always static
public static void printHumans(){
System.out.println(numberOfHumans);
}
In a static method, there is no “this”! — compile error
Primitive Types:
- byte: 8-bit integer -128…127.
- short: 16-bit. -32,768…32.767
- int: 32-bit. -2,147,483,648…2,147,483,647
- long: 64-bit
- double: 64-bit floating point number 18.355
- float: 32-bit
- boolean: “true” or “false”
- char: 2-bit character
long x = 43L;
//double & float values must have a decimal point:
double y = 18.0;
float f = 43.9f;
char c = ‘h’;
java.lang library:
- Math class
x = Math.abs(y);
x = Math.sqrt(y);
— Integer class
int x = Integer.parseInt(“1984”);
— Double class
double d = Double.parseDouble(“3.14”);
Type conversion:
Integers can be assigned to variables of longer types
int i = 43;
long l = 43;
l = i; // ok
i = l; // compiler Error
i = (int)l; // force cast
Boolean Values:
and or not
&& || !
created by comparision operators “==”, “<”, “>”, “<=”. “>=”, “!=”
boolean x = 3==5; // x is false
Conditionals:
if (boolValue){
statements;
}
e.g.
boolen pass = score >= 75;
if (pass){
output(“You pass CS 61B”);
}
else{
//score < 75
output(“You are loser.”);
}
if-then-else clauses can be (1)Nested & (2)Daisy-chained
Find maximum of 3 numbers
if (x > y) {
if(x > z){
max = x;
}
else{
max = z;
}
else if (y > z){
max = y;
}
else{
max = z;
}
}
“swtich” statements
switch (month){
case 2:
days = 28;
break; //jumps to the end of “switch” statement
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
default:
days = 31;
break;
}
The “return” Keyword:
“return” causes a method to end immediately.
Control returns to the calling method.
prints numbers from 1 to x:
public static void ontToX(int x){
if (x < 1){
return;
}
oneToX(x — 1);
system.out.println(x)
}
// return is means by which a function returns a value.
function: method declared to return a non-void type.
can return expressions or valuespublic int daysInMonth(int month){
switch (month){
}
case 2:
return 28;
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}}
Loops:
“while” loops
public static boolean isPrime(int n){
int divisor = 2;
while (divisor < n){
if (n % divisor == 0){
return false;
}
divisor ++;
}
return true;
}
iteration: a pass through the loop body
if n <= 2, the loop body wont iterate even once.
“for” loops
for (initialize; condition; next){
statements;
}
equivalent to
initialzie;
while(condation){
statement;
next;
}
Arrays:
an object storing a numbered list of variables.
each is a primitive type of reference.
char[] c; // reference to array (any length) of characters.
c = new char[4];
c[0] = ‘b’;
…
c[3] = ‘e’;
c[4] = ‘s’; // run-time error
fields “c.length”
you can never assign a value to “length” (compile-time error)
Primes Revisited
sieve of eratosthenes
public static void printPrimes(int n){
boolean[] prime = new boolean[n+1];
int i;
for (i=2; i<=n; i++){
prime[i] = true; // prime until proven composite
}
for (int divisor=2; divisor * divisor <= n; divisor++){
if (prime[divisor]){
for (i = 2 * divisor; i <= n; i = i + divisor){
prime[i] = false;
}
}
}
for (i=2; i<=n; i++){
if (prime[i]){
system.out.print(“ “ + i);
}
}
}
Multi-dimensional Arrays:
2D array: array of reference to arrays
Pascal’s Triangle:
row i represents coefficients of (x + 1)**i
e.g. (x+1)⁴ = x⁴ + 4x³ + 6x² + 4x + 1
public static int[][] pascalTriangle(int n){
int[][] pt = new int[n][];
for (int i = 0; i < n; i++){
pt[i] = new int[i + 1];
pt[i][0] = 1;
for (int j = 1; j < i; j++){
pt[i][j] = pt[i-1][j-1] + pt[i-1][j]
}
p[i][i] = 1;
}
return pt;
}
Automatic Array Construction:
int[][] table = new int[x][y];
constructs an array of x references to arrays;
constructs x arrays of y ints;
Initializers:
Human[] b = {amanda, rishi, new Human(“Pob”)};
int[][] c = {{7,3,2}, {x}, {8,5,0,0}, {y+z,3}};
int[] a, b, c; // all reference arrays
int a[], b, c[][]; // a is 1d; c is 2d; b is not array
int[] a, b[]; // a is 1d; b is 2dd = {3, 7}; // compile-time error
int[] b[3]; // wrong
new int[3][]; //ok
new int[][3]; //wrong
Arrays of Objects:
when you construct array of objects, Java does not construct the objects.
String[] sentence = new String[3]; // null references
sentence[0] = “Word”; // point to a string “word”
sentence[2] = new String(); // point to an empty string
Main() parameter
class Echo{
public static void main(String[] args){ // list of command-line arguments
for (int i = 0; i < args.length; i++){
System.out.println(args[i]);
}
}
}
“do” loops:
“do” always executes loop body at least once
do {
s = keybd.readLine();
process(s);
} while (s.length() > 0);
The “break” and “continue” statements:
“break” exits the innermost loop or “switch” enclossing the “break”.
— 1
s = keybd.readLine();
while (s.length() > 0){
process(s);
s = keybd.readLine();
} // disadvantage: duplicated code
— 2
while (true){
s = keybd.readLine();
if (s.length() == 0){
break;
}
process(s);
} // disadvantage: obfuscated
— 3
for(int i = 0; i < 10; i++){
s = keybd.readLine();
if (s.length() == 0){
break;
}
process(s);
} // disadvantage: obfuscated
— 4
int i = 0;
do{
s = keybd.readLine();
if (s.length() > 0){
process(s);
}
i++;
} while ((i<10)&&(s.length()>0));
“continue”
— only applies to loops
— jumps to the end of loop body, but another iteration commences if loop condition satisfied
— 1
int i = 0;
while (i < 10){
if (condition(i)){
continue;
}
call(i);
i++;
}
— 2
for (int i = 0; i < 10; i++){ // i++ still execute!
if (condition(i)){
continue;
}
call(i);
}
CONSTANTS:
“final” keyword: value that can never be changed
bad:
if (month == 2){}
good:
public final static int February = 2;
…
if (month == February){}
for any array x, “x.length” is a “final” field