Lecture 2 Datatypes and Variables
Lecture 2 Datatypes and Variables
This can be used instead of int or other integer types to save memory when you are certain that the value will be within -128 and
127.
2. short •value ranges from -(216)/2 to (216)/2 - 1
•Stores whole numbers from -32,768 to 32,767
• takes 2 byte
6. double Datatype:
•Stores fractional numbers. Sufficient for storing 15 decimal digits
•takes 8 byte. Note that you should end the value with a “d"
Default Datatype of a Value
In case of Integral values, the default datatype of a value would be Integer
In case of Fractional Values, the default datatype of a value would be
Double
The precision of a floating point value indicates how many digits the
value can have after the decimal point.
The precision of float is only six or seven decimal digits, while double
variables have a precision of about 15 digits.
Therefore it is safer to use double for most calculations.
Primitive Data Types
7. char Datatype
•Stores a single character/letter
•takes 2 bytes
(In other programming languages like c, char is of 1 byte only because it was holding the
ASCI values only).
But in Java, char is capable of holding the characters not limited to English Language
only.
So, instead of ASCII, UNICODE value is stored.
char charname= ‘A’; //the values must be enclosed within Single Quotes only
char charname2=“B”; //Double Quotes are used for Strings only.
8. Boolean Datatype
•value can be true or false
•1 bit
boolean b=1 //will give compile time error (incompatible types: int cannot be
converted to Boolean)
Output?
.
How to choose data types for our variables
In order to choose the data type, we first need to find the type of data,
we want to store.
After that, we need to analyse the min & max value we might use.
Strings Data type
• The String data type is used to store a sequence of characters (text).
String values must be surrounded by double quotes:
String greeting = "Hello World";
System.out.println(greeting);