SlideShare a Scribd company logo
1 of 46
Fundamentals of Programming
Data Types, Variables, Expressions & Arithmetic
Operators
“Once a programmer has understood the use of
variables, he has understood the essence of
programming”
Rana Javed Rashid (Gold Medallists)
University of Education, Okara Campus
In this lecture, you will learn……..
 What are the Primitive data types in Java?
 What is a variable?
 Rules for naming a variable.
 How to declare a variable.
 Assignment Statement
 Assignment & Initialization of a variable
 Strings in Expressions
 What is a Expression
 How expressions are evaluated
 Arithmetic Operators
 Order of Precedence & Associativity
March 23, 2015 2
What is Data in Java
Data can be…..
 Numbers, Characters or other value that can be produced by a
human or computer.
 Useful computer programs manipulate data.
 Now we will learn how to print and manipulate other
kinds of data, such as numbers:
System.out.println(42);
System.out.println(3 + 5 * 7);
System.out.println(12.5 / 8.0);
March 23, 2015 3
What is Data in Java
Data can be…..:
 Whole Numbers like 4, 258, 78621, -3, 0 etc.
 Real Numbers like 3.14, 2589.25, -0.25, 9.0 etc.
 Characters like ‘a’, ‘A’, ‘?’, ‘n’ etc.
 Logical (boolean) like True or False
 Strings (names, address etc. ) like “Rana Javed Rashid”, “Okara” etc.
March 23, 2015 4
Primitives Data Types in Java
There are eight primitives data types in java. Primitives data
types are predefined by language and named by the
keywords.
◦ byte
◦ short
◦ int
◦ long
◦ float
◦ double
◦ character
◦ boolean
March 23, 2015 5
Primitives Data Types
byte:
 byte data type is 8-bit (1 byte) signed integer.
 Reserved Word used: byte
 Range is -128 to +127
 -128 means -2^7 & +127 means (2^7-1)
 Default value is 0
 byte data type can used to save the memory.
 Smaller than an integer (4 bytes) and short (2 bytes).
 Example: byte x = 100, byte y = -50
March 23, 2015 6
Primitives Data Types
short:
 short data type is 16-bit (2 byte) signed integer.
 Reserved Word used: short
 Range is -32,768 to +32,767
 -32,768 means -2^15 and +32, 767 means (2^15-1)
 Default value is 0
 short data type can also used to save the memory.
 Smaller than an integer (4 bytes).
 Example: short x = 1000, short y = -500
March 23, 2015 7
Primitives Data Types
int:
 int data type is 32-bit (4 byte) signed integer.
 Reserved Word used: int
 Range is -2,147,483,648 to +2,147, 483, 647
 -2,147,483,648 means -2^31 and +2,147, 483, 647 means (2^31-1)
 Default value is 0
 int is generally used as the default data type for integer values unless
there is a concern about memory.
 Example: int x = 100000, int y = -500000
March 23, 2015 8
Primitives Data Types
long:
 long data type is 64-bit (8 byte) signed integer.
 Reserved Word used: long
 Range is -9,233,372,036,854,755,808 to + 9,233,372,036,854,755,807
 - 9,233,372,036,854,755,808 means -2^63
 + 9,233,372,036,854,755,807 means (2^63-1)
 Default value is 0
 This type is used when wide range than int is needed.
 Example: long x = 100000L, long y = -500000L
March 23, 2015 9
Primitives Data Types
float:
 float data type is a single precession 32-bit (4 byte) floating point.
 Reserved Word used: float
 Default value is 0.0f
 Range: 1.4e(-45) to 3.4e(+38)
 float is mainly used to save memory in large arrays of floating point
numbers.
 Example: float x = 100.02f, float y = -2.528f
March 23, 2015 10
Primitives Data Types
double:
 double data type is a double precession 64-bit (8 byte) floating point.
 Reserved Word used: double
 double data type is generally used as default data type of floating
values.
 Default value is 0.0d
 Range: 4.9e(-324) to 1.7e(+308)
 Example: double x = 100.02, double y = -2.528
March 23, 2015 11
Primitives Data Types
char:
 char data type is a single 16-bit Unicode Character.
 Reserved Word used: char
 Range: ‘u0000’ (or 0) to ‘uffff’ (inclusive 65,535)
 char data type is used to store any character.
 Example: char letterA = ‘A’
March 23, 2015 12
Primitives Data Types
boolean:
 boolean data type represents 1-bit of information .
 Reserved Word used: boolean
 There is only two possible values: true or false
 This type is used for simple flags that track true or false conditions
 Default value is false
 Example: boolean isFind = true
March 23, 2015 13
What is Variable:
 A piece of your computer's memory that is given a name
and type, and can store a value.
◦ We use variables to store the results of a computation and use
those results later in our program.
◦ Unlike a cheap calculator, which may only have enough to store a
few values, we can declare as many variables as we want, limited
only by the memory are program is allowed to use.
 Variables are a bit like the 6 preset stations on your car stereo, except
we can, essentially, have as many of them as we want, and we give
them names, not numbers.
March 23, 2015 14
Rules for naming a variable:
 Variable names (or identifier) may be any length, but must
starts with:
◦ A letter (a – z),
◦ A dollar sign ($),
◦ Or, an underscore ( _ )
 Variables can never used special characters like +, -, &, *
#, ., etc.
 Space is not allowed in variable names
 Variable name may consists of number, characters, $ sign
and _ score but variable can’t start with number.
 Reserve words can not used as variable names like class,
main, int, float, static, for, if etc.
 Variable name must be unique in its scope.
March 23, 2015 15
Rules for naming a variable cont….:
 Java is case sensitive language it means that average,
Average and AVERAGE are different variable.
 In java there is a convention that variable names are in
small caps and constant declared in upper case.
 Always give meaningful names to variable like
