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

Variables and Operators

This document discusses variables and operators in Java. It defines variables as places to store information while a program runs. Variables must be declared with a data type and have valid identifiers that start with a letter or underscore. The eight primitive data types in Java are discussed, including four integer types (byte, short, int, long), two floating point types (float, double), boolean, and char. Variables must be declared before use and have a consistent data type.

Uploaded by

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

Variables and Operators

This document discusses variables and operators in Java. It defines variables as places to store information while a program runs. Variables must be declared with a data type and have valid identifiers that start with a letter or underscore. The eight primitive data types in Java are discussed, including four integer types (byte, short, int, long), two floating point types (float, double), boolean, and char. Variables must be declared before use and have a consistent data type.

Uploaded by

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

DEBRE MARKOS INSTITUTE OF TECHNOLOGY

ECEg3142: Object Oriented Programming

2. Basic Programming Constructs of Java


Variables and Operators

By: Mequanent Argaw Muluneh


Day 2
Tuesday, June 1, 2021
2
2

Lecture Outline

❖ Variables and Their Declaration

❖ Operators used in Java

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
3
3

Variables and Their Declaration


What are variables?

❖ Variables are places where information can be stored while a program is


running.

❖ Their values can be changed at any point over the course of a program.

❖ String studentName; studentName = “Kebede Alemu”;


Type Variable name

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
4 4

Variables and Their Declaration …


Naming Variables
❖ The name that you choose for a variable is called an identifier. In Java,
an identifier can be of any length, but must start with: a letter (a – z), a
dollar sign ($), or, an underscore ( _ ).

❖ The rest of the identifier can include any character except those used as operators
in Java such as + , - , * , /, %.

❖ In addition, there are certain keywords reserved (e.g., "class") in the Java language
which can never be used as identifiers.
2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
5 5

Variables and Their Declaration …


Naming Variables …
❖ Java is a case-sensitive language – the capitalization of letters in
identifiers matters.
❖ A rose is not a Rose is not a ROSE

❖ It is good practice to select variable names that give a good indication of


the sort of data they hold.
❖ For example, if you want to record the size of a hat, hatSize is a good choice for a name
whereas xyz would be a bad choice.

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
6 6

Variables and Their Declaration …


Naming Variables …
❖ When naming a variable, the following convention is commonly used:

❖ The first letter of a variable name is lowercase.

❖ Each successive word in the variable name begins with a capital


letter.

❖ All other letters are lowercase

❖ Here are some examples: pageCount, loadFile, anyString, threeWordVariable


2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
7
7

Pop Quiz
❖ Which of the following are valid variable names?
1. $amount Valid

2. 6tally Invalid Started by a number

3. my*Name Invalid Has an arithmetic operator

4. salary Valid

5. _score Valid

6. first Name Invalid Has a white space at the middle

7. total# Valid
2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
8
8

Variables and Statements


❖ A statement is a command that causes something to happen which ends with a
semicolon.

❖ Variable declaration and initialization


❖ One way is to declare a variable and then assign a value to it with two statements:
int e; // declaring a variable

e = 5; // assigning a value to a variable

❖ Another way is to write a single initialization statement:

int e = 5; // declaring AND assigning


2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
9
9

Java is a Strongly Typed Language


❖ All variables must be declared with a data type before they are used.

❖ Each variable's declared type does not change over the course of the program.

❖ Certain operations are only allowed with certain data types.

❖ If you try to perform an operation on an illegal data type (like multiplying Strings),
the compiler will report an error.

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
10 10

Data Types
❖ There are eight built-in (primitive) data types in the Java language
❖ 4 integer types (byte, short, int, long)

❖ 2 floating point types (float, double)

❖ Boolean (boolean)

❖ Character (char)

**see Appendix II: Summary of Primitive Data Types for a complete table of sizes and formats**

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
11
Integer Data Types
❖ There are four data types that can be used to store integers.

❖ The one you choose to use depends on the size of the number that we
want to store.
Data Type Value Range
byte -128 to +127
short -32768 to +32767
int -2147483648 to +2147483647
long -9223372036854775808 to +9223372036854775807

❖ In this course, we will always use int when dealing with integers.
2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT 11
Tuesday, June 1, 2021
12 12

Integer Data Types …


❖ Here are some examples of when you would want to use integer types:
❖ byte smallValue;

❖ smallValue = -55;

❖ int pageCount = 1250;

❖ long bigValue = 1823337144562L;

❖ Note: By adding an L to the end of the value in the last example, the program is
“forced” to consider the value to be of a type long even if it was small enough to be an
int.

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
13 13

