0% found this document useful (0 votes)
4 views

Lecture 02 - Annotated - Programming Languages - Classes and Objects P1

Uploaded by

kemalemran25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lecture 02 - Annotated - Programming Languages - Classes and Objects P1

Uploaded by

kemalemran25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

COE 318

Software Systems
Lecture 02:
Classes and Objects

Boujemaa Guermazi
Java Primitive Data Types

• byte: 1 signed byte. Each byte is 8 bits. –128 to 127.

• char: 2 unsigned bytes. Unicode, 0 to 65535

• short: 2 signed bytes, -32768 to 32767

• int: 4 signed bytes, -2147483648 to 2147483647


2
Java Primitive Data Types

• long : 8 signed bytes

• float: 4 signed bytes

• double: 8 signed bytes

3
Arithmetic Operators
• Addition: + When you divide one integer by
another integer in Java, the
• Subtraction: - result will be an integer
int a = 10;
int b = 3;
• Multiplication: * float result = a / b; ??? → 3

• Division: /

• Remainder or modulus: % (e.g. 8%3 is 2)


4
The “overloaded” + operator
• a+b evaluates to sum of a and b when both are numbers.
• When one or both of them are Strings, they evaluate to a
concatenation of the strings.

2+3 Evaluates as 5
"Hello"+"There" Evaluates as "HelloThere"
"Hello"+2 Evaluates as "Hello2"

5
The “overloaded” + operator
• More than two operands? The “+” operator is evaluated
left to right. But parentheses can be used to force the
order.

System.out.println("1"+2+3); "123"
System.out.println(1+2+ "3"); "33"
System.out.println("1"+ (2+3)); "15"

1+2+”3” + (4+5)=??? → “339”


6
Equality Operators
• ==
e.g. x==y means x is equal to y

• !=
e.g. x!=y means x is not equal to y
• that you must use "==", not "=", when testing if two primitive values are equal.
• == checks for value equality. It compares the actual values of the operands.

7
Relational Operators
• > means “greater than”
• < means “less than”
• >= means “greater than or equal to”
• <= means “less than or equal to”
e.g.
x>y ;
c<d
e>=f ;
8
g<=k
Compound Assignment Operator
Operator Example Meaning
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y

9
Increment & Decrement Operator
• Prefix increment ++ e.g. ++i int x = 5;
Increase i by 1, then use the new value of
i to evaluate the expression that i resides int prefixIncrement = ++x;

// prefixIncrement is ?, x is now ?
// prefixIncrement is 6, x is now 6
• Postfix increment ++ e.g. i++ int postfixIncrement = x++;
Use the current value of i to evaluate the // prefixIncrement is ?, x is now ?
expression that i resides, then increase i // prefixIncrement is 6, x is now 7
by 1

10
Increment & Decrement Operator

• Prefix decrement -- e.g. --i


Decrease i by 1, then use the new value of i to evaluate
the expression that i resides

• Postfix decrement -- e.g. i--


Use the current value of i to evaluate the expression that
i resides, then decrease i by 1
11
Conditional Statements
class IfTest2 {
public static void main (String[] args) {
int x = 2;
if (x == 3) {
System.out.println("x must be 3");
}
else {
System.out.println("x is NOT 3");
} Output:
System.out.println("This runs no matter what"); x is NOT 3
This runs no matter what
}
}
12
Conditional Statements
class IfTest2 {
public static void main (String[] args) {
int x = 2;
if (x == 3) {
System.out.println("x must be 3");
}
else if(x==2) {
System.out.println("x must be 2");
}
else{
System.out.println("Wrong value"); Output:
} x must be 2
}
}
13
The Switch Statement
The switch statement evaluates an expression, then
attempts to match the result to one of several possible
cases.

14
15
The Switch Statement
• An optional default case as the last case in the statement If no
other value matches, control falls through to the statement
after the switch

• A break statement is used as the last statement in each case


statement list

• If a break statement is not used, the flow of control will


continue into the next case after matching the correct case
16
The Switch Statement
class SwitchTest {
public static void main (String[] args) {
int x = 3;
switch (x) {
case 3:
System.out.println("x must be 3");
break;
case 2:
System.out.println("x must be 2");
break;
default:
System.out.println("Wrong value"); Output:
break; x must be 3
}
}
} 17
6
What is the final value of x if initially: 6
9

