3.3 Lecture 1
Introduction to Systems Programming - Lectures - Class 1.pdf
Important Terminology
- Program: A set of instructions that can be executed, i.e., the code you write.
- Algorithm: A finite set of instructions that can be executed.
- Executable: A file with a specific format, e.g., ELF, which contains a compiled program that can be executed.
- Process: An instance of an executable that is being executed.
It’s common to see "Program", "Executable", and "Algorithm" used interchangeably.
Example (Division)
Theorem: Given n
and d
with d ≠ 0
, there exist q
and r
such that:
-
n = (d × q) + r
-
0 ≤ r < d
Algorithm: Given n
and d
with d ≠ 0
, find q
and r
such that:
-
Start with
q
at0
. -
Subtract
d
fromn
:
a. If the result is negative, restoren
and setr
asn
.
b. If the result is positive, increaseq
by1
, go back to step 2. -
Return
q
andr
.
Example (Division)
int divide(int n, int d) {
int q = 0;
int r = n;
while (r >= d) {
r = r - d;
q++;
}
return q;
}
Is this a program? Yes
Is this an algorithm? It depends, but yes
Classes and Objects
Objects represent entities from the real world, in a specific problem domain, and even "internal" software entities. And classes represent all objects of a specific kind.
Some Examples:
-
A class representing all bicycles, and a particular red bicycle would be an object of that class.
-
A class representing all students, and a particular student called "Arthur Dent" with ID number "42" would be an object of that class.
-
A class representing all possible calculators, and a particular calculator that we are using would be an object of that class.
Methods and Parameters
Once we have an object of a class, we need to be able to do something with it; if not, then it’s completely useless. How do we do it? We apply an operation to the object, most commonly known as methods.
In many cases, we want to apply an operation/method to an object which involves one or more arguments.
Methods can also return a value.
Where are methods defined?
Inside classes (we will talk about it later)
Data Types
A Data Type defines a set of values and operations that can be applied to those values.
Examples:
-
int:
set of all integer values. -
boolean:
set of boolean values (truth values). -
float:
set of real values. -
char:
set of all character values (ASCII).
State of an Object
Each object has attributes/fields Mutable values that define relevant information of the objects
A class defined which attributes/fields will objects of that class will have
Source Code
Classes are a way of representing and organizing computer programs.
Classes are written in source code (Java code), and define how objects will be represented and how they will behave.
Java code is compiled into a low-level language called Bytecode that will be executed by a Java Virtual Machine.
Roadmap of Topics
- Fields (also known as attributes)
- Constructors
- Methods
- Parameters
- Assignment
Ticket Machine - An External View
- By interacting with an object, we can have clues of what is the behavior of the object.
- By examining the internal definition of an object, we can have an insight about how such behavior is provided, or implemented.
- All Java classes have a consistent internal structure.
Structure of a Class
Fields
- Class fields define the internal values an object will hold.
- In BlueJ, one can use the Inspect option to see the fields of an object.
- Class fields define the state space of an object.
public class TicketMachine {
private int price;
private int balance;
private int total;
// Additional details omitted.
}
Constructors
- Class constructors are responsible for initializing objects.
- They have the same name as the name of the class.
- They take care of storing initial values into fields.
- Frequently, constructors receive external values (parameters) to perform the initialization.
- Note In Java, all fields are automatically initialized to a default value if they are not explicitly initialized.
For integer fields, this default value is zero. So, strictly speaking, we could have done without setting balance and total to zero, relying on the default value to give us the same result.
However, we prefer to write the explicit assignments anyway.
public TicketMachine(int ticketCost) {
price = ticketCost;
balance = 0;
total = 0;
}
Passing Data via Parameters
- Parameters are a kind of variable.
- They take care of passing data from the "client" of the method to the method itself.
- As opposed to fields, parameters are only accessible within the method’s body.
Assignment
- Values are stored in fields (and other kinds of variables) using assignment statements.
- A variable can hold a unique value.
- The previous value is lost when a variable is assigned to.
- E.g.:
price = ticketCost;
The expression is evaluated, and the result is stored in the variablevariable = expression;
* The type of the expression and the type of the variable must be compatible!
Methods
- The methods of a class implement the behavior of the objects of the class.
- Methods have a structure, consisting of a header and a body.
- The header defines the signature of the method.
- The body comprises the sentences that implement the method.
Methods (Command - Query Separation)
A method either represents a command which changes the state of the object in which it is invoked ( ). Or represents a query , which only returns data associated with the object in which it has been invoked.( ) Printing is considered as a command.
The query-command separation principle establish that a method must either be a command and not return any value; or a query and only return a value without modifying the state of the object.
public void changePrice(int newPrice) {
price = newPrice;
}
public int getPrice() {
return price;
}
Quick Quiz!
There are 5 errors
public class CokeMachine {
private !!int!! price;
public CokeMachine() {
price = 300!!;!!
}
public int getPrice!!()!! {
return !!p!!rice;
}
!!}!!
The method name and the parameter types of a method are called its signature. They provide the information needed to invoke that method.
Codepad
We can use code pad mode in BlueJ
Create an new object: <class name> <object name> = new <class name>;
Call a method to object: <object name>.<method name>(<parameters if needed>);
PascalCase should be used on Class name like PascalCase
camelCase should be used on Method name and variable name like camelCase
Return value and objects
The header of getName
(as shown in the object’s pop-up menu) is defined as String getName()
The word String
before the method name specifies the return type.
In this case, it states that calling this method will return a result of type String
.
The header of changeName
states: void changeName(String replacementName)
The word void indicates that this method does not return any result.
Objects can be passed as parameters to methods of other objects. In the case where a method expects an object as a parameter, the expected object’s class name is specified as the parameter type in the method signature.
Summary
We have discussed the fact that objects are specified by classes. Classes represent the general concept of things, while objects represent concrete instances of a class. We can have many objects of any class.
Objects have methods that we use to communicate with them. We can use a method to make a change to the object or to get information from the object. Methods can have parameters, and parameters have types. Methods have return types, which specify what type of data they return. If the return type is void, they do not return anything.
Objects store data in fields (which also have types). All the data values of an object together are referred to as the object’s state.
Data type
Category | Type | Description | Example |
---|---|---|---|
Primitive Types | byte |
8-bit integer | byte b = 100; |
short |
16-bit integer | short s = 1000; |
|
int |
32-bit integer | int i = 100000; |
|
long |
64-bit integer | long l = 100000L; |
|
float |
32-bit floating-point | float f = 3.14F; |
|
double |
64-bit floating-point | double d = 3.14159; |
|
char |
16-bit Unicode character | char c = 'A'; |
|
boolean |
Logical true/false | boolean b = true; |
|
Reference Types | String |
Immutable sequence of characters (text) | String s = "Hello"; |
Arrays |
Ordered collection of elements | int[] arr = {1, 2, 3}; |
|
Classes |
User-defined or built-in classes | Object obj = new Object(); |
|
Interfaces |
Contracts for classes to implement | List<String> list; |
|
Enums |
Fixed set of constants | enum Day {MON, TUE, WED} |
Exercise 1.35 Look at the book you are reading right now. Is it an object or a class? If it is a class, name some objects. If it is an object, name its class.
public class Book {
String title;
String author;
int pageCount;
public Book(String title, String author, int pageCount) {
this.title = title;
this.author = author;
this.pageCount = pageCount;
}
}
Class definition
public class TicketMachine //This is class header, which provides a name for the class.
{
//Inner part of the class omitted.
}
Note that we can omit public
here, then class will become private
as default.
But we cannot omit class
Methods: Header and Body
-
Definition: A method has two parts:
-
Header: Includes a comment, return type, method name, and parentheses
()
. - Body: Enclosed in
{}
and contains declarations and statements. - Example Header:
public int getPrice()
- No semicolon at the end (unlike field declarations).
- Parentheses
()
indicate it’s a method. -
Method Body:
-
Starts after the header and ends with matching
}
. -
Contains:
- Declarations: Create temporary variables.
- Statements: Define the method’s actions.
- Example:
return price;
(single statement ingetPrice
). - Can include multiple lines of declarations and statements in complex methods.
- Block:
-
Any code between
{}
is a block. - Examples: Class body, constructor bodies, method bodies.
Constructor vs. Method Headers
-
Differences:
-
Return Type:
- Methods: Have a return type (e.g.,
int
inpublic int getPrice()
). - Constructors: No return type (e.g.,
public TicketMachine(int cost)
). - Rule: Constructors must never have a return type.
-
Parameters:
-
Constructor: Can have parameters (e.g.,
int cost
). - Method: Can have zero or more parameters (e.g., empty
()
ingetPrice
). - Both can have any number of parameters, including none.
- Name match with Class:
A constructor’s name must exactly match the class name. * Example Headers:
- Methods: Have a return type (e.g.,
-
Constructor:
public TicketMachine(int cost)
- Method:
public int getPrice()
Accessor Methods
- Definition: Methods such as
getPrice
andgetBalance
in theTicketMachine
class are called accessor methods (or accessors). - Purpose: They return information about an object's state to the caller, providing a way to access the object's internal data.
-
Characteristics:
-
Usually contain a
return
statement to pass back the requested information. - Do not modify the object's state (read-only behavior).
-
Examples:
-
getPrice
: Returns the price of a ticket. -
getBalance
: Returns the current balance of the ticket machine.
Mutator Methods
- Definition: Methods like
insertMoney
andprintTicket
in theTicketMachine
class are called mutator methods (or mutators). - Purpose: They change the state of an object by modifying the values of one or more fields.
-
Comparison with Accessors:
-
Accessors: Request information about an object’s state (e.g., "get" methods like
getPrice
). - Mutators: Request the object to change its state.
-
Characteristics:
-
Alter the value of one or more fields each time they are called.
- Can lead to different object behavior before and after the method call due to the state change.
-
Common Form:
-
Often take a single parameter to directly overwrite a field’s value.
- These are typically called "set" methods, acting as a complement to "get" methods.
- Example: A
setPrice
method might take a parameter to update theprice
field. - Note: The
TicketMachine
class currently does not have any "set" methods. -
Examples in
TicketMachine
: -
insertMoney
: Likely increases the balance by adding the inserted amount. -
printTicket
: Likely deducts the ticket price from the balance and prints a ticket.
Printing with System.out.println
- Purpose: The
System.out.println
method prints its parameter to the text terminal. -
Basic Form:
-
Syntax:
System.out.println(something-we-want-to-print);
- Parameter: Can be any string enclosed in double quotes (e.g.,
System.out.println("# The BlueJ Line");
). - Behavior: Prints the exact string between the double quotes, including special characters like
#
or spaces.
Complex Parameter Example
- Statement:
System.out.println(" # " + price + " cents.");
-
Components:
-
String Literal:
" # "
(includes a space after the hash). - Field Value:
price
(no quotes, uses the value of theprice
field, converted to a string). - String Literal:
" cents."
(includes a space before "cents"). -
String Concatenation:
-
The
+
operator acts as a string-concatenation operator when used between a string and another value. - Combines the three components into a single string (e.g., if
price
is 50, output might be" # 50 cents."
). - Note:
+
is not arithmetic addition here; it joins strings, converting non-strings (likeprice
) to strings automatically. - Result: Prints the ticket price with extra characters (e.g.,
" # "
and" cents."
) on either side.
Special Case: No Parameter
- Statement:
System.out.println();
- Behavior: Prints a blank line.
- Observation: Visible when printing multiple tickets, creating separation between outputs.
Non-Void Return Types
- Purpose: Enable passing a value from a method back to the calling location.
- Requirement: Methods with non-void return types must include at least one
return
statement within their body. - Common Practice: The
return
statement is typically the last statement in the method.
Constructors
- Return Type: Constructors do not have any return type, not even
void
.
Overview of Conditional Statements
- Definition: Conditional statements, also known as
if-statements
, allow a program to take one of two possible actions based on the result of a test or check. - General Form (Pseudo-code):
if(perform some test that gives a true or false result) {
Do the statements here if the test gave a true result
}
else {
Do the statements here if the test gave a false result
}
-
Key Components (in Java):
-
Keywords:
if
andelse
. - Round brackets
()
enclosing the test. - Curly brackets
{}
marking the blocks of code to execute for each case. - The test, true block, and false block are specific to each situation.
Behavior of Conditional Statements
- Execution: Only one of the two blocks of statements (the
if
block or theelse
block) is executed, depending on the result of the test. - Example (from the
insertMoney
method):
if(amount > 0) {
balance = balance + amount;
}
else {
System.out.println("Use a positive amount rather than: " + amount);
}
Boolean Expressions in Tests
- Definition: The test in a conditional statement is a boolean expression, which evaluates to either
true
orfalse
. -
Example:
amount > 0
is a boolean expression. -
Returns
true
ifamount
is greater than zero. - Returns
false
ifamount
is not greater than zero. - Role: The boolean value determines which block of code (
if
orelse
) is executed.
Comparison Operators
- Purpose: Used in boolean expressions to compare two numeric values.
-
Common Operators (in Java):
-
>
(greater than): Checks if the left value is greater than the right value. -
<
(less than): Checks if the left value is less than the right value. -
>=
(greater than or equal to): Checks if the left value is greater than or equal to the right value. -
<=
(less than or equal to): Checks if the left value is less than or equal to the right value. - Usage Example: In the
printTicket
method, these operators might be used to validate numeric conditions.
Types of Variables
- Commonality: All variables store data but serve distinct roles in a program.
-
Three Types Encountered:
-
Fields (Instance Variables)
- Parameters
- Local Variables (Introduced in this section)
Local Variables
-
Definition: A local variable is a variable declared and used within a single method or block.
-
Example from the
refundBalance
method:* In this example,public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund; }
amountToRefund
is a local variable. * Distinguishing Features: -
Not a Field: Unlike fields, local variables are defined inside a method body, not outside methods.
- Not a Parameter: Unlike parameters, local variables are not defined in the method header.
-
Syntax:
-
Local variable declarations resemble field declarations but never include access modifiers like
private
orpublic
-
Scope and Lifetime:
-
Scope: Limited to the statements of the method (or block) in which they are declared.
- Lifetime: Exist only during the execution of the method; they are created when the method is called and destroyed when the method finishes.
- Note: Constructors can also have local variables with similar scope and lifetime properties.
Comparison to Fields
-
Purpose of Local Variables:
-
Used as temporary storage to help a single method complete its task.
- Considered data storage specific to a single method.
-
Purpose of Fields:
-
Used to store data that persists throughout the life of an entire object.
- Accessible to all methods of the object.
-
Best Practice:
-
Avoid declaring variables as fields if they are only used locally within a method and their values do not need to persist beyond the method’s execution.
- Example: Even if multiple methods use similar local variables, they should not be fields unless their values need to be shared or retained across method calls.
Role of Local Variables in refundBalance
-
Usage:
-
amountToRefund
temporarily holds the value ofbalance
beforebalance
is reset to zero. - The method then returns the remembered value (
amountToRefund
). -
Why Needed:
-
Exercises following this section will illustrate why a local variable is necessary here, as opposed to attempting to write
refundBalance
without one.
Initialization of Local Variables
-
Common Practice:
-
Local variables are often initialized at the time of declaration.
-
Example: The first two statements of
refundBalance
can be abbreviated as:* Key Concept: This combines two steps:int amountToRefund = balance;
- Declaring the variable (
int amountToRefund
). - Assigning an initial value (
= balance
).
- Declaring the variable (
Pitfalls
Name Conflicts:
A local variable with the same name as a field will "shadow" the field, preventing access to the field from within the method or constructor.
Features of Each Variable Type
Fields (Instance Variables)
- Definition Location: Defined outside constructors and methods, typically at the class level.
-
Purpose:
-
Store data that persists throughout the life of an object.
- Maintain the current state of an object.
- Lifetime: Lasts as long as the object exists.
-
Scope:
-
Class scope: Accessible throughout the entire class, including all constructors and methods.
-
Access Control:
-
If defined as
private
, fields cannot be accessed from outside their defining class.
Formal Parameters
- Definition Location: Defined in the header of a constructor or method.
-
Purpose:
-
Receive values from outside, initialized by the actual parameter values passed during a constructor or method call.
- Act as temporary storage locations.
- Lifetime: Exists only during the execution of the constructor or method (lost between calls).
- Scope: Limited to the constructor or method in which they are defined.
Local Variables
- Definition Location: Defined inside the body of a constructor or method.
-
Purpose:
-
Used for temporary storage within the body of their defining constructor or method.
- Lifetime: Exists only during the execution of the constructor or method (lost between calls).
-
Scope:
-
Limited to the block in which they are defined (not accessible outside that block).
-
Initialization:
-
Must be explicitly initialized before use in an expression (no default value is provided).
Overview of Method Calling
Example Method:
public String getLoginName()
{
return name.substring(0,4) + id.substring(0,3);
}
Key Features Illustrated
-
Calling a Method on Another Object:
- Concept: Methods can be called on objects to perform actions or retrieve data.
-
Example:
-
Both
name
andid
areString
objects. - The
substring
method is called on theseString
objects to extract portions of their content. - Purpose: Allows interaction with the functionality provided by other objects (in this case, the
String
class).
-
Using the Returned Value in an Expression:
- Concept: The value returned by a method can be directly used as part of a larger expression.
-
Example:
-
name.substring(0,4)
returns a string, which is immediately concatenated with the result ofid.substring(0,3)
using the+
operator. - The combined result is then returned by the
getLoginName
method.
Details of the substring
Method
- Method Header (from the
String
class):
/**
* Return a new string containing the characters from
* beginIndex to (endIndex-1) from this string.
*/
public String substring(int beginIndex, int endIndex)
- Extracts a portion of the string starting at
beginIndex
(inclusive) and ending atendIndex - 1
(inclusive). - Index
0
represents the first character of the string. -
Usage in
getLoginName
: -
name.substring(0,4)
extracts the first four characters of thename
string. -
id.substring(0,3)
extracts the first three characters of theid
string.
Example of getLoginName
in Action
-
Input:
-
name = "Leonardo da Vinci"
-
id = "468366"
-
Execution:
-
name.substring(0,4)
returns"Leon"
(characters at indices 0, 1, 2, 3). -
id.substring(0,3)
returns"468"
(characters at indices 0, 1, 2). - The
+
operator concatenates these into"Leon468"
. -
Output:
-
The
getLoginName
method returns the string"Leon468"
.