Docsity

Java Fundamentals: Understanding Primitive Types and Reference Types, Assignments of Computer Science

Toggle sidebar
bg1
1
1
CS162: Introduction to Computer
Science II
Java Fundamentals
2
Primitive Types
3
Primitive types
• Primitive types:
byte, short, int, long,
float, double, char, boolean
• Example:
int size = 42;
–size is a primitive variable, i.e., a variable that
contains a data value of the declared type.
4
The eight primitive types in Java
5
Limitations
• All primitive types have limited ranges
– Exceeding the range will cause inaccurate
results
•float and double are typically
approximations
– don't use == to compare real types
– Use Math.abs(x-y) <= EPSILON where
EPSILON is some small number
6
Operations on primitive types
• Variable holds value
• Assignment statements assign values
– E.G., int n =10;
• Operations are defined as language primitives
– E.G., n += 5;
• Relational operators, etc., are defined as
language primitives
– E.G., if (n <= 15) ...
pf3
pf4
pf5

Partial preview of the text

Download Java Fundamentals: Understanding Primitive Types and Reference Types and more Assignments Computer Science in PDF only on Docsity!

1

CS162: Introduction to ComputerScience II

Java Fundamentals

2

Primitive Types

3

Primitive types

• Primitive types: byte, short, int, long,

• Example: float, double, char, boolean

int size = – size is a primitive variable, i.e., a variable that 42;

contains a data value of the declared type.

4

The eight primitive types in Java

5

Limitations

• All primitive types have limited ranges– Exceeding the range will cause inaccurate

• float results and double are typically

approximations– don't use == to compare real types

– Use Math.abs(x-y) <= EPSILON whereEPSILON is some small number

6

Operations on primitive types

• Variable holds value• Assignment statements assign values

• Operations are defined as language primitives– E.G.,^ int^ n^ =^ 10;

• Relational operators, etc., are defined as– E.G.,^ n^ +=^ 5;

language primitives– E.G., if (n <= 15) ...

7

Result of logical operators

AND OR NOT

8

!(x DeMorgan’s Laws && y) == !x || !y

!(x || y) == !x && !y

int x^ Short-circuit evaluation = 3;

intif ((xy = ==5; y) && (y > 0)) ...

if ((x < y) || (y < 0)) ...

9

Short-circuit evaluation

intint xy == 3;5;

int z = x / y;

if// ((zOK != 0) && ((y / z) < 5))

if// (((ycrash / ifz) DivideByZeroException< 5) && (z != 0))

// is not handled 10

Reference types

• All types that are not primitive are referenceor class types

• Example: String greeting = "Howdy";

– greeting variable that contain a reference to (address of)the memory location of the data. is a reference variable, i.e., a

11

Reference Types

12

Objects

• An object is a program entity that– contains data

• The actions are called methods– performs certain actions

• The actions of various objects interact toform a solution for a given problem

19

Instantiation

bobsCar

0.9^2000

“Sedan”

address of the data forcontains the memoryA memory cell that bobsCar 20

• It is possible for two variables to reference the sameAliases

• object. They are aliasesExample:

Automobile myCar = bobsCar;

myCar

bobsCar

0.9^2000

“Sedan”

If an object has two (or more) aliases,the object may be referenced and/ormodified through any of those aliases.

21

• Instead of calling a function to “do somethingInvoking methods in a program

to” an object (imperative programming), tellthe object to perform one of its actions (object-

• Examples:based programming).

bobsCar.accelerate(5);intif (bobsCar.getFuelLevel() <currentSpeed = bobsCar.getSpeed(); 0.1) bobsCar.decelerate(10); 22

• Valued methods return a single value, andInvoking methods in a program

should be used in an expression.– Return type of method must be assignment-compatible in the context of the call

• void should be used as a single statement. methods do not return a value, and

• Examples: bobsCar.accelerate(5);int currentSpeed = bobsCar.getSpeed();

if (^) bobsCar.decelerate(10);(bobsCar.getFuelLevel() < 0.1)

23

Arguments and Parameters

• Invocation of a method must have samenumber of arguments as formal parameters in

• Arguments are associated in order with formalthe declaration of the method.

• Argument types must be assignment-parameters

compatible with the associated formalparameter types

24

• The formal parameter in the method becomes anArguments and Parameters

alias for the argument passed to it, and is treatedas a local variable.

• The formal parameter is discarded when themethod terminates.

• Example: Suppose that adefined as follows: matchSpeed method is

publicint diff void matchSpeed(Automobile = getSpeed() - other.getSpeed(); other) { }if(diff > 0)else^ other.decelerate(-diff);^ other.accelerate(diff);

25

Before calling matchSpeed

bobsCar 2140555

0.9^2000

“Sedan” (^) suesCar 986435

0.45^2001

“SUV”

26

bobsCar.matchSpeed(suesCar); Call^ matchSpeed

bobsCar 2140555

0.9^2000

“Sedan” other suesCar 986435

0.45^2001

“SUV”

suesCar is associated withother is an alias ofsuesCar.other

27

other.accelerate(diff); After executing

bobsCar

2140555

0.9^2000

“Sedan” other suesCar 986455

0.45^2001

“SUV”

suesCar.speed is changed

28

After matchSpeed terminates

bobsCar 2140555

0.9^2000

“Sedan” other suesCar 986455

0.45^2001

“SUV”

other no longer exists

29

Passing Arguments

• Pass by value– For primitive type, parameter initialized to value ofargument in call

• Pass by reference– For a class type, formal parameter is initialized tothe address of the object in the call

• An argument cannot be changed by beingpassed to a method!

– An object referenced by an argument can bechanged by a method. 30

Alternate implementation of matchSpeed *

publicotherCar void matchSpeed(Automobile = new Automobile(other.getModel(),other.getYear(), other) { other.getFuelLevel(),getSpeed(),other.getMileage()); }

* WRONG!

37

To treat primitive types as objects, you must useWrapper Classes

wrapper classes

shortlong ShortLong intfloat IntegerFloat doublechar DoubleCharacter booleanbyte BooleanByte Primitive Class Wrapper Class

38

int sizeWrapper Class Example = 42;

Integer String sizeStringsizeWrapper = = sizeWrapper.toString(); new Integer(size); size = 42 value = 42^ Integer

39

Wrapper Class Functions

There are lots of other functions you can call on awrapper class:

• doubleValue() • intValue() – returns the value as an integer – returns the value as a double

To see the complete list, check out the Java 5.0 API

40

Auto-boxing

• In Java 5.0, conversion between primitivetypes and the corresponding wrapper classesis automatic

• This is called auto-boxing Integer i = 42; // auto-boxing

// int same x = as Integeri; // auto-unboxing i = new Integer(42) // same as int x = i.intValue();

41

You can even make auto-boxing work insideFancy Auto-boxing

arithmetic expressions eg. Double e = d + 1; // d is a Double

Let’s look at the steps that this involves:1. Auto-unbox d into a double 2.3. Add 1Auto-box the result into a new Double

  1. Store a reference to the newly created wrapper objectin e 42

A Note About Wrappers

• Storing wrapper numbers is quite inefficient• This is because you often only want to store

the raw value but the wrapper class storesother stuff in addition to the value

• If you care about efficiency, use theprimitive type where possible