18
While Loop
public class Loopy {
public static void main (String[] args) {
int x = 1;
System.out.println("Before the Loop") ; Output:
while (x < 4) { Before the Loop
System.out.println("In the loop"); In the loop
Value of x is 1
System.out.println("Value of x is " + x) ; In the loop
x = x + 1; Value of x is 2
In the loop
} Value of x is 3
System.out.println("This is after the loop"); This is after the loop
}
}
19
For Loop
public class Loopy {
public static void main (String[] args) {
int x = 1;
System.out.println("Before the Loop") ;
for (x=1;x < 4;x++) {
System.out.println("In the loop");
System.out.println("Value of x is " + x) ;

}
System.out.println("This is after the loop");
}
}
20
Do-while Loop
Useful if you want the body of the loop to execute at least once
regardless of condition.
public class Loopy {
public static void main (String[] args) {
int x = 1;
System.out.println("Before the Loop") ;
while(x!=1) { //code never enters the loop!
System.out.println("In the loop");
System.out.println("Value of x is " + x) ;
x = 1;
}}}
21
Do-while Loop
Useful if you want the body of the loop to execute at least once
regardless of condition.
public class Loopy { executed at least once
public static void main (String[] args) {
int x = 1;
System.out.println("Before the Loop") ;
do{
System.out.println("In the loop");
System.out.println("Value of x is " + x) ;
x = 1;
}while(x!=1);}}
22
Given the following code, where x = 0, what is the resulting value
of x after the for-loop terminates? 10

int x=0;
for (int i=0;i<5;i++)
x = x+i;
How many times will the following loop iterate? 10

int x = 10;
while (x > 0){
System.out.println(x);
x=x-1;
}
23
How many times will the following loop
iterate?
39

for (x=1;x < 40;x++) {


System.out.println("In the loop" + x);
}

24
How many times will the following loop
iterate?
Infinity!

int x=3;
while (x<40) {
System.out.println("In the loop" + x);
}

25
How many times will the following loop
iterate?
37

int x=3;
while (x<40) {
System.out.println("In the loop" + x);
x=x+1;
}

26
How many times will the following loop
iterate?
1

int x=50;
do {
System.out.println("In the loop" + x);
} while (x<40);

27
How many times will the following loop
iterate?
39*39

int x,y;
for (x=1;x < 40;x++) {
for(y=1;y<40;y++){
System.out.println("In the loop");
}
}

28
Conditional Operator
Condition ? Do_if_true : do_if_false
• Can be used in place of “if .. else” statement
• It takes three operands.
– The first operand is the boolean expression.
– The second operand is the conditional expression if the boolean expression is true.
– The third operand is the conditional expression if the boolean expression is false.
float grade=40;
String result= grade >=50 ? "passed" : "failed";
System.out.println(result);
29
Class (Recap)
• A “template” that defines type of an object.
• Can contain - variables, methods.

30
General Form of class definition
class classname
{
//declare variables
type var1;
type var2;
….
//declare methods
type method(parameters)
{
//body of method, consists of statements
}
type method2(parameters)
{
//body of method, consists of statements
}
….
} 31
public class Car {
String licensePlate;
double speed;
double maxSpeed;

public void setLicensePlate(String plateNumber ){


licensePlate=plateNumber;
}
public void setSpeed (double speedVal) {
speed=speedVal;
}
public double getSpeed () {
return speed;
}
}
32
Object (Recap)
• A class is simply a definition.
• To use a class, you need to create an object of that
specific class type (called instance of a class).
• Objects are created through operator “new”.
• Since an object is an “instance of a class”, the variables
in the class are called “instance variables/methods”.

33
Steps to create an object
• Step 1: declare a variable called miniVan of the class type
Car. This is just a variable that can refer to an object. At the
point, miniVan contains value “null”, meaning it is not
referring to any object yet.

• Step2: Allocate memory in computer and construct an object


of type “Class” in that memory segment. This is done by
using operator “new”. Then, assign to “miniVan” a reference
to that object.
34
..But WHERE should I create the object?
public class Car {
String licensePlate;
double speed;
double maxSpeed;

public void setLicensePlate(String plateNumber ){


licensePlate=plateNumber;
}
public void setSpeed (double speedVal) {
speed=speedVal;
}
public double getSpeed () {
return speed;
}
}
35
..But WHERE should I create the object?
• Class definition can only contain variables and methods.
You can not write code outside of the method bodies.

• Remember, execution starts from the main() method.

36
..But WHERE should I create the object?
• Option 1: Have a main() method in the class definition
itself: Not a good practice, class definitions should just
contain class specific code for clarity.
• Option 2: Have a “Helper” or “Tester” class where the
main method resides. Typically, this class JUST have
the main() method, nothing else. Both class files should
be in the same project.

37
To “test” the car class (Car.java)…
public class Car {
String licensePlate;
double speed;
double maxSpeed;
public void setLicensePlate(String plateNumber ){
licensePlate=plateNumber;
}
public void setSpeed (double speedVal) {
speed=speedVal;
}
public double getSpeed () {
return speed;
}
}
38
We create a “CarTest” class
(CarTest.java) and put the main() method
in it