studentGrade, studentAverage, petrolPrice etc.
 “Camel Case”: Start variable names with lower case and
capitalize each word like studentExamGrade.
March 23, 2015 16
Quiz
Which of the following are valid variable names?
 $amount
 12January
 My name
 _student_name_
 salary
 x*y
 a=b+c
 total$
 short
 main
 Main
March 23, 2015 17
How to declare a variable:
 variable declaration statement: A Java statement that
creates a new variable of a given type.
◦ A variable is declared by writing a statement that says its type, and
then its name. (The name is an identifier.)
 Declaration statement syntax:
<type> <name> ;
◦ Example: int x;
◦ Example: double myGPA;
 It is also legal to declare multiple variables of the same
type on one line:
<type> <name>, <name>, ..., <name> ;
◦ Example: int a, b, c;
March 23, 2015 18
More about declaring a variable:
 Declaring a variable sets aside a chunk of memory in which you can store a
value.
int x;
int y;
◦ A (crude) diagram of part of the computer's memory:
+--------+ +---------+
x | | y | | (The memory has no value in it yet.)
+--------+ +---------+
 The compiler will fail if you try to declare a variable twice, or declare two
variables with the same name.
◦ Illegal:
int x;
int x; // variable x already exists! ERROR
 When tracing code, draw boxes for variables!!
March 23, 2015 19
Assignment Statement:
 Assignment Statement: A Java statement that stores a value into a variable's
memory location.
◦ Variables must be declared before they can be assigned a value.
 Assignment statement syntax:
<name> = <value> ;
◦ Example: x = 3;
◦ Example: myGPA = 3.95;
◦ Another (crude) diagram of part of the computer's memory:
+---+ +------+
x | 3 | myGPA | 3.95 |
+---+ +------+
◦ Technically, = is an operator like + or *, called the assignment operator, with very
low precedence (it is carried out last).
March 23, 2015 20
Variable Initialization:
 When we assign a value to a variable when we declare a
variable then it is called variable initialization.
◦ Example: int x = 3;
◦ Example: float myGPA = 3.95f;
◦ Another (crude) diagram of part of the computer's memory:
+---+ +------+
x | 3 | myGPA | 3.95 |
+---+ +------+
 Other than the initialization assignment is called
variable assignment.
 Example: x = 3;
March 23, 2015 21
Declaration & Initialization:
 A variable can be declared and assigned an initial value in
the same statement, to save lines in your program.
 Declaration and initialization statement syntax:
<type> <name> = <value> ;
◦ Example: double myGPA = 3.95;
◦ Example: int x = (11 % 3) + 12;
 It is also legal to declare/initialize several at once:
<type> <name> = <value> , <name> = <value> ;
◦ Example: int a = 2, b = 3, c = -4;
◦ Example: double grade = 3.5, delta = 0.1;
March 23, 2015 22
same effect as:
double myGPA;
myGPA = 3.95;
int x;
x = (11 % 3) + 12;
More about assignment:
 The <value> assigned to a variable can be a complex
expression. The expression will be evaluated, and the
variable will store the result.
◦ Example:
x = (2 + 8) / 3 * 5;
(The variable x now stores the value 15)
 A variable can be assigned a value more than once in the
program.
◦ Example (Draw the boxes!!):
int x;
x = 3;
System.out.println(x); // 3
x = 4 + 7;
System.out.println(x); // 11
March 23, 2015 23
Using variables’ values:
 Once a variable has been assigned a value, it can be used
in an expression, just like a literal value.
int x;
x = 3;
System.out.println(x * 5 - 1);
◦ The above has output equivalent to:
System.out.println(3 * 5 - 1);
 A variable that has not been assigned a value cannot be
used in an expression or println statement.
◦ Illegal:
int x;
System.out.println(x); // ERROR -- x has no value
March 23, 2015 24
Assignment and algebra:
 Though the assignment statement uses the = character, it
