---
tags: fall 2018 cs61b
---
# Basic Java Syntax Review
[TOC]
## Class Architecture
* **Methods:** functions
* **Fields:** variables
* **Constructors:** intializes object's state
* Same as class name
```Java
class Student {
//fields
String major;
int GPA;
// default constructor: public Student() {}
// written constructor
public Student(String major, int GPA) {
this.major = major;
this.GPA = GPA;
}
//Methods
public declareMajor() {
System.out.println(major);
}
}
```
## Primitive Types
**Copied from CS 61BL Summer 2018 Lab 2:**

### Declaring primitive types without intialization
``` Java
int a; // 0
double b; // 0.0d
long c; // 0
char d; // '\u0000'
boolean e; //false
```
## Classes, Objects, and References
Quoted from [StackOverFlow](https://stackoverflow.com/questions/9224517/what-are-classes-references-and-objects):
> * a **class** is like the blueprint for a house. Using this blueprint, you can build as many houses as you like.
> * each house you build (or instantiate, in OO lingo) is an **object**, also known as an **instance**.
> * each house also has an address, of course. If you want to tell someone where the house is, you give them a card with the address written on it. That card is the object's **reference**.
> * If you want to visit the house, you look at the address written on the card. This is called dereferencing.
### Declaring objects without intialization
All objects that are declared, but not intialized are `null`.
``` Java
String j; //null
Object i; //null
String[] s; //null
String[] strArray = new String[3]; //[null, null, null]
```
## Autoboxing
Some data structures can only store objects, not primitive types. An example is an`ArrayList`. However, we still want some way to store the primitive types we have. Therefore, Java utilizes **autoboxing** in which we create a **wrapper** type for our primitive type.

Referenced from Hilfinger's [slides](https://inst.eecs.berkeley.edu/~cs61b/fa18/materials/lectures/lect8.pdf)
### Boxing
```Java
int j = 3; //j is a primitive type
Integer i = new Integer(j); //i is an object
```
### Unboxing
```Java
int x = i.intValue();
```
Don't worry about unboxing. Unboxing is automatic so the code above is never usually used.
## '==' vs .equals
Only primitive types work with `==` comparison.
```Java
int i = 5;
int j = 5;
i == j; //returns true
```
`==` compares object references. When an object is instantiated (even if it seems to have the same components as another object), it will have a new memory address.
`equals` is a method inside the object's class that overrides Java's default comparison method. It allows you to compare the objects based on their components rather than their memory addresses.
```Java
String h = 'hi';
String j = 'hi';
h == j; //returns false
h.equals(j); //returns true
```
## 'Static' Keyword
You can have static fields, methods, and classes (out ot scope). When a field or method is static, it can be applied to the general class. If a field or method is non-static, it is applied to all instances. Let's look at the example below:
```Java
class CalStudent {
double currentGPA; //non-static
static double maxGPA = 4.0; //static
//non-static method
public double getCurrentGPA() {
return currentGPA;
}
//static method
public static double getMaxGPA() {
return maxGPA;
}
//non-static method
public double getCurrentGPA() {
return currentGPA;
}
//constructor
public CalStudent(double GPA) {
currentGPA = GPA;
}
}
```
We use the class name to call static methods and return static fields.
```Java
CalStudent.getMaxGPA(); // returns 4.0
CalStudent.maxGPA; //returns 4.0
```
We use an instance object to call non-static methods and return non-static fields.
```Java
CalStudent bob = new CalStudent(3.5);
bob.getCurrentGPA(); //returns 3.5
bob.currentGPA; //returns 3.5
```
#### Can a constructor be static?
No. It's a common misconception. Remember a constructor is *not* a method despite having a similar structure.
#### Can we call static fields/methods with an instance object?
Yes! The following code will work. After all, all individual students still have the same max GPA.
```Java
CalStudent bob = new CalStudent(3.5);
bob.getmaxGPA(); //returns 4.0
bob.maxGPA; //returns 4.0
```
#### Can we call non-static fields/methods with a static object?
No! It would make no sense to ask the general CalStudent for a current GPA because we all have different GPA's.
```Java
CalStudent.getCurrentGPA(); //compile-time error
```
More specifically, we get the error below.
```Java
Cannot access non-static field in static method main
```
#### Why have static and non-static fields and methods in the first place?
It leads to less repetition of code. A common acronym in programming is DRY: Do not Repeat Yourself. If we wanted to instantly update a field for multiple instances, we could do it through `static` keywords.
**Example:** We write a class that represents babies born **last year**. As a result, they all have the same age.
```Java
class Baby {
public static int age = 1;
public void ageOneYear() {
age++;
}
}
```
Suppose one year has passed and we want the time change to reflect in all of the individual babies. The static keyword allows us to update the age all at once.
```Java
Baby sally = new Baby();
sally.age; //returns 1
Baby billy = new Baby();
billy.age; //returns 1
sally.ageOneYear(); //1 year has passed
sally.age; //returns 2
billy.age; //returns 2
```
#### When to use static vs non-static?
Keep it static if we don't want to access a non-static field or method.
## Constructors
Constructors intialize the objects state and create instance objects. Each time an object is created using 'new', the constructor is being called.
If a constructor isn't written in the class, we use the default `Candy()` constructor to intialize an object.
```Java
class Candy {
String color;
boolean soft;
//default constructor
public Candy() {}
//written constructors replace the default constructor
//multiple constructors can exist as long
//as they have a different number of arguments +
//different types of arguments
public Candy(String colour, boolean softCandy) {
color = colour;
soft = softCandy;
}
public Candy(boolean softCandy, String colour) {
color = colour;
soft = softCandy;
}
public Candy(boolean hard) {
soft = !hard;
}
}
```
If a written constructor replaces the default constructor, the default constructor cannot be called unless a constructor with the same structure is written in as well.
## Scoping and Variable Lookup
In Java, variables have **lookup rules** that follow the checklist below:
1. Local Scope (located in the code block)
2. Instance and Class
3. Superclass
#### Usage of 'this' keyword
1. If a parameter or variable in the local scope has the same name as a field: use `this.variableName` to assign something to the field
2. A method requires you to utilize the current instance object
```Java
class Fruit {
public boolean isTasty;
public String color;
public Fruit(boolean isTasty, String color) {
//isTasty = isTasty;
//color = color;
//The lines above only affect the variables in the local scope
//adding 'this' allows us to assign
//the values passed in to the class fields
this.isTasty = isTasty;
this.color = color;
}
public Fruit growFruit(Fruit f) {
return new Fruit(f.isTasty, f.color);
}
//method requires current instance object
public Fruit cloneFruit() {
return makeFruit(this);
}
}
```
## Access Modifiers
Access modifiers limit the scope of the field or method they're used on. **Note:** If there is no modifier, the scope defaults to **package-private**.

:::info
Package refers to a group of related classes. Files contained in the same folder are considered to be in the same package.
:::