Floating Point Data Types


❖ There are two data types that can be used to store decimal values (real numbers).

❖ The one you choose to use depends on the size of the number that we want to store.

Data Type Value Range


float 1.4×10-45 to 3.4×1038

double 4.9×10-324 to 1.7×10308

❖ In this course, we will always use double when dealing with decimal values.

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
14 14

Floating Point Data Types …


❖ Here are some examples of when you would want to use floating point types:
❖ double big = 7.7e100 ;

❖ double tinyNumber = 5.82e-203;

❖ float costOfBook = 49.99F;

❖ Note: in the last example we added an F to the end of the value. Without the F,
it would have automatically been considered a double instead.

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
15 15

Boolean Data Type

❖ Boolean is a data type that can be used in situations where there


are two options, either true or false.

❖ Example:
❖ boolean switchOn = true;
❖ boolean fileOpen = false;

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
16 16

Character Data Type


❖ Character is a data type that can be used to store a single character
such as a letter, number, punctuation mark, or other symbol.

❖ Example:
❖ char firstLetterOfName = 'e’ ;

❖ char myQuestion = '?' ;

❖ Note that you need to use singular quotation marks when assigning
char data types.

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
17 17

Introduction to Strings
❖ Strings consist of a series of characters inside double quotation marks.
❖ Examples statements assign String variables:
❖ String coAuthor = "John Smith";
❖ String password = "swordfish786";

❖ Strings are not one of the primitive data types, although they are very
commonly used.
❖ Strings are constant; their values cannot be changed after they are
created.
2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
18 18

Pop Quiz
What data types would you use to store the following types of
information?
1. Population of Ethiopia int
2. Approximation of π double
3. Open/closed status of a file Boolean
4. Your name String
5. First letter of your name char
6. $237.66 double
2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
19 19

Operators
❖ Operators are special symbols used for

❖ mathematical functions

❖ assignment statements

❖ logical comparisons

❖ Examples:
❖ 3+5 // uses + operator

❖ 14 + 5 – 4 * (5 – 3) // uses +, -, * operators

❖ Expressions can be combinations of variables, primitives and operators that


result in a value.
2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
20 20

The Operator Groups


❖ There are 5 different groups of operators:
❖ Arithmetic operators
❖ Assignment operator
❖ Increment/Decrement operators
❖ Relational operators
❖ Conditional operators

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
21 21

Arithmetic Operators
❖ Java has 6 basic arithmetic operators
+ add

- subtract

* multiply

/ divide

% modulo (remainder)

^ exponent (to the power of)

❖ Order of operations (or precedence) when evaluating an expression is the


same as you learned in school (PEMDAS).
2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
22 22

Order of Arithmetic Operations


❖ Example: 10 + 15 / 5;

❖ The result is different depending on whether the addition or division


is performed first.

(10 + 15) / 5 = 5

10 + (15 / 5) = 13

❖ Without parentheses, Java will choose the second case.

❖ Note: you should be explicit and use parentheses to avoid confusion.


2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
23 23

Integer Division
❖ In the previous example, we were lucky that (10 + 15) / 5 gives an exact integer
answer (5).

❖ But what if we divide 63 by 35?

❖ Depending on the data types of the variables that store the numbers, we will get
different results. int i = 63; double x = 63;

int j = 35; double y = 35;

System.out.println(i / j); System.out.println(x / y);

Output: 1 Ouput: 1.8

❖ The result of integer division is just the integer part of the quotient!
2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
24 24

Assignment Operator
❖ The basic assignment operator (=) assigns the value of var to expr.

❖ var = expr ;

❖ Java allows you to combine arithmetic and assignment operators into a single operator.

❖ Examples:

❖ x = x + 5; is equivalent to x += 5;
❖ y = y * 7; is equivalent to y *= 7;

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
25 25

Increment/ Decrement Operators


count = count + 1; // can be written as:

++count; or count++;

++ is called the increment operator.

count = count - 1; // can be written as:

--count; or count--;

-- is called the decrement operator.


2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
26 26

The increment/decrement operator has two forms:


❖ The prefix form ++count, --count first adds 1 to the variable and then continues
to any other operator in the expression
int numOranges = 5;
numFruit has value 16
int numApples = 10;
numOranges has value 6
int numFruit;
numFruit = ++numOranges + numApples;
The postfix form count++, count-- first evaluates the expression and then adds 1
to the variable
int numOranges = 5; numFruit has value 15
int numApples = 10; numOranges has value 6
int numFruit;
numFruit = numOranges++ + numApples;
2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
27
Relational (Comparison) Operators
❖ Relational operators compare two values
❖ Produces a boolean value (true or false) depending on the
is true when . . .
relationship operation
a > b a is greater than b
a >= b a is greater than or equal to b
a == b a is equal to b
a != b a is not equal to b
a <= b a is less than or equal to b
a < b a is less than b
2. Variables and Operators, Object Oriented Programming,
27
Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
28 28