is not like an algebraic equation.
= means, "store the value on the right into the memory of the
variable on the left“
in Java = is a verb, not a statement of fact
◦ Illegal:
3 = 1 + 2;
(because 3 is not a piece of the computer's memory)
1 + 2 = x; // syntax error
 What do you suppose happens when a variable is used on
both sides of an assignment statement?
int x;
x = 3;
x = x + 2; // what happens?
March 23, 2015 25
Assignment and Types:
 A variable can only store a value of its own type.
◦ Illegal: x = 2.5; // ERROR: x can only store
an int
◦ (Technically, the value does not need to be the same type as the
variable--it can be any type that Java knows how to convert into the
variable's type... see below.)
 An int value can be stored in a variable of type double.
The value is converted into the equivalent real number.
◦ Legal: double myGPA = 4;
+-----+
myGPA | 4.0 |
+-----+
March 23, 2015 26
Assignment Examples:
 What is the output of the following Java code?
int number;
number = 2 + 3 * 4;
System.out.println(number - 1);
number = 16 % 6;
System.out.println(2 * number);
 What is the output of the following Java code?
double average;
average = (9 + 8) / 2;
System.out.println(average);
average = (average * 2 + 10 + 8) / 4;
System.out.println(average);
March 23, 2015 27
Integer or Real Number?
 Categorize each of the following quantities by whether an
int or double variable would best to store it:
March 23, 2015 28
integer (int) real number (double)
1. Temperature in degrees Celsius
2. The population of lemmings
3. Your grade point average
4. A person's age in years
5. A person's weight in pounds
6. A person's height in meters
7. Number of miles traveled today
8. Number of dry days in the past month
9. The number of games the volleyball
team wins this season
10. Number of seconds left in a game
11. The sum of a group of integers
12. The average of a group of integers
Strings in Expression:
 A String can be used in an expression.
◦ But the only operator Strings understand is + , and its meaning is
different.
◦ A + operator on a String and another value causes the other value
to be attached to the String, creating a longer String. This is called
concatenation.
◦ Remember, the precedence of the + operator is below * / % .
Example: "hello" + 42 evaluates to "hello42"
Example: 1 + "abc" + 2 evaluates to "1abc2"
Example: "abc" + 1 + 2 evaluates to "abc12"
Example: 1 + 2 + "abc" evaluates to "3abc"
Example: "abc" + 9 * 3 evaluates to "abc27"
Example: "1" + 1 evaluates to "11"
March 23, 2015 29
Printing Strings in Expression:
 String expressions with + are useful so that we can print
more complicated messages that involve computed
values.
double grade = (95.1 + 71.9 + 82.6) / 3.0;
System.out.println("Your grade was " +
grade);
int students;
students = 11 + 17 + 4 + 19 + 14;
System.out.println("There are " + students +
" students in the course.");
March 23, 2015 30
Example variable Exercise:
 Write a Java program that stores the following data:
◦ Section 58615 has 17 students.
◦ Section 58617 has 8 students.
◦ Section 58620 has 11 students.
◦ Section 58625 has 23 students.
◦ Section 58627 has 24 students.
◦ Section 58630 has 7 students.
◦ The average number of students per section.
and prints the following:
There are 24 students in Section 58627.
There are an average of 15 students per section.
March 23, 2015 31
Expressions:
 Expression: A data value, or a set of operations
that compute a data value.
◦ Example: 1 + 4 * 3
◦ The simplest expression is a literal value.
◦ A more complex expression can have operators
and/or parentheses.
 The values that an operator applies to are called operands.
 5 common arithmetic operators we will use:
+ (addition)
- (subtraction or negation)
* (multiplication)
/ (division)
% (modulus, a.k.a. remainder)
March 23, 2015 32
Evaluating Expressions:
 When your Java program executes and encounters a line
with an expression, the expression is evaluated (its value
is computed).
◦ The expression 3 * 4 is evaluated to obtain 12.
◦ System.out.println(3 * 4) prints 12, not 3 * 4.
(How could we print 3 * 4 on the screen?)
 When an expression contains more than one operator of
the same kind, it is evaluated
left-to-right.
◦ Example: 1 + 2 + 3 is (1 + 2) + 3 which is 6
◦ Example: 1 - 2 - 3 is (1 - 2) - 3 which is -4
(not the same as 1 - (2 - 3) which is 2)
 Show the BlueJ interaction pane code pad
March 23, 2015 33
Integer division with /:
 14 / 4 evaluates to 3, not 3.5.
◦ Back to division in 4th grade
◦ In Java, when we divide integers, the result is also an integer: the integer
quotient.
◦ The integer quotient of dividing 14 by 4 is 3.
The integer remainder of dividing 14 by 4 is 2.
◦ Imagine that you were doing long division:
3 52
4 ) 14 27 ) 1425
12 135
2 75
54
21
◦ Examples:
 35 / 5 evaluates to 7
 84 / 10 evaluates to 8
 156 / 100 evaluates to 1
◦ Dividing by 0 causes your program to crash.
◦ Try it!
March 23, 2015 34
Integer remainder with %:
 The % operator computes the remainder from a division of
integers.
◦ Example: 14 % 4 is 2
◦ Example: 218 % 5 is 3
3 43
4 ) 14 5 ) 218
12 20
2 18
15
3
 What do the following expressions evaluate to?
◦ 45 % 6
◦ 2 % 2
◦ 8 % 20
◦ 11 % 0
March 23, 2015 35
Applications of % Operator:
 What expression obtains the last digit (units place) of a
number?
◦ Example: From 230857, obtain the 7.
 How could we obtain the last 4 digits of a Social Security
Number?
◦ Example: From 658236489, obtain 6489.
 What expression obtains the second-to-last digit (tens
place) of a number?
◦ Example: From 7342, obtain the 4.
 Can the % operator help us determine whether a number
is odd? Can it help us determine whether a number is
divisible by, say, 27?
March 23, 2015 36
Operator Precedence:
 How does Java evaluate 1 + 3 * 4?
Is it (1 + 3) * 4, or is it 1 + (3 * 4)?
◦ In a complex expression with several operators, Java uses internal
rules of precedence to decide the order in which to apply the
operators.
 precedence: Order in which operations are computed in
an expression.
◦ Multiplicative operators have a higher level of precedence than
additive operators, so they are evaluated first.
 * / % before + -
◦ In our example, * has higher precedence than +, just like on a
scientific calculator, so 1 + 3 * 4 evaluates to 13.
◦ Parentheses can be used to override a precedence.
(1 + 3) * 4 evaluates to 16.
March 23, 2015 37
Associativity of Arithmetic Operators:
 For operators, associativity means that when the same operator
appears in a row, then to which direction the expression is evaluated.
 If the same priority operators are present in the same expression then
it should be solved Left to Right, it is called operator associativity.
March 23, 2015 38
 1 * 2 + 3 * 5 / 4
 _/
|
2 + 3 * 5 / 4
 _/
|
2 + 15 / 4
 ___/
|
2 + 3
 ________/
|
5
Operator Precedence Examples:
March 23, 2015 39
 1 * 2 + 3 * 5 / 4
 _/
|
2 + 3 * 5 / 4
 _/
|
2 + 15 / 4
 ___/
|
2 + 3
 ________/
|
5
 1 + 2 / 3 * 5 - 4
 _/
|
1 + 0 * 5 - 4
 ___/
|
1 + 0 - 4
 ______/
|
1 - 4
 _________/
|
-3
Operator Precedence Examples:
 What do the following expressions evaluate to?
9 / 5
695 % 20
7 + 6 * 5
7 * 6 + 5
248 % 100 / 5
6 * 3 - 9 / 4
(5 - 7) * 4
6 + (18 % (17 - 12))
 Which parentheses above are unnecessary (which
do not change the order of evaluation?)
March 23, 2015 40
Operator Precedence & Real Numbers:
 The expressions we have seen so far used integers, but
