Java Fundamentals
CPIT 202
Week 2 Lecture 2
Java Primitive Data Types
Java’s Eight Primitive Data Types
DATA TYPE SIZE MIN VALUE MAX VALUE
byte 8 bits ‐128 127
short 16 bits ‐32768 32767
int 32 bits –2147483648 2147483647
long 64 bits –9223372036854775808 9223372036854775807 long 64 bits 9223372036854775808 9223372036854775807 float 32 bits ±1.40239846E‐45 ±3.40282347E+8
double 64 bits ±4.94065645841246544E 324
±1.79769313486231570E +308
‐324 +308
char 16 bits \u0000 \uFFFF
boolean n/a true or false
3 Java Programming
Variables
Variables are used to store data. In Java, a
i bl d t b d l d
variable needs to be declared.
Declaring a variable involves two steps:
Giving the variable a name
Stating what type of data is to be stored in the variable
short x;
short x;
int age;
float salary;
Declaring Variables
int x; // Declare x to be an int x; // Declare x to be an
// integer variable;
d bl di // l di
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a // character variable;
// character variable;
Assigning Variables
Use the assignment operator = to assign a
i bl t ti l l
variable to a particular value.
int x; // declare a variable 12 // i 12 t th
x = 12; // assign 12 to the var Or we can do the declaration and initialisation at
f
the same time, like the following int x = 12;;
Integral Types
From the eight primitive data types, 4 of them diff l b th i i
are differ only by their size :
byte, short, int, long int x = 250;
Example :
short a, b;
a = 21;
a 21;
b = 9;
Java Programming
long y = 12345678987654321L;
7
Floating‐Point Types
Two of the eight primitive data types are used
f t i b
for storing numbers:
float, double Example :
double pi = 3.14159;
float f = 2.7F;
Boolean Data Type
Only one from the eight primitive data types is
d t t B l l
used to represent Boolean values:
boolean Example :
char a = ‘A’;
char half = ‘\u00AB’;
char half \u00AB ;
Java Programming 9
Char Data Type
The char data type represents characters in Java
Java.
Single quote ‘ ’ are used to denote a character literal
ESCAPE SEQUENCE
DEFINITION
\t tab
char a = ‘A’;
literal.
\t tab
\b backspace
\n newline
char half = ‘\u00AB’;
\r carriage return
\’ single quote
\” double quote
Strings
A string is a sequence of characters.
Treated as a single item.
Enclosed in double quote “ “.
“The quick brown fox jumps over the lazy cat”
string greeting = “Good Morning!!\n”;
Example :
string greeting = Good Morning!!\n ;
string errorMessage = “Record Not Found!”;
Java Programming 11
Constants
The final keyword is used, makes a constant.
Cannot be changed after it is assigned a value.
final Example :
final double pi = 3.14159;
final int x;