Examples of values:
A temperature, a name, a list of test scores, a student record
Types of values:
int, double, String, List, Point, Student
Definition: A variable is a value container
Definition: An expression is a program fragment that produces a value when evaluated.
Examples of expressions:
6 * 7 + 2 * 3
"Bat" + "Man"
15 % 4
Declaring variables:
int exam1 = 78;
int exam2 = 82;
int exam3 = 90;
int average = (exam1 + exam2 + exam3)/3; // = 250/3 = 83
double radius = 10;
double pi = 3.13;
double area = pi * radius * radius;
String planet1 = "Mercury", planet2 = "Venus", planet3 = "Earth";
Principle: Variable names should suggest their interpretation
/*
This is a
multi-line comment
*/
// this is a one line comment
Definition: The value contained in a variable can be changed using an assignment command.
Examples:
radius = 12;
exam1 = exam2;
exam2 = exam2 + 2; // no change to exam1
Definition: An object is a value that contains variables (fields) and methods (functions). The type of an object is called a class.
Objects are good for representing things that have state and behavior.
Demo: Use BlueJ to create a class called Demo1. Create several instances of this class and invoke the sample method. Modify the class by adding a method for changing the instance variable.
Demo: Use BlueJ to create a simple calculator that accumulates the result in an instance variable.
Demo: Use BlueJ to create a calculator that computes well known formulas from Math and Physics such as areas, distances, speeds, forces, etc.
A
class is a template for creating objects. For example:
public class Student {
private String name;
private int id;
private double gpa;
// constructors:
public Student() {
name = "unknown";
id = 0;
gpa = 0;
}
public Student(String initName, int initID, double initGPA) {
name = initName;
id = initID;
gpa = initGPA;
}
// getters:
public String getName() { return name; }
public int getID()
{ return id; }
public double getGPA() { return gpa; }
// setters:
public void setGPA(double newGPA) {
// if authorized?
gpa = newGPA;
}
} // end of class Student
We create student objects using the student constructors and the new operator:
Student
student1 = new Student(),
student2 = new Student("Jones", 321, 2.0),
student3 = new Student("Smith", 555, 3.5);
Definition: The memory address of an object is called a reference. For example:
Student student4 = student2;
student2.setGPA(4.0); // student2.gpa = 4.0 also!