Java also can manipulate real numbers (numbers with a
decimal point).
◦ Examples: 6.022 -15.9997 42.0
2.143e17
 The operators we saw, + - * / % , as well as
parentheses ( ) , all work for real numbers as well.
◦ The / operator produces a more precise answer when used on real
numbers, rather than an integer quotient.
 Example: 15.0 / 2.0 evaluates to 7.5
◦ The % operator is not often used on real numbers.
 The same rules of precedence that apply to integers also
apply to real numbers.
◦ ( ) before * / % before + -
March 23, 2015 41
Operator Precedence & Real Numbers:
 The expressions we have seen so far used integers, but
Java also can manipulate real numbers (numbers with a
decimal point).
◦ Examples: 6.022 -15.9997 42.0
2.143e17
 The operators we saw, + - * / % , as well as
parentheses ( ) , all work for real numbers as well.
◦ The / operator produces a more precise answer when used on real
numbers, rather than an integer quotient.
 Example: 15.0 / 2.0 evaluates to 7.5
◦ The % operator is not often used on real numbers.
 The same rules of precedence that apply to integers also
apply to real numbers.
◦ ( ) before * / % before + -
March 23, 2015 42
Real Numbers Example:
March 23, 2015 43
 1.5 * 2.4 + 3.3 * 4.25 / 5.5
 _/
|
3.6 + 3.3 * 4.25 / 5.5
 _/
|
3.6 + 14.025 / 5.5
 ___/
|
3.6 + 2.55
 _____________/
|
6.15
Mixing Integer &Real Numbers :
March 23, 2015 44
 When a Java operator is used on an integer and a real
number, the result is a real number.
◦ Example: 3 * 4.2 evaluates to 12.6
◦ Example: 1 + 1.0 evaluates to 2.0
 The kind of number that results from a given operator
depends only on its operands, not any other operands.
 7 / 3 * 1.2 + 3 / 2
 _/
|
2 * 1.2 + 3 / 2
 ___/
|
2.4 + 3 / 2
 _/
|
2.4 + 1
 ________/
|
3.4
March 23, 2015 45
Any Questions?
March 23, 2015 46
THANKS

More Related Content

What's hot

What's hot (20)

class and objects
class and objectsclass and objects
class and objects
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Programming Fundamentals lecture 1
Programming Fundamentals lecture 1Programming Fundamentals lecture 1
Programming Fundamentals lecture 1
 
Function in C
Function in CFunction in C
Function in C
 
Function C++
Function C++ Function C++
Function C++
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
C++ programming
C++ programmingC++ programming
C++ programming
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
Introduction to c++ ppt
Introduction to c++ pptIntroduction to c++ ppt
Introduction to c++ ppt
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 

Viewers also liked

Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaAbhilash Nair
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaAtul Sehdev
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in JavaAbhilash Nair
 
Java Arrays
Java ArraysJava Arrays
Java ArraysOXUS 20
 
itft-Operators in java
itft-Operators in javaitft-Operators in java
itft-Operators in javaAtul Sehdev
 
Fişinqdən necə qorunmaq olar?
Fişinqdən necə qorunmaq olar?Fişinqdən necə qorunmaq olar?
Fişinqdən necə qorunmaq olar?Irkan Akhmedov
 
Təhlükəsiz proqram təminatının java mühitində hazırlanma texnologiyaları
Təhlükəsiz proqram təminatının java mühitində hazırlanma texnologiyalarıTəhlükəsiz proqram təminatının java mühitində hazırlanma texnologiyaları
Təhlükəsiz proqram təminatının java mühitində hazırlanma texnologiyalarıIrkan Akhmedov
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsCS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsKwangshin Oh
 
Java proqramlaşdirma mühitində təhlükəsiz proqram təminatinin hazirlanma texn...
Java proqramlaşdirma mühitində təhlükəsiz proqram təminatinin hazirlanma texn...Java proqramlaşdirma mühitində təhlükəsiz proqram təminatinin hazirlanma texn...
Java proqramlaşdirma mühitində təhlükəsiz proqram təminatinin hazirlanma texn...Irkan Akhmedov
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 
Datatype introduction- JAVA
Datatype introduction- JAVADatatype introduction- JAVA
Datatype introduction- JAVAHamna_sheikh
 
Java Magazine : The JAVA Virtual Machine alternative languages
Java Magazine : The JAVA Virtual Machine alternative languagesJava Magazine : The JAVA Virtual Machine alternative languages
Java Magazine : The JAVA Virtual Machine alternative languagesErik Gur
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methodsfarhan amjad
 

Viewers also liked (20)

Operators in java
Operators in javaOperators in java
Operators in java
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in Java
 
02 data types in java
02 data types in java02 data types in java
02 data types in java
 
Operators in java
Operators in javaOperators in java
Operators in java
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in java
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
itft-Operators in java
itft-Operators in javaitft-Operators in java
itft-Operators in java
 
Fişinqdən necə qorunmaq olar?
Fişinqdən necə qorunmaq olar?Fişinqdən necə qorunmaq olar?
Fişinqdən necə qorunmaq olar?
 
Təhlükəsiz proqram təminatının java mühitində hazırlanma texnologiyaları
Təhlükəsiz proqram təminatının java mühitində hazırlanma texnologiyalarıTəhlükəsiz proqram təminatının java mühitində hazırlanma texnologiyaları
Təhlükəsiz proqram təminatının java mühitində hazırlanma texnologiyaları
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsCS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
 
