Primitive Data Types in Java

Integer Types

The integer types in Java are byte, short, int, and long. All integral types represent signed numbers;

Example of Primitive int
Code fragment defining, using int variables:

int secondsPerMinute = 60;
int minutesPerHour = 60;
int hoursPerDay =24;
int daysPerWeek =7;
int secondsPerWeek = secondsPerMinute *
minutesPerHour * hoursPerDay * daysPerWeek;
JOptionPane.showMessageDialog(null,
"There are " + secondsPerWeek +
" seconds per week");

int Operation Examples
int i = 5;
int j = 7;
int sumij = i + j; // 12
int diffij = i - j; // -2
int prodij = i * j; // 35
int divij = i / j; // 0
int remij = i % j; // 5
int divji = j / i; // 1
int remji = j % i; // 2

Double Types

Example of Primitive double
Code fragment:

double lbsPerKg = 2.205;
double mPerInch = 0.0254;
double height = 70.5;
double weight = 183.;
double heightMetres = height * mPerInch ;
double bmi = (weight / lbsPerKg) /
(heightMetres * heightMetres); // body mass index
System.out.println("Your body mass index is " + bmi);

double Operation Examples
double x = 5.e20; // 5.e20 = 5 * 1020
double y = 7.0e20;
double sumxy = x + y; // 1.2e21
double diffxy = x - y; // -2.0e20
double prodxy = x * y; // 3.5e41
double divxy = x / y; // .7142857142857143
double remxy = x % y; // 5.0e20
double divxy = y / x; // 1.4
double remxy = y % x; // 2.0e20

The Boolean Type
The Boolean type represents truth values. This type has only two possible values, representing the two Boolean states: on or off, yes or no, true or false. Java reserves the words true and false to represent these two Boolean values.

Example of Primitive boolean
boolean canBeCaught = true;
boolean canBeThrown = false;
What am I?

boolean goesAroundTheWorld = true;
boolean staysInACorner = true;
What am I?

The char Type
The char type represents Unicode characters.

Example of char type
char c = 'A';

________________________________________

No comments: