Data Type in Java
Data Type in Java
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Boolean Types
Very often in programming, you will need a data type that can only have one of two values,
like:
YES / NO
ON / OFF
TRUE / FALSE
For this, Java has a boolean data type, which can only take the values true or false:
Example
Characters
The char data type is used to store a single character. The character
must be surrounded by single quotes, like 'A' or 'c':
Example
System.out.println(myGrade);
Byte
The byte data type can store whole numbers from -128 to 127. 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:
Example
System.out.println(myNum);
Short
The short data type can store whole numbers from -32768 to 32767:
Example
System.out.println(myNum);
Int
The int data type can store whole numbers from -2147483648 to
2147483647. In general, and in our tutorial, the int data type is
the preferred data type when we create variables with a numeric
value.
Example
System.out.println(myNum);
Long
Example
System.out.println(myNum);
The float and double data types can store fractional numbers. Note that
you should end the value with an "f" for floats and "d" for doubles:
Float Example
System.out.println(myNum);
Double Example
double myNum = 19.99d;
System.out.println(myNum);
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.
1. Strings
Strings are defined as an array of characters. The difference between a character
array and a string in Java is, that the string is designed to hold a sequence of
characters in a single variable whereas, a character array is a collection of separate
char-type entities.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:
// Declare String without using new operator
String s = "Hello Java";
// Declare String using new operator
String s1 = new String("Hello Java");
2. Arrays
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
String[] cars;