[go: up one dir, main page]

0% found this document useful (0 votes)
12 views31 pages

Lecture5-2024

The document covers fundamental data types in Java, focusing on number types, variable declaration, assignment, and memory usage. It outlines learning outcomes, including the ability to describe Java number types, declare variables, and convert mathematical expressions into Java statements. Additionally, it provides examples of valid variable naming conventions and discusses floating-point data types.

Uploaded by

HAMO
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views31 pages

Lecture5-2024

The document covers fundamental data types in Java, focusing on number types, variable declaration, assignment, and memory usage. It outlines learning outcomes, including the ability to describe Java number types, declare variables, and convert mathematical expressions into Java statements. Additionally, it provides examples of valid variable naming conventions and discusses floating-point data types.

Uploaded by

HAMO
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

COMPUTER

SCIENCE

CSI141
PROGRAMMING
h t t p : / / ho r st m a n n . c o m / b j l o / i n d e x . ht m l PRINCIPLES
Programming Principles T ALLMAN NKGAU

L ECTURE 5 – F UNDAMENTAL
D ATA TYPES
‣ Everyday data
‣ Number Types, variables, &
assignment, output

http://horstmann.com/bjlo/index.html
L EARNING OUTCOMES

At the end of the lecture, you should be able

to:

‣ Describe the different Java number types

‣ Define what a data type is

‣ Declare Java number types variables

‣ Assign proper values to number type variables

‣ Convert math expression into equivalent Java

expressions/statements
h t t p : / / ho r st m a n n . c o m / b j l o / i n d e x . ht m l

‣ Draw memory diagrams

‣ Compute how much memory is used by Java

number types
‣ Everyday data
‣ Number Types, variables, &
assignment, input/output

h t t p : / / ho r st m a n n . c o m / b j l o / i n d e x . ht m l
Everyday data
• We work with numbers, text (strings), single characters, & a
combination of characters

Numbers

Numbers/Date?/String
String – a sequence of
characters
5
M ONEY IS AN ABSTRACT HUMAN
HAPPINESS , SO WHO IS NO
LONGER ABLE TO APPRECIATE THE
TRUE HUMAN HAPPINESS , IS
COMPLETELY DEDICATED TO IT . –
A RTHUR SCHOPENHAUE
‣ Everyday data
‣ Number Types, variables, &
assignment, input/output

h t t p : / / ho r st m a n n . c o m / b j l o / i n d e x . ht m l
Abstract View of RAM

https://en.wikipedia.org/wiki/Random-access_memory#/media/File:Swissbit_2GB_PC2-5300U-555.jpg
0
❑ We view memory as a sequential list of cells; 1
each 1 byte in size 2
❑ Each cell has an address associated with it Byte Address 3
❑ The example shown here will correspond to have 4
4096 bytes of RAM (= 4KB of RAM). [1KB = 1024 ⋮
bytes] 1023

4095
7
Integer data type
❑ Java provides a means to work with whole numbers.
❑ Java uses named memory locations to hold numbers.
— they make it easy to access the values stored – just use the
name. A variable is a storage
— they are called variables location with a name
— they can’t hold all the possible numbers. Not enough memory
for that!

Type Size in Set of Operations minimum maximum


bytes values

byte 1 integers +, -, /, %, * -128 127


short 2 integers +, -, /, %, * -32768 32767
int 4 integers +, -, /, %, * -2147483648 2147483647

long 8 integers +, -, /, %, * −𝟐 𝟔𝟑 𝟐 𝟔𝟑 − 𝟏

8
Integer data type, declaration
❑ A data type is a set of values and operations on them.
— For example: integers (…,-2,-1,0,1,2,…) and operations (add,
subtract, multiply, remainder, and divide)
❑ For a Java program to store an integer value, it MUST declare its intent to
the compiler – this is called static typing
❑ Declaration statements follow the following syntax:
<< type>> variableName;

• A variable name is also called an identifier.


• Java identifiers start with a letter or
byte numberOfChildren ; underscore (_) character. Remaining
short numOfSchools ; characters must be letters, underscore,
numbers, or $ character.
int population ; • Identifiers are case sensitive and can not
long numOfPlanes ; use spaces.
• Identifiers can not be Java keywords –
these are reserved for use by Java.

9
Java identifiers
❑ Identifiers are case sensitive
• mySalary and mysalary are different identifiers

❑Valid variable names (valid identifiers)


• input, myAge, numOfStudents, counter, j, _home

❑ Invalid/Bad variable names (invalid identifiers)


• int, 6ty, where?, up!, course code, my-age

keyword ‘?’ Not allowed Space not allowed

Can’t start with ‘-’ not allowed


‘!’ Not allowed
number

10
Java keywords

abstract continue for new switch


assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
true false null

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

11
POP QUIZ
Which of these are valid Java variable names?
A. catch
B. lean
C. 1stBorn
D. last$
E. PI
F. annual_salary
G. Int
H. Long
I. top!
J. “aws”
K. some body Page 12
POP QUIZ
Which of these are valid Java variable names?
A. catch
B. lean
C. 1stBorn
D. last$
E. PI
F. annual_salary
G. Int
H. Long
I. top!
J. “aws”
K. some body Page 13
Java Variable Naming Convention – Lower Camel Case

1. Start with lowercase letter


2. Capitalize first letter of ever subsequent word
3. Variable name should be meaningful – sufficient
to understand the purpose of a variable

Good Variable Names Bad Variable Names


annualSalary sal
paycheck pCheck
firstName fN
timeToLoad ttl

14
Pause…

N = 674532
t = 0
while N > 0
r = N % 10 // Remainder operation
if r % 2 == 0
t = t + r
N = N / 10 // Integer division
return t