public class CarTest {


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

39
We create a “CarTest” class
(CarTest.java) and put the main() method
in it
public class CarTest {
public static void main(String[] args){
Car miniVan;
miniVan=new Car();
}
}

40
We create a “CarTest” class
(CarTest.java) and put the main() method
in it
public class CarTest {
public static void main(String[] args){
Car miniVan=new Car();
}
}

41
Accessing object’s data
• Object contains data that you can access with operator “.”
in the form of
object.variable for instance variable
e.g.
miniVan.licensePlate="ABC";
miniVan.speed = 100;
double maxSpeed=miniVan.maxSpeed;
object.method() for instance method
e.g.
miniVan.setSpeed(50); 42
Good Programming Practice
• Typically, instance variables are NOT directly accessed
(we will learn about access modifiers later, to enforce
this)
• Instead, each instance variable that you want to be
“accessible” have getter and setter methods.
• e.g. getSpeed() and setSpeed() in our Car class.

43
Methods
• Methods are subroutines that act on object’s data. A
method can call other methods of its own class, it can
also call methods of other classes.

• Objects interact with each other through method calls.

• You can model the real world through object


interactions.

44
General Form of a Method
ReturnType methodName(parameter-list) {
//body of method
}
• methodName is the name of the method as a string with
no space. Capitalize first letter of each word except the
first as a convention.

45
General Form of a Method
ReturnType methodName(parameter-list) {
//body of method
}
• ReturnType is any primitive type, or object reference. If
nothing is returned from the method to the method-caller,
a “void” is declared.

46
General Form of a Method
ReturnType methodName(parameter-list) {
//body of method
}
• Parameter-list is a comma separated list of type and
variable pair. Each pair pass a value of certain data type
to the method.

47
General Form of a Method
ReturnType methodName(parameter-list) {
//body of method
}
• The body of a method consists of statements.

48
public class CarTest {
public static void main(String[] args){
Car miniVan=new Car();
miniVan.setLicensePlate("ABC");
miniVan.setSpeed(100);
double speed=miniVan.getSpeed();
System.out.println(speed);
}
}
49
You can create multiple objects of the
same class!

public class CarTest {


public static void main(String[] args){
Car miniVan=new Car();
Car sedan=new Car();
}
}
50
Each object has there OWN instance
variable and methods
public class CarTest {
public static void main(String[] args){ Output:
Car miniVan=new Car(); 100
110
Car sedan=new Car();
miniVan.setLicensePlate("ABC");
miniVan.setSpeed(100);
sedan.setLicensePlate("DEF");
sedan.setSpeed(110);
double speed=miniVan.getSpeed();
System.out.println(speed);
speed=sedan.getSpeed();
System.out.println(speed);
}
}
51
Step-by-step Exercise:
Let’s modify the Car class
1. Add a variable to keep track of “fuel”.
2. Add “getter” and “setter” methods for fuel.
3. Add a method “refuel” that increases the “fuel” by an
input param “amount”.
4. Add a method “drive” that reduces the “fuel” based on
an input param “speed”. Let’s assume for a speed of 1, fuel
reduces by 0.5.
52
public class Car {
String licensePlate;
double speed;
double maxSpeed;
public void setLicensePlate(String plateNumber ){
licensePlate=plateNumber;
}
public void setSpeed (double speedVal) {
speed=speedVal;
}
public double getSpeed () {
return speed;
}
}

53
Let’s modify the Car class (1)
1. Add a variable to keep track of “fuel”.

54
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public void setLicensePlate(String plateNumber ){
licensePlate=plateNumber;
}
public void setSpeed (double speedVal) {
speed=speedVal;
}
public double getSpeed () {
return speed;
}
}

55
Let’s modify the Car class (2)
2. Add “getter” and “setter” methods for fuel.

56
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public void setLicensePlate(String plateNumber ){
licensePlate=plateNumber;
}
public void setSpeed (double speedVal) {
speed=speedVal;
}
public double getSpeed () {
return speed;
}
public double getFuel() {
return fuel;
}
public void setFuel(double val) {
fuel=val;
}
}
57
Let’s modify the Car class (3)
3. Add a method “refuel” that increases the
“fuel” by an input param “amount”.

58
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public void setLicensePlate(String plateNumber ){
licensePlate=plateNumber;
}
public void setSpeed (double speedVal) {
speed=speedVal;
}
public double getSpeed () {
return speed;
}
public double getFuel() {
return fuel;
}
public void setFuel(double val) {
fuel=val;
}
public void refuel(double amount){
fuel=fuel+amount;
}
}

59
Let’s modify the Car class (4)
4. Add a method “drive” that reduces the
“fuel” based on an input param “speed”. Let’s
assume for a speed of 1, fuel reduces by 0.5.

60
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public void setLicensePlate(String plateNumber ){
licensePlate=plateNumber;
}
public void setSpeed (double speedVal) {
speed=speedVal;
}
public double getSpeed () {
return speed;
}
public double getFuel() {
return fuel;
}
public void setFuel(double val) {
fuel=val;
}
public void refuel(double amount){
fuel=fuel+amount;
}
public void drive(double speed){
fuel=fuel-speed*0.5;
}
}
61
Test it!
public class CarTest {
public static void main(String[] args){ Output:
20
Car miniVan=new Car(); 40
miniVan.setFuel(0); 30
miniVan.refuel(20);
System.out.println(miniVan.getFuel());
miniVan.refuel(20);
System.out.println(miniVan.getFuel());
miniVan.drive(20);
System.out.println(miniVan.getFuel());
}
}
62

You might also like