java fundamentals - kaujava fundamentals cpit 202. week 2 lecture 2 java primitive data types....
TRANSCRIPT
Java Fundamentals
CPIT 202
Week 2Lecture 2
Java Primitive Data Types
Java’s Eight Primitive Data TypesDATA 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 9223372036854775807long 64 bits 9223372036854775808 9223372036854775807
float 32 bits ±1.40239846E‐45 ±3.40282347E+8double 64 bits ±4.94065645841246544E
324±1.79769313486231570E+308‐324 +308
char 16 bits \u0000 \uFFFF
boolean n/a true or false
3Java Programming
Variables
Variables are used to store data. In Java, a i bl d t b d l dvariable 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;
Java Programming 4
Declaring Variables
int x; // Declare x to be anint x; // Declare x to be an// integer variable;
d bl di // l didouble 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 lvariable to a particular value.
int x; // declare a variable12 // i 12 t thx = 12; // assign 12 to the var
Or we can do the declaration and initialisation at fthe same time, like the following
int x = 12;;
Java Programming 6
Integral Types
From the eight primitive data types, 4 of them diff l b th i iare 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 bfor storing numbers: float, double
Example :
double pi = 3.14159;float f = 2.7F;
Java Programming 8
Boolean Data Type
Only one from the eight primitive data types is d t t B l lused to represent Boolean values:
boolean
Example :
char a = ‘A’;char half = ‘\u00AB’;char half \u00AB ;
Java Programming 9
Char Data TypeThe char data type represents characters in JavaJava.
Single quote ‘ ’ are used to denote a character literal
ESCAPE SEQUENCE
DEFINITION
\t tabchar a = ‘A’;
literal.
\t tab
\b backspace
\n newlinechar half = ‘\u00AB’;\r carriage return
\’ single quote
\” double quote
10Java Programming
\\ backslash
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;
Java Programming 12
End of lecture 2