Q. What values are in the variables N and t at the


end of executing the algorithm?
Meaning of declarations (Semantics)

❑ Remember, a variable is a name that refers to a memory location where


a value could be stored.
— A declaration reserves enough memory to hold the type of value to
be stored.
For example, given the following declarations

numberOfChildren
byte numberOfChildren;
short numOfSchools; numOfSchools
int population;
long numOfPlanes; population

numOfPlanes
Q. How much memory is used
by the 4 variables?
A. 1 + 2 + 4 + 8 = 15 bytes Memory diagram showing the
meaning of a declaration
16
Assignment statement – used to assign a value to a
variable

❑ An assignment statement is a statement that puts a value in a memory


location named by a variable.
— It uses the ‘=‘ character to do that
❑ Assignment statements follow the following syntax:

variableName = expression;

❑ The left-hand side MUST always be a variable/memory location.


❑ The semantics of the assignment statement is: evaluate the
expression. Put the value in the memory location named
by the variable on the left-hand side.
❑ The value of the expression MUST be type-compatible with the type of
the variable on the left-hand side.
❑ The variable MUST have been already declared.

17
Assignment statement – examples

int population; population = 2500000;


long numOfPlanes; numOfPlanes = -12L;

Declaration Assignment

population 2500000

Literals (specific value) numOfPlanes -12

Memory diagram

18
Expressions
❑ Expressions are your normal arithmetic expressions,
expressed as Java expressions.
❑ Expressions can involve other variables.

int divisor = 5; Declare and assign (initialize)


int groupsOfFive;
int total = 250;
groupsOfFive = total / divisor + 1;
int result = total * 10 - 100;
int leftover = result – total – 22;

Lookup the value in the variable,


to evaluate the expression.
DO NOT change the variable!
Page 19
PAUSE…dry run code

int divisor = 5;
int groupsOfFive;
int total = 250;

groupsOfFive = total / divisor + 1;


int result = total * 10 - 100;
int leftover = result – total – 22;

Page 20
Expressions
𝒙𝟐 +𝒙+𝟏
❑ The Math expression
𝟐+𝒚
is written as

(x*x + x + 1) / (2+y) in Java.


❑ Precedence is similar to Algebra:
❑ PEMDAS
❑ Parenthesis, Exponent, Multiply/Divide, Add/Subtract
❑ Integer operations
Operation Result Comment
7+3 10
3-7 -4
3*7 21
7/3 2 Integer division - drop
fractional part
7%3 1 remainder
Page 21
Example

public class Swap


{
public static void main(String[] args)
{
int a = 25;
int b = 75;
int t = a;
a = b;
b = t;
}
}
Q. What values are in Dry run the program. That is, trace the
variables a, b, and t? program with pencil and paper, using
A. a = 75, b = 25, t = 25 memory diagrams.
Displaying values in variables or expressions

❑We use the printf function – surprise!!

int divisor = 5;
int groupsOfFive;
int total = 250;

System.out.printf(“divisor = %d\n”, divisor);


System.out.printf(“result = %d\n”,total * 10 – 100);
Example

public class Swap


{
public static void main(String[] args)
{
int a = 25;
int b = 75;
int t = a;
a = b;
b = t;
System.out.printf(“a = %d\n”, a);
System.out.printf(“b = %d\n”, b);
System.out.printf(“t = %d\n”, t);
}
}
Example – with 1 printf statement

public class Swap


{
public static void main(String[] args) {
int a = 25;
int b = 75;
int t = a;
a = b;
b = t;
System.out.printf(“a = %d, b = %d, t = %d\n”, a, b, t);
}
}
Floating-point Data types in Java
❑ Java provides a means to work with floating-point numbers AKA real
numbers.
Type Size in bytes Set of Operations Range
values

float 4 Real +, -, /, * ±3.40282347E+38


numbers
double 8 Real +, -, /, * ±1.79769313486231570
numbers E+308

double area; ± 1.79769313486231570 × 10308


double radius = 2;
double pi = 3.14;
area = pi * radius * radius;
Page 26
Expressions

❑Parenthesis, Exponent, Multiply/Divide, Add/Subtract


❑ Operations
Operation Result Comment
3.142 + 0.31 3.452
3.142 – 0.31 2.832
3.142e5 / 3 104733.33333333 Never ending!
7.0 / 3.0 2.3333333333333 Never ending!

Page 27
Other operators
Operator Example Meaning Comment
++ b = i++; b = i; i = i + 1; post-increment

c = ++i; i = i + 1; b = i; pre-increment
-- b = i--; b = i; i = i - 1; post-decrement

c = --i; i = i - 1; b = i; pre-decrement

+= b += x + y; b = b + (x + y);
-= b -= x + y; b = b - (x + y);
*= b *= x + y; b = b * (x + y);
/= b /= x + y; b = b / (x + y);
%= b %= x + y; b = b % (x + y);

Page 28
POP QUIZ
Given c = 5; i = 3, x = -3 (all integer variables)
Evaluate the following (independently).
A. i++;
B. y = ++c – x++; // assume y is int
C. c %= 2*i + x / 2;
D. y = ++c + --i * x++; // assume y is int

Page 29
Summary

• Know the number data types: byte, short, int, long, float, double

• Know how to declare variables to hold each of the different number data

• Know how to assign values to variables – using expressions.


• Know how to convert mathematical expressions to equivalent Java
expressions.
• Know how to initialize variables (declare and assign at the same time)
• Know how to display values of number type variables
• Use compound operators including pre and post decrement operators

Page 30
Exercises

1. R2.1 – R2.5

Page 31

You might also like