Examples of Relational Operations

int x = 3;
int y = 5;
boolean result;

1. result = (x > y); now result is assigned the value false because 3 is not
greater than 5

2. result = (15 == x*y); now result is assigned the value true because the
product of 3 and 5 equals 15

3. result = (x != x*y); now result is assigned the value true because the
product of x and y (15) is not equal to x (3)

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
29
Conditional Operators

Symbol Name

&& AND
|| OR
! NOT

❖ Conditional operators can be referred to as boolean operators, because they are


only used to combine expressions that have a value of true or false.

2. Variables and Operators, Object Oriented Programming,


29
Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
30
Truth Table for Conditional Operators
x y x && y x || y !x

True True True True False

True False False True False

False True False True True

False False False False True


2. Variables and Operators, Object Oriented Programming,
30
Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
31 31

Examples of Conditional Operators


boolean x = true;
boolean y = false;
boolean result;
1. Let result = (x && y);
now result is assigned the value false (see truth table!)
2. Let result = ((x || y) && x);
(x || y) evaluates to true
(true && x) evaluates to true
now result is assigned the value true

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
32 32

Using && and ||


❖ Examples:
(a && (b++ > 3))
(x || y)

❖ Java will evaluate these expressions from left to right and so will evaluate
a before (b++ > 3)
x before y
❖ Java performs short-circuit evaluation:
❖ it evaluates && and || expressions from left to right and once it finds the result,
it stops.
2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
33 33

Short Circuit Evaluation


❖ (a && (b++ > 3))

❖ What happens if a is false?

❖ Java will not evaluate the right-hand expression (b++ > 3) if the left-hand operator a is false,
since the result is already determined in this case to be false. This means b will not be
incremented!

❖ (x || y)

❖ What happens if x is true?

❖ Similarly, Java will not evaluate the right-hand operator y if the left-hand operator x is true,
since the result is already determined in this case to be true.
2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
34 34

Pop Quiz
1) What is the value of number?
-12
int number = 5 * 3 – 3 / 6 – 9 * 3;
2) What is the value of result?
int x = 8;
int y = 2; false
boolean result = (15 == x * y);
3) What is the value of result?
int x = 7;
boolean result = (x < 8) && (x > 4); true

4) What is the value of numCars?


int numBlueCars = 5;
int numGreenCars = 10;
int numCars = numGreenCars++ + numBlueCars + ++numGreeenCars; 27
2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
35 35

REFERENCES
• Summary of Java operators

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/opsummary.html

• Order of Operations (PEMDAS)

1. Parentheses

2. Exponents

3. Multiplication and Division from left to right

4. Addition and Subtraction from left to right

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
36
Appendix I: Reserved Words

The following keywords are reserved in the Java language. They can
never be used as identifiers:
abstract assert boolean break byte
case catch char class const
continue default do double else
extends final finally float for
goto if implements import instanceof
int interface long native new
package private protected public return
short static strictfp super switch
synchronized this throw throws transient
try void violate while
2. Variables and Operators, Object Oriented Programming,
36
Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
37 37

Appendix II: Primitive Data Types

The following tables show all of the primitive data types along with
their sizes and formats:

Integers Data Type Description


byte Variables of this kind can have a value from:
-128 to +127 and occupy 8 bits in memory
short Variables of this kind can have a value from:
-32768 to +32767 and occupy 16 bits in memory
int Variables of this kind can have a value from:
-2147483648 to +2147483647 and occupy 32 bits in memory
long Variables of this kind can have a value from:
-9223372036854775808 to +9223372036854775807 and occupy
64 bits in memory
2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
38 38

Appendix II: Primitive Data Types …

Data Type Description


float Variables of this kind can have a value from:
1.4e(-45) to 3.4e(+38)
Real Numbers
double Variables of this kind can have a value from:
4.9e(-324) to 1.7e(+308)

Other Primitive Data Types


char Variables of this kind can have a value from:
A single character
boolean Variables of this kind can have a value from:
True or False

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021
39 39

Questions???

2. Variables and Operators, Object Oriented Programming, Electrical and Computer Engineering, DMiT Tuesday, June 1, 2021

You might also like