Week2-L2-Variables and Data Types
Week2-L2-Variables and Data Types
int data=10;
Names can contain letters, digits,
underscores, and dollar signs
Names must begin with a letter
Names can also begin with $ and _
Names cannot contain whitespace
Names are case sensitive ("myVar" and
"myvar" are different variables)
Reserved words (like Java keywords, such as
int or boolean) cannot be used as names
Variable names are preferred to be self-
declarative (has a meaning for the reader).
It is a tradition to use Camel Case for naming
variables with multiple words.
Variable name / Comments
myAddress
_test
$1 Not self declarative
myNewDevice
First One White space included
Last1
A variable can hold a specific type of data.
There are different types of data, the
following are the commonly used data types
in java.
String - stores text, such as "Hello". String values
are surrounded by double quotes
int - stores integers (whole numbers), without
decimals, such as 123 or -123
float - stores floating point numbers, with
decimals, such as 19.99 or -19.99
double- stores floating point numbers, with
decimals, using a double precision.
char - stores single characters, such as 'a' or 'B'.
Char values are surrounded by single quotes
boolean - stores values with two states: true or
false
Primitive data types - includes
byte,
short,
int,
long,
float,
double,
boolean and
char
Non-primitive
data types - such as String,
Arrays and Classes
Syntax
<data type> <variableName> ;
Example:
int myAge;
double employeeSalary;
String employeeName;
boolean married;
int x,y,z;
Syntax:
<data type> <variableName> = <value> ;
Example:
int myAge = 34;
double employeeSalary = 2336.50;
String employeeName = “Mohamed”;
boolean married = true;
char bloodType = ‘A’;
int x=9,y=6;
x = y = 77;
A primitive data type specifies the size
and type of variable values, and it has no
additional methods.
Data Type Size Description
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Narrowing Casting (manually) - converting
a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte