0% found this document useful (0 votes)
26 views42 pages

Lecture 02 Variables and Operators

This document provides an introduction to fundamental programming structures in Java, including variables, data types, and operators. It discusses how to declare and assign values to variables of different data types like integers, doubles, Booleans, chars, and Strings. It also covers arithmetic, assignment, comparison, and logical operators and the order in which expressions are evaluated.

Uploaded by

Umer Beshir
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
26 views42 pages

Lecture 02 Variables and Operators

This document provides an introduction to fundamental programming structures in Java, including variables, data types, and operators. It discusses how to declare and assign values to variables of different data types like integers, doubles, Booleans, chars, and Strings. It also covers arithmetic, assignment, comparison, and logical operators and the order in which expressions are evaluated.

Uploaded by

Umer Beshir
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 42

1

Lecture 2

Introduction to Java Elements

Fundamental Programming Structures in


Java Part I
2

Outline

 Variables and their declaration

 Operators used in Java


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
4

Creating Variables
• To create a variable, declare its name and the type of information
that it will store.
• The type is listed first, followed by the name.

• Example: a variable that stores an integer representing the


highest score on an exam could be declared as follows:

int highScore ;

type name
5

Creating Variables (continued)


• Now you have the variable (highScore), you will want
to assign a value to it.

• Example: the highest score in the class exam is 98.

highScore = 98;

• Examples of other types of variables:

String studentName;
boolean gameOver;
6

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.
7

Naming (Continued)
• 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, hat_size is a
good choice for a name whereas qqq would be a bad choice
8

• 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
▫ Or use underscore between words
▫ All other letters are lowercase

• Here are some examples:

pageCount/page_count
loadFile/load_file
anyString/any_string
threeWordVariable/three_word_variable
9

POP QUIZ
• Which of the following are valid variable names?

1)$amount
2)6tally
3)my*Name
4)salary
5)_score
6)first Name
7)total#
10

Statements
• A statement is a command that causes something to
happen.

• All statements in Java are separated by semicolons ;

• Example:
System.out.println(“Hello, World”);

• You have already used statements to create a variable


and assign it a value.
11

Variables and Statements


• 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
12

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.
13

Primitive 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**
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.
14
15

• Here are some examples of when you would want


to use integer types:
- byte smallValue;
smallValue = -55;
- intpageCount = 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.
16

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.
17

• Here are some examples of when you would want


to use floating point types:
double g = 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.
18

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 monsterHungry = true;
boolean fileOpen = false;
19

Character Data Types


• Character is a data type that can be used to store a single
characters 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.
20

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.
21

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
22

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
23

The Operator Groups


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

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).
25

Order of 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


26

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.
27

Integer Division Example


• int i = 63;
int j = 35;
System.out.println(i / j);
Output: 1

• double x = 63;
double y = 35;
System.out.println(x / y);
Ouput: 1.8

• The result of integer division is just the integer part of the


quotient!
28

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;
29

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.
30

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;
int numApples = 10;
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16
numOranges has value 6

▫ The postfix form count++, count--


first evaluates the expression and then adds 1 to the variable

int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = numOranges++ + numApples;
numFruit has value 15
numOranges has value 6
Relational (Comparison) Operators
• Relational operators compare two values
• Produces a boolean value (true or false)
depending on the relationship
operation is true when . . .
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
31
32

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)
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.

33
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

34
35

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


36

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.
37

Short-Circuit Evaluations

(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.
38

POP QUIZ
1) What is the value of number?
int number = 5 * 3 – 3 / 6 –-12
9 * 3;

2) What is the value of result?


int x = 8; false
int y = 2;
boolean result = (15 == x * y);

3) What is the value of result?


boolean x = 7; true
boolean result = (x < 8) && (x > 4);

4) What is the value of numCars?


int numBlueCars = 5; 27
int numGreenCars = 10;
int numCars = numGreenCars++ + numBlueCars + ++numGreeenCars;
39

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


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

40
41

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
42

Real Numbers

Appendix II: Primitive Data Types (cont)


Data Type Description
float Variables of this kind can have a value from:
1.4e(-45) to 3.4e(+38)

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

You might also like