[go: up one dir, main page]

0% found this document useful (0 votes)
84 views41 pages

Chapter 2 - 1

The document discusses Java identifiers such as variables, rules for naming identifiers, and data types. It explains that every variable must have a data type, name, and value, and how to declare and initialize variables in Java. The main data types in Java are integer, floating point, character, and boolean primitive types.

Uploaded by

jojo
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)
84 views41 pages

Chapter 2 - 1

The document discusses Java identifiers such as variables, rules for naming identifiers, and data types. It explains that every variable must have a data type, name, and value, and how to declare and initialize variables in Java. The main data types in Java are integer, floating point, character, and boolean primitive types.

Uploaded by

jojo
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/ 41

Chapter 2

Dr. Sami Albouq


What You Will Learn
• Identifier
• Variables
• Data types
• Variable initialization
• Change variable value
• Constant
• Assignment

Dr. Sami Albouq


Identifier
A name that is used to identify:
• Variable
• Method
• Class How did we choose
• Other programming element. this name?

Example:
public class Welcome

Can we use 123 as a


class name?

Dr. Sami Albouq


Identifier
Identifier Rules Example Cannot do this
Starts with: a letter (a-z or A-Z), dollar age
sign($), or underscore(_) $um
_count
Followed by: zero or more letters, dollar signs, _count2 2_count
underscores, or digits(0-9) COUNT1 1COUNT
Case-sensitive! Uppercase and lowercase are RATE
different. Rate, rate, and RATE are the names of rate
three different variable Rate
Cannot be any of the reserved names public
void,, etc..
identifier cannot contain white space (e.g., _ count or count 1
student grade).
Can theoretically be of any length myAppCanDoSomething

Dr. Sami Albouq


Identifier
Keywords and Reserved words:

Identifiers that have a predefined meaning in Java


Do not use them to name anything else.

Examples:

public class void static


if for private

Dr. Sami Albouq


Identifier
Predefined identifiers:
Identifiers that are defined in libraries required by the Java
language standard

Although they can be redefined, this could be confusing and


dangerous if doing so would change their standard meaning

Examples:

System String println

Dr. Sami Albouq


Check Your Knowledge

Identifier Correct (Y or N) Explain


Rate
7age
_myAge
void Variable
intNumber
Abstract
abstract

Dr. Sami Albouq


Variables

In Java, a variable is a container that holds a value that can


be used by the program. Variables can be used to store various
types of data such as integers, floating-point numbers,
characters, and strings.

Every variable must have:


1. Data type
2. Name
3. Value

Dr. Sami Albouq


How to Declare Variables in
JAVA?
• What does variable declaration mean?

• Variable declaration is the process of creating a new


variable in a program. It involves specifying the name of
the variable and its data type, which defines the kind of
data that can be stored in the variable.
• Instructs the compiler to reserve a portion of memory space
large enough to hold a particular type of value
• Indicates the name by which we refer to that location

Dr. Sami Albouq


Variable Declaration
Datatype Identifier ;

boolean | char | byte


Any name that meets
short | int | long End of the statement
the rules of java
float | double

Example: int age ;


byte x ;
double y ;

Dr. Sami Albouq


Data Types
Data type tells the compiler:
• How much memory to allocate
• How to store the data
• The types of operations you will perform on the data

Compiler monitors use of data


• Java is a strongly typed language

Java has eight primitive data types


byte, short, int, long, float, double, char, boolean

Dr. Sami Albouq


Data Types

Dr. Sami Albouq


Declare Variables
Note variables are typically declared just before they are
used or at the start of a block (indicated by an opening
brace { )
public class Test{
public static void main (String [] args){

int x; // uninitialized
int y; // uninitialized
int n1, n2; // uninitialized

}
n1 n2 x y
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

RAM

Dr. Sami Albouq


Declare Variables and Assign
Them Values
Note variables are typically declared just before they are
used or at the start of a block (indicated by an opening
brace { )
public class Test{
public static void main (String [] args){

int x = 1; // inline initialization


int y; // uninitialized
int n1 = 5, n2; // inline initialization and uninitialized
y = 12; // late initialization

} n1 n2 x y
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

5 1 12 RAM
Dr. Sami Albouq
Change Variable Values
In Java, you can change the value of a variable by
assigning a new value to it using the assignment operator
"=".
public class Test{
public static void main (String [] args){

int x = 1; // Declare x and assign an initial value of 1


x = 3; // Change the value of x to 3
x = 4 + 5; // Change the value of x to be 4 + 5
int y = 3 ; // Declare y and assign an initial value of 3
y = 2 + x // Change the value of y to be 2 + x where x is equal to 9

}
}
x y

1 2 3 4 5 6 7 8 9 10

9 11 RAM

Dr. Sami Albouq


Do Not Do This
Redeclaring a variable in Java means declaring the same variable
again within the same scope with a different data type or the
same data type. This is not allowed in Java, and it will result
in a compile-time error.

public class Test{


public static void main (String [] args){

int x = 1; // Declare x and assign an initial value of 1

// trying to redeclare variable x with value 10 (this will result in a compile-time error)
int x = 10

}
}

Dr. Sami Albouq


Check Your Knowledge
Do we have a problem in following code segment?
How can we fix the problem?

public class Test{


public static void main (String [] args){

sum = num1 + num2;


System.out.println(”The sum is ” + sum);
}
}

Dr. Sami Albouq


Check Your Knowledge
Do we have a problem in following code segment?
Yes, we do. We did not declare the variables sum, num1, and num2 yet.
How can we fix the problem?
We need to declare sum, num1, and num2 and assign them values.

public class Test{


public static void main (String [] args){

sum = num1 + num2;


System.out.println(”The sum is ” + sum);
}
}

Dr. Sami Albouq


Check Your Knowledge
Do we have a problem in following code segment?
Yes, we do. We did not declare the variables sum, num1, and num2 yet.
How can we fix the problem?
We need to declare sum, num1, and num2 and assign them values.

public class Test{


public static void main (String [] args){

int sum, num1 = 1, num2 = 3;


// after this step the value of sum will be 4.
sum = num1 + num2;
System.out.println(”The sum is ” + sum);
}
sum num1 num2
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

RAM
4 1 3
Dr. Sami Albouq
Primitive Data Types
Basic types in java are called primitive types

• Integer types:
• int: most common
• short, byte: for small integers
• long: for huge values

• Floating point types:


• float: roughly 7 digits of precision
• double: 16 digits of precision
• char: a single character

• boolean: (true or false)

Dr. Sami Albouq


Named Constant
• Constant represents permanent data that never changes.
• A constant must be declared and initialized at the same line
• The word final is a java keyword for declaring a constant
• Example π

final Datatype CONSTANTNAME = Value;

A value of
Java reserved keyword boolean | char | byte Any name that
the same
indicates the value short | int | long meets the
data type
will not change float | double rules of java

Example: final int MAX_SIZE = 100;


final float PI = 3.14159f;
Dr. Sami Albouq
Naming Conventions
• Names of variables should be meaningful and reflect
the data they will store.

int studentAge = 60;


int classRoomNumber = 60;

• Don't skimp on characters, but avoid extremely long


names.

int age = 60;


int IamFromIslamicUniversity_age_whatElse = 60;

Dr. Sami Albouq


Assignment Statements With
Primitive Types

In Java, the assignment statement is used to change


the value of a variable

Dr. Sami Albouq


Assignment Statements With
Primitive Types
• The equal sign (=) is used as the assignment operator
• An assignment statement consists of a variable on the left side of
the operator, and an expression on the right side of the operator
Variable = Expression;

• An expression consists of a variable, number, or mix of variables,


numbers, operators, and/or method invocations

temperature = 98.6;
count = numberOfBeans;

Dr. Sami Albouq


Assignment Statements With
Primitive Types
• When an assignment statement is executed, the expression is first
evaluated, and then the variable on the left-hand side of the equal
sign is set equal to the value of the expression

distance = rate * time;

• Note that a variable can occur on both sides of the assignment


operator
count = count + 2;

Dr. Sami Albouq


Assignment Statements With
Primitive Types
The assignment operator is automatically executed from right-to-left,
so assignment statements can be chained

step 2: number1 = 3

number2 = number1 = 3;

step 3: number2 = step 1: 3 will be


number1 assigned to number 1

Dr. Sami Albouq


Examples

Example 1: int x; // Declare a variable of type int


x = 10; // Assign the value 10 to the variable x
int y = 4; // Declare a variable of type int and initialize it with 4
y = y + x + 4;
Variable y
appeared in
both sides
Expression
Example 2: int a = 5;
int b = 3;
int c = a + b; // Assign the result of the expression "a + b" to the variable c

Variable

Dr. Sami Albouq


Shorthand Assignment
• Shorthand assignment notation combines the assignment operator (=) and
an arithmetic operator
• It is used to change the value of a variable by adding, subtracting,
multiplying, or dividing by a specified value The general form is

Variable Op = Expression
which is equivalent to

Variable = Variable Op (Expression)

• The Expression can be another variable, a constant, or a more


complicated expression
• Some examples of what Op can be are +, -, *, /, or %

Dr. Sami Albouq


Shorthand Assignment
Example: Equivalent To:
count += 2; count = count + 2;

sum -= discount; sum = sum – discount;

bonus *= 2; bonus = bonus * 2;

time /= time =
rushFactor; time / rushFactor;

change %= 100; change = change % 100;

amount *= amount = amount * (count1 +


count1 + count2; count2);

Dr. Sami Albouq


Practice
Here are some examples of shorthand assignments in Java:

1. Addition:
int x = 5;
x += 3; // equivalent to x = x + 3;
System.out.println(x);

2. Moduls
int b = 13;
b %= 5; // equivalent to b = b % 5;
System.out.println(b);

You may see something like this in the exam and the question
will be what is the output of the following statements.

Dr. Sami Albouq


Assignment Compatibility
• In general, the value of one type cannot be stored in a variable of
another type
int intVariable = 2.99; //Illegal

• The above example results in a type mismatch because a double value


cannot be stored in an int variable

• However, there are exceptions to this

double doubleVariable = 2;

For example, an int value can be stored in a double type

Dr. Sami Albouq


Assignment Compatibility
• More generally, a value of any type in the following list can
be assigned to a variable of any type that appears to the right
of it

byte®short®int®long®float®double
char
• Note that as your move down the list from left to right, the
range of allowed values for the types becomes larger
• An explicit type cast is required to assign a value of one type
to a variable whose type appears to the left of it on the above
list (e.g., double to int)
• Note that in Java an int cannot be assigned to a variable of
type boolean, nor can a boolean be assigned to a variable of
type int

Dr. Sami Albouq


Examples assign double
to int var

Example 1: int num = 5.5; // Error: mismatch between int type and floating-point value

Example 2: short s = 256;


byte b = s; // -127 to 128 but s exceeds the size of b
System.out.println(b);
The size of b
is smaller than
s

Example 3: byte b = 100 * 2; // the result exceeds the range -127 to 128
System.out.println(b);

Dr. Sami Albouq


Arithmetic Operators

• As in most languages, expressions can be formed in Java using


variables, constants, and arithmetic operators

• These operators are + (addition), - (subtraction), *


(multiplication), / (division), and % (modulo, remainder)

• An expression can be used anyplace it is legal to use a value of


the type produced by the expression

Dr. Sami Albouq


Arithmetic Operators
Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% Remainder 20 % 3 2

Dr. Sami Albouq


Integer Division
Integer division is a type of division operation that involves
two integer operands, and it returns an integer result. In Java,
integer division is denoted by the / operator.

Example 1: int x = 10;


int y = 3;
int z = x / y; // z will be 3, as the result is rounded down to the nearest integer

Dr. Sami Albouq


Avoid Integer Division
To avoid integer division, you can either use floating-point
division or use type casting to convert one or both of the
integer operands to a floating-point type before performing the
division.

Example 1: int x = 10;


int y = 3;
int z = x / y; // z will be 3, as the result is rounded down to the nearest integer

Example 1: int x = 10;


double y = 3.0;
double z = x / y; // z will be 3.33333,

Dr. Sami Albouq


Examples
Example 1: 5 / 2 yields an integer 2.
Note both are integer values

Example 2: 5.0 / 2 yields a double value 2.5


Note one of then is a floating point value

Example 3: 5 % 2 yields 1 (the remainder of the division)


Note both are integers, but how about 5.5 % 2?

Dr. Sami Albouq


Now You Can Answer :
1.What characters can be used in a Java identifier?
2.Are Java identifiers case-sensitive or case-insensitive?
3.Can Java keywords be used as identifiers?
4.Are there any restrictions on the length of a Java identifier?
5.What is a variable declaration in Java?
6.What are the different data types that can be used for Java
variable declarations?
7.What is the syntax for declaring a variable in Java?
8.Can multiple variables of the same data type be declared in a
single statement in Java?
9.What is the scope of a variable declared in Java, and how does it
affect the visibility and accessibility of the variable within a
program?

Dr. Sami Albouq


Practical Questions:
1.What is the result of 5 / 2 in Java?
Answer: The result is 2, because integer division truncates the
decimal portion of the result.

2.What is the result of 5.0 / 2 in Java?


Answer: The result is 2.5, because floating-point division retains the
decimal portion of the result.

3.What is the result of 1 / 2 in Java?


Answer: The result is 0, because integer division truncates the decimal
portion of the result.

Dr. Sami Albouq


Practical Questions:
1.Declare two integer variables x and y, and assign them values of 10 and 5,
respectively. Then, write a new line of code that adds x and y together and
assigns the result to a new integer variable called z. Finally, print the value
of z to the console.

int x = 10;
int y = 5;
int z = x + y;
System.out.println("The value of z is: " + z);

2. Declare two integer variables m and n, and assign them values of 10 and 2,
respectively. Then, write a new line of code that divides m by n and assigns
the result to a new integer variable called o. Finally, print the value of o to
the console.

int m = 10;
int n = 2;
int o = m / n;
System.out.println("The value of o is: " + o);

Dr. Sami Albouq

You might also like