Java proqramlaşdirma mühitində təhlükəsiz proqram təminatinin hazirlanma texn...
Java proqramlaşdirma mühitində təhlükəsiz proqram təminatinin hazirlanma texn...Java proqramlaşdirma mühitində təhlükəsiz proqram təminatinin hazirlanma texn...
Java proqramlaşdirma mühitində təhlükəsiz proqram təminatinin hazirlanma texn...
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Datatype introduction- JAVA
Datatype introduction- JAVADatatype introduction- JAVA
Datatype introduction- JAVA
 
Jdbc
JdbcJdbc
Jdbc
 
Java Magazine : The JAVA Virtual Machine alternative languages
Java Magazine : The JAVA Virtual Machine alternative languagesJava Magazine : The JAVA Virtual Machine alternative languages
Java Magazine : The JAVA Virtual Machine alternative languages
 
Data types
Data typesData types
Data types
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
 
Java operators
Java operatorsJava operators
Java operators
 
Java arrays
Java arraysJava arrays
Java arrays
 

Similar to Data types, Variables, Expressions & Arithmetic Operators in java

Ch-3(b) - Variables and Data types in C++.pptx
Ch-3(b) - Variables and Data types in C++.pptxCh-3(b) - Variables and Data types in C++.pptx
Ch-3(b) - Variables and Data types in C++.pptxChereLemma2
 
Java căn bản - Chapter3
Java căn bản - Chapter3Java căn bản - Chapter3
Java căn bản - Chapter3Vince Vo
 
Identifiers, keywords and types
Identifiers, keywords and typesIdentifiers, keywords and types
Identifiers, keywords and typesDaman Toor
 
computer notes - Data Structures - 1
computer notes - Data Structures - 1computer notes - Data Structures - 1
computer notes - Data Structures - 1ecomputernotes
 
Data structures cs301 power point slides lecture 01
Data structures   cs301 power point slides lecture 01Data structures   cs301 power point slides lecture 01
Data structures cs301 power point slides lecture 01shaziabibi5
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx
3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx
3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptxLeenaChaudhari24
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01Wingston
 
2 EPT 162 Lecture 2
2 EPT 162 Lecture 22 EPT 162 Lecture 2
2 EPT 162 Lecture 2Don Dooley
 
CS301-lec01.ppt
CS301-lec01.pptCS301-lec01.ppt
CS301-lec01.pptomair31
 

Similar to Data types, Variables, Expressions & Arithmetic Operators in java (20)

Ch-3(b) - Variables and Data types in C++.pptx
Ch-3(b) - Variables and Data types in C++.pptxCh-3(b) - Variables and Data types in C++.pptx
Ch-3(b) - Variables and Data types in C++.pptx
 
Java căn bản - Chapter3
Java căn bản - Chapter3Java căn bản - Chapter3
Java căn bản - Chapter3
 
Python
PythonPython
Python
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Identifiers, keywords and types
Identifiers, keywords and typesIdentifiers, keywords and types
Identifiers, keywords and types
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Numerical data.
Numerical data.Numerical data.
Numerical data.
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 
JAVA LESSON-01.pptx
JAVA LESSON-01.pptxJAVA LESSON-01.pptx
JAVA LESSON-01.pptx
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
additional.pptx
additional.pptxadditional.pptx
additional.pptx
 
computer notes - Data Structures - 1
computer notes - Data Structures - 1computer notes - Data Structures - 1
computer notes - Data Structures - 1
 
Data structures cs301 power point slides lecture 01
Data structures   cs301 power point slides lecture 01Data structures   cs301 power point slides lecture 01
Data structures cs301 power point slides lecture 01
 
vb.net.pdf
vb.net.pdfvb.net.pdf
vb.net.pdf
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx
3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx
3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx
 
Data Structure Lec #1
Data Structure Lec #1Data Structure Lec #1
Data Structure Lec #1
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
2 EPT 162 Lecture 2
2 EPT 162 Lecture 22 EPT 162 Lecture 2
2 EPT 162 Lecture 2
 
CS301-lec01.ppt
CS301-lec01.pptCS301-lec01.ppt
CS301-lec01.ppt
 

Recently uploaded

Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 

Recently uploaded (20)

Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 

