Chapter 2 - 1
Chapter 2 - 1
Example:
public class Welcome
Examples:
Examples:
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
} 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){
}
}
x y
1 2 3 4 5 6 7 8 9 10
9 11 RAM
// trying to redeclare variable x with value 10 (this will result in a compile-time error)
int x = 10
}
}
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
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
temperature = 98.6;
count = numberOfBeans;
step 2: number1 = 3
number2 = number1 = 3;
Variable
Variable Op = Expression
which is equivalent to
time /= time =
rushFactor; time / rushFactor;
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.
double doubleVariable = 2;
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
Example 1: int num = 5.5; // Error: mismatch between int type and floating-point value
Example 3: byte b = 100 * 2; // the result exceeds the range -127 to 128
System.out.println(b);
+ Addition 34 + 1 35
% Remainder 20 % 3 2
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);