Data types, Variables, Expressions & Arithmetic Operators in java

  • 1. Fundamentals of Programming Data Types, Variables, Expressions & Arithmetic Operators “Once a programmer has understood the use of variables, he has understood the essence of programming” Rana Javed Rashid (Gold Medallists) University of Education, Okara Campus
  • 2. In this lecture, you will learn……..  What are the Primitive data types in Java?  What is a variable?  Rules for naming a variable.  How to declare a variable.  Assignment Statement  Assignment & Initialization of a variable  Strings in Expressions  What is a Expression  How expressions are evaluated  Arithmetic Operators  Order of Precedence & Associativity March 23, 2015 2
  • 3. What is Data in Java Data can be…..  Numbers, Characters or other value that can be produced by a human or computer.  Useful computer programs manipulate data.  Now we will learn how to print and manipulate other kinds of data, such as numbers: System.out.println(42); System.out.println(3 + 5 * 7); System.out.println(12.5 / 8.0); March 23, 2015 3
  • 4. What is Data in Java Data can be…..:  Whole Numbers like 4, 258, 78621, -3, 0 etc.  Real Numbers like 3.14, 2589.25, -0.25, 9.0 etc.  Characters like ‘a’, ‘A’, ‘?’, ‘n’ etc.  Logical (boolean) like True or False  Strings (names, address etc. ) like “Rana Javed Rashid”, “Okara” etc. March 23, 2015 4
  • 5. Primitives Data Types in Java There are eight primitives data types in java. Primitives data types are predefined by language and named by the keywords. ◦ byte ◦ short ◦ int ◦ long ◦ float ◦ double ◦ character ◦ boolean March 23, 2015 5
  • 6. Primitives Data Types byte:  byte data type is 8-bit (1 byte) signed integer.  Reserved Word used: byte  Range is -128 to +127  -128 means -2^7 & +127 means (2^7-1)  Default value is 0  byte data type can used to save the memory.  Smaller than an integer (4 bytes) and short (2 bytes).  Example: byte x = 100, byte y = -50 March 23, 2015 6
  • 7. Primitives Data Types short:  short data type is 16-bit (2 byte) signed integer.  Reserved Word used: short  Range is -32,768 to +32,767  -32,768 means -2^15 and +32, 767 means (2^15-1)  Default value is 0  short data type can also used to save the memory.  Smaller than an integer (4 bytes).  Example: short x = 1000, short y = -500 March 23, 2015 7
  • 8. Primitives Data Types int:  int data type is 32-bit (4 byte) signed integer.  Reserved Word used: int  Range is -2,147,483,648 to +2,147, 483, 647  -2,147,483,648 means -2^31 and +2,147, 483, 647 means (2^31-1)  Default value is 0  int is generally used as the default data type for integer values unless there is a concern about memory.  Example: int x = 100000, int y = -500000 March 23, 2015 8
  • 9. Primitives Data Types long:  long data type is 64-bit (8 byte) signed integer.  Reserved Word used: long  Range is -9,233,372,036,854,755,808 to + 9,233,372,036,854,755,807  - 9,233,372,036,854,755,808 means -2^63  + 9,233,372,036,854,755,807 means (2^63-1)  Default value is 0  This type is used when wide range than int is needed.  Example: long x = 100000L, long y = -500000L March 23, 2015 9
  • 10. Primitives Data Types float:  float data type is a single precession 32-bit (4 byte) floating point.  Reserved Word used: float  Default value is 0.0f  Range: 1.4e(-45) to 3.4e(+38)  float is mainly used to save memory in large arrays of floating point numbers.  Example: float x = 100.02f, float y = -2.528f March 23, 2015 10
  • 11. Primitives Data Types double:  double data type is a double precession 64-bit (8 byte) floating point.  Reserved Word used: double  double data type is generally used as default data type of floating values.  Default value is 0.0d  Range: 4.9e(-324) to 1.7e(+308)  Example: double x = 100.02, double y = -2.528 March 23, 2015 11
  • 12. Primitives Data Types char:  char data type is a single 16-bit Unicode Character.  Reserved Word used: char  Range: ‘u0000’ (or 0) to ‘uffff’ (inclusive 65,535)  char data type is used to store any character.  Example: char letterA = ‘A’ March 23, 2015 12
  • 13. Primitives Data Types boolean:  boolean data type represents 1-bit of information .  Reserved Word used: boolean  There is only two possible values: true or false  This type is used for simple flags that track true or false conditions  Default value is false  Example: boolean isFind = true March 23, 2015 13
  • 14. What is Variable:  A piece of your computer's memory that is given a name and type, and can store a value. ◦ We use variables to store the results of a computation and use those results later in our program. ◦ Unlike a cheap calculator, which may only have enough to store a few values, we can declare as many variables as we want, limited only by the memory are program is allowed to use.  Variables are a bit like the 6 preset stations on your car stereo, except we can, essentially, have as many of them as we want, and we give them names, not numbers. March 23, 2015 14
  • 15. Rules for naming a variable:  Variable names (or identifier) may be any length, but must starts with: ◦ A letter (a – z), ◦ A dollar sign ($), ◦ Or, an underscore ( _ )  Variables can never used special characters like +, -, &, * #, ., etc.  Space is not allowed in variable names  Variable name may consists of number, characters, $ sign and _ score but variable can’t start with number.  Reserve words can not used as variable names like class, main, int, float, static, for, if etc.  Variable name must be unique in its scope. March 23, 2015 15
  • 16. Rules for naming a variable cont….:  Java is case sensitive language it means that average, Average and AVERAGE are different variable.  In java there is a convention that variable names are in small caps and constant declared in upper case.  Always give meaningful names to variable like studentGrade, studentAverage, petrolPrice etc.  “Camel Case”: Start variable names with lower case and capitalize each word like studentExamGrade. March 23, 2015 16
  • 17. Quiz Which of the following are valid variable names?  $amount  12January  My name  _student_name_  salary  x*y  a=b+c  total$  short  main  Main March 23, 2015 17
  • 18. How to declare a variable:  variable declaration statement: A Java statement that creates a new variable of a given type. ◦ A variable is declared by writing a statement that says its type, and then its name. (The name is an identifier.)  Declaration statement syntax: <type> <name> ; ◦ Example: int x; ◦ Example: double myGPA;  It is also legal to declare multiple variables of the same type on one line: <type> <name>, <name>, ..., <name> ; ◦ Example: int a, b, c; March 23, 2015 18
  • 19. More about declaring a variable:  Declaring a variable sets aside a chunk of memory in which you can store a value. int x; int y; ◦ A (crude) diagram of part of the computer's memory: +--------+ +---------+ x | | y | | (The memory has no value in it yet.) +--------+ +---------+  The compiler will fail if you try to declare a variable twice, or declare two variables with the same name. ◦ Illegal: int x; int x; // variable x already exists! ERROR  When tracing code, draw boxes for variables!! March 23, 2015 19
  • 20. Assignment Statement:  Assignment Statement: A Java statement that stores a value into a variable's memory location. ◦ Variables must be declared before they can be assigned a value.  Assignment statement syntax: <name> = <value> ; ◦ Example: x = 3; ◦ Example: myGPA = 3.95; ◦ Another (crude) diagram of part of the computer's memory: +---+ +------+ x | 3 | myGPA | 3.95 | +---+ +------+ ◦ Technically, = is an operator like + or *, called the assignment operator, with very low precedence (it is carried out last). March 23, 2015 20
  • 21. Variable Initialization:  When we assign a value to a variable when we declare a variable then it is called variable initialization. ◦ Example: int x = 3; ◦ Example: float myGPA = 3.95f; ◦ Another (crude) diagram of part of the computer's memory: +---+ +------+ x | 3 | myGPA | 3.95 | +---+ +------+  Other than the initialization assignment is called variable assignment.  Example: x = 3; March 23, 2015 21
  • 22. Declaration & Initialization:  A variable can be declared and assigned an initial value in the same statement, to save lines in your program.  Declaration and initialization statement syntax: <type> <name> = <value> ; ◦ Example: double myGPA = 3.95; ◦ Example: int x = (11 % 3) + 12;  It is also legal to declare/initialize several at once: <type> <name> = <value> , <name> = <value> ; ◦ Example: int a = 2, b = 3, c = -4; ◦ Example: double grade = 3.5, delta = 0.1; March 23, 2015 22 same effect as: double myGPA; myGPA = 3.95; int x; x = (11 % 3) + 12;
  • 23. More about assignment:  The <value> assigned to a variable can be a complex expression. The expression will be evaluated, and the variable will store the result. ◦ Example: x = (2 + 8) / 3 * 5; (The variable x now stores the value 15)  A variable can be assigned a value more than once in the program. ◦ Example (Draw the boxes!!): int x; x = 3; System.out.println(x); // 3 x = 4 + 7; System.out.println(x); // 11 March 23, 2015 23
  • 24. Using variables’ values:  Once a variable has been assigned a value, it can be used in an expression, just like a literal value. int x; x = 3; System.out.println(x * 5 - 1); ◦ The above has output equivalent to: System.out.println(3 * 5 - 1);  A variable that has not been assigned a value cannot be used in an expression or println statement. ◦ Illegal: int x; System.out.println(x); // ERROR -- x has no value March 23, 2015 24
  • 25. Assignment and algebra:  Though the assignment statement uses the = character, it is not like an algebraic equation. = means, "store the value on the right into the memory of the variable on the left“ in Java = is a verb, not a statement of fact ◦ Illegal: 3 = 1 + 2; (because 3 is not a piece of the computer's memory) 1 + 2 = x; // syntax error  What do you suppose happens when a variable is used on both sides of an assignment statement? int x; x = 3; x = x + 2; // what happens? March 23, 2015 25
  • 26. Assignment and Types:  A variable can only store a value of its own type. ◦ Illegal: x = 2.5; // ERROR: x can only store an int ◦ (Technically, the value does not need to be the same type as the variable--it can be any type that Java knows how to convert into the variable's type... see below.)  An int value can be stored in a variable of type double. The value is converted into the equivalent real number. ◦ Legal: double myGPA = 4; +-----+ myGPA | 4.0 | +-----+ March 23, 2015 26
  • 27. Assignment Examples:  What is the output of the following Java code? int number; number = 2 + 3 * 4; System.out.println(number - 1); number = 16 % 6; System.out.println(2 * number);  What is the output of the following Java code? double average; average = (9 + 8) / 2; System.out.println(average); average = (average * 2 + 10 + 8) / 4; System.out.println(average); March 23, 2015 27
  • 28. Integer or Real Number?  Categorize each of the following quantities by whether an int or double variable would best to store it: March 23, 2015 28 integer (int) real number (double) 1. Temperature in degrees Celsius 2. The population of lemmings 3. Your grade point average 4. A person's age in years 5. A person's weight in pounds 6. A person's height in meters 7. Number of miles traveled today 8. Number of dry days in the past month 9. The number of games the volleyball team wins this season 10. Number of seconds left in a game 11. The sum of a group of integers 12. The average of a group of integers
  • 29. Strings in Expression:  A String can be used in an expression. ◦ But the only operator Strings understand is + , and its meaning is different. ◦ A + operator on a String and another value causes the other value to be attached to the String, creating a longer String. This is called concatenation. ◦ Remember, the precedence of the + operator is below * / % . Example: "hello" + 42 evaluates to "hello42" Example: 1 + "abc" + 2 evaluates to "1abc2" Example: "abc" + 1 + 2 evaluates to "abc12" Example: 1 + 2 + "abc" evaluates to "3abc" Example: "abc" + 9 * 3 evaluates to "abc27" Example: "1" + 1 evaluates to "11" March 23, 2015 29
  • 30. Printing Strings in Expression:  String expressions with + are useful so that we can print more complicated messages that involve computed values. double grade = (95.1 + 71.9 + 82.6) / 3.0; System.out.println("Your grade was " + grade); int students; students = 11 + 17 + 4 + 19 + 14; System.out.println("There are " + students + " students in the course."); March 23, 2015 30
  • 31. Example variable Exercise:  Write a Java program that stores the following data: ◦ Section 58615 has 17 students. ◦ Section 58617 has 8 students. ◦ Section 58620 has 11 students. ◦ Section 58625 has 23 students. ◦ Section 58627 has 24 students. ◦ Section 58630 has 7 students. ◦ The average number of students per section. and prints the following: There are 24 students in Section 58627. There are an average of 15 students per section. March 23, 2015 31
  • 32. Expressions:  Expression: A data value, or a set of operations that compute a data value. ◦ Example: 1 + 4 * 3 ◦ The simplest expression is a literal value. ◦ A more complex expression can have operators and/or parentheses.  The values that an operator applies to are called operands.  5 common arithmetic operators we will use: + (addition) - (subtraction or negation) * (multiplication) / (division) % (modulus, a.k.a. remainder) March 23, 2015 32
  • 33. Evaluating Expressions:  When your Java program executes and encounters a line with an expression, the expression is evaluated (its value is computed). ◦ The expression 3 * 4 is evaluated to obtain 12. ◦ System.out.println(3 * 4) prints 12, not 3 * 4. (How could we print 3 * 4 on the screen?)  When an expression contains more than one operator of the same kind, it is evaluated left-to-right. ◦ Example: 1 + 2 + 3 is (1 + 2) + 3 which is 6 ◦ Example: 1 - 2 - 3 is (1 - 2) - 3 which is -4 (not the same as 1 - (2 - 3) which is 2)  Show the BlueJ interaction pane code pad March 23, 2015 33
  • 34. Integer division with /:  14 / 4 evaluates to 3, not 3.5. ◦ Back to division in 4th grade ◦ In Java, when we divide integers, the result is also an integer: the integer quotient. ◦ The integer quotient of dividing 14 by 4 is 3. The integer remainder of dividing 14 by 4 is 2. ◦ Imagine that you were doing long division: 3 52 4 ) 14 27 ) 1425 12 135 2 75 54 21 ◦ Examples:  35 / 5 evaluates to 7  84 / 10 evaluates to 8  156 / 100 evaluates to 1 ◦ Dividing by 0 causes your program to crash. ◦ Try it! March 23, 2015 34
  • 35. Integer remainder with %:  The % operator computes the remainder from a division of integers. ◦ Example: 14 % 4 is 2 ◦ Example: 218 % 5 is 3 3 43 4 ) 14 5 ) 218 12 20 2 18 15 3  What do the following expressions evaluate to? ◦ 45 % 6 ◦ 2 % 2 ◦ 8 % 20 ◦ 11 % 0 March 23, 2015 35
  • 36. Applications of % Operator:  What expression obtains the last digit (units place) of a number? ◦ Example: From 230857, obtain the 7.  How could we obtain the last 4 digits of a Social Security Number? ◦ Example: From 658236489, obtain 6489.  What expression obtains the second-to-last digit (tens place) of a number? ◦ Example: From 7342, obtain the 4.  Can the % operator help us determine whether a number is odd? Can it help us determine whether a number is divisible by, say, 27? March 23, 2015 36
  • 37. Operator Precedence:  How does Java evaluate 1 + 3 * 4? Is it (1 + 3) * 4, or is it 1 + (3 * 4)? ◦ In a complex expression with several operators, Java uses internal rules of precedence to decide the order in which to apply the operators.  precedence: Order in which operations are computed in an expression. ◦ Multiplicative operators have a higher level of precedence than additive operators, so they are evaluated first.  * / % before + - ◦ In our example, * has higher precedence than +, just like on a scientific calculator, so 1 + 3 * 4 evaluates to 13. ◦ Parentheses can be used to override a precedence. (1 + 3) * 4 evaluates to 16. March 23, 2015 37
  • 38. Associativity of Arithmetic Operators:  For operators, associativity means that when the same operator appears in a row, then to which direction the expression is evaluated.  If the same priority operators are present in the same expression then it should be solved Left to Right, it is called operator associativity. March 23, 2015 38  1 * 2 + 3 * 5 / 4  _/ | 2 + 3 * 5 / 4  _/ | 2 + 15 / 4  ___/ | 2 + 3  ________/ | 5
  • 39. Operator Precedence Examples: March 23, 2015 39  1 * 2 + 3 * 5 / 4  _/ | 2 + 3 * 5 / 4  _/ | 2 + 15 / 4  ___/ | 2 + 3  ________/ | 5  1 + 2 / 3 * 5 - 4  _/ | 1 + 0 * 5 - 4  ___/ | 1 + 0 - 4  ______/ | 1 - 4  _________/ | -3
  • 40. Operator Precedence Examples:  What do the following expressions evaluate to? 9 / 5 695 % 20 7 + 6 * 5 7 * 6 + 5 248 % 100 / 5 6 * 3 - 9 / 4 (5 - 7) * 4 6 + (18 % (17 - 12))  Which parentheses above are unnecessary (which do not change the order of evaluation?) March 23, 2015 40
  • 41. Operator Precedence & Real Numbers:  The expressions we have seen so far used integers, but Java also can manipulate real numbers (numbers with a decimal point). ◦ Examples: 6.022 -15.9997 42.0 2.143e17  The operators we saw, + - * / % , as well as parentheses ( ) , all work for real numbers as well. ◦ The / operator produces a more precise answer when used on real numbers, rather than an integer quotient.  Example: 15.0 / 2.0 evaluates to 7.5 ◦ The % operator is not often used on real numbers.  The same rules of precedence that apply to integers also apply to real numbers. ◦ ( ) before * / % before + - March 23, 2015 41
  • 42. Operator Precedence & Real Numbers:  The expressions we have seen so far used integers, but Java also can manipulate real numbers (numbers with a decimal point). ◦ Examples: 6.022 -15.9997 42.0 2.143e17  The operators we saw, + - * / % , as well as parentheses ( ) , all work for real numbers as well. ◦ The / operator produces a more precise answer when used on real numbers, rather than an integer quotient.  Example: 15.0 / 2.0 evaluates to 7.5 ◦ The % operator is not often used on real numbers.  The same rules of precedence that apply to integers also apply to real numbers. ◦ ( ) before * / % before + - March 23, 2015 42
  • 43. Real Numbers Example: March 23, 2015 43  1.5 * 2.4 + 3.3 * 4.25 / 5.5  _/ | 3.6 + 3.3 * 4.25 / 5.5  _/ | 3.6 + 14.025 / 5.5  ___/ | 3.6 + 2.55  _____________/ | 6.15
  • 44. Mixing Integer &Real Numbers : March 23, 2015 44  When a Java operator is used on an integer and a real number, the result is a real number. ◦ Example: 3 * 4.2 evaluates to 12.6 ◦ Example: 1 + 1.0 evaluates to 2.0  The kind of number that results from a given operator depends only on its operands, not any other operands.  7 / 3 * 1.2 + 3 / 2  _/ | 2 * 1.2 + 3 / 2  ___/ | 2.4 + 3 / 2  _/ | 2.4 + 1  ________/ | 3.4
  • 45. March 23, 2015 45 Any Questions?
  • 46. March 23, 2015 46 THANKS