Java Data Types
Java has two main categories of data types: Primitive and Non-primitive.
Primitive Data Types:
These are the basic data types that represent single values.
Java has eight primitive data types:
Types Description Range
byte 8-bit signed integer -128 to 127
short 16-bit signed integer -32,768 to 32,767
int 32-bit signed integer -2,147,483,648 to 2,147,483,647
long 64-bit signed integer -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 32-bit single-precision floating-point ~6-7 significant decimal digits
number (IEEE 754).
double 64-bit double-precision floating-point ~15-16 significant decimal digits
number (IEEE 754).
boolean Represents a logical value, either true or True, false
false.
char 16-bit Unicode character 0 to 65,535 (unsigned)
Note : ~6-7 significant decimal digits
In Java, the float data type provides approximately 6-7 significant decimal digits of
precision. This means that a float can accurately represent numbers with up to 6-7 total digits, not
just after the decimal point.
For instance, the number 12.12345 can be stored accurately as a float,
but 12.123456789 cannot because it exceeds the precision limit.
It is important to note that the float data type is a 32-bit IEEE 754 single-precision floating-
point number. This format uses a limited number of bits to store the number, which affects the
precision.
If more precision is required,
the double data type should be used, which provides around 15 significant decimal digits
float f = 12.123456f;
System.out.println(f); // Output: 12.123456
float g = 12.1234567f;
System.out.println(g); // Output: 12.123457
In the above example, the number 12.123456 can be accurately stored as a float,
but when we add another digit to the number, the precision is lost.
Built-in data types
A data type is a set of values and a set of operations on those values.
Type Set of values Default value Size Examples of Examples of
(Occupies of values operations
memeory)
byte Integers 0 1 byte (none) add, subtract,
multiply, divide
short Integers 0 2 bytes (none) add, subtract,
multiply, divide
int Integers 0 4 bytes 17, -5, 12345 add, subtract,
multiply, divide
long Integers 0L 8 bytes -2L,0L,1L add, subtract,
multiply, divide
float With decimal 0.0f 4 bytes 3.14f, -1.23e- add, subtract,
numbers 10f multiply, divide
double With decimal 0.0d 8 bytes 3.1415d, add, subtract,
numbers 1.23e100d multiply, divide
boolean Truth values false 1 byte True and, or, not
false
String Sequences of "Hello World" Compare (==, !=),
characters "CS is fun" Concatenate
char characters \u0000 or 0 2 bytes 'A' Compare,
'@' Concatenate
'a',
'\u0041',
'\101',
'\\', '\', '\n', 'β'
char
Characters are enclosed in single quotes, e.g., 'A', '5', '@'.
It can represent letters, numbers, symbols, and control characters.
Internally, characters are stored as numerical values corresponding to their Unicode code points.
For example, 'A' is represented by the number 65.
The range of values that a char variable can hold is from '\u0000' (or 0) to '\uffff' (or 65,535).
Single quotes are used for characters, while double quotes are used for strings.
The char data type is different from a string, which is a sequence of characters.
Java's char is based on the Unicode specification, which allows for a wide range of characters from
different languages.
The default size (as mentioned above) is 2 bytes because Java uses the Unicode system and not the
ASCII code system.
char myChar = 'A';
System.out.println(myChar); // Output: A
char myNumber = '5';
System.out.println(myNumber); // Output: 5
char mySymbol = '@';
System.out.println(mySymbol); // Output: @
char myUnicodeChar = '\u0041'; // Unicode for 'A'
System.out.println(myUnicodeChar); // Output: A
char c1 = 'x';
char c2 = 'X';
System.out.println("c1 is: " +c1); // Output : c1 is x
System.out.println("c2 is: " +c2); // Output : c2 is X
char c1, c2, c3;
c1 = 65;
c2 = 'B';
c3 = 67;
System.out.println("The characters are: " + c1 + c2 + c3); // Output : ABC
char c1 = 'A';
System.out.println("The value of c1 is: " + c1); // A
c1++;
System.out.println("After incrementing: " + c1); // B
c1--;
System.out.println("After decrementing: " + c1); // A
char chars1 = '\u0058';
char chars2 = '\u0059';
char chars3 = '\u005A';
System.out.println("chars1, chars2 and chars2 are: " + chars1 + chars2 + chars3); // XYZ
Non-Primitive Data Types
Non-primitive data types are called reference types because they refer to objects.
The main differences between primitive and non-primitive data types are:
Primitive types in Java are predefined and built into the language,
while non-primitive types are created by the programmer (except for String).
Examples of non-primitive types are
Strings,
Arrays,
Classes
Interface
Object
Difference between Primitive and non-Primitive Datatypes
Primitive types store actual values,
while non-primitive types store references to memory locations where the data is stored.
Primitive types are predefined by Java,
while non-primitive types are created by the programmer.
Primitive types start with a lowercase letter,
while non-primitive types start with an uppercase letter.
Primitive types always hold a value,
whereas non-primitive types can be null.
Non-primitive types can be used to call methods to perform certain operations,
whereas primitive types cannot.
Variable - Literal - Identifiers -
Declaration Statement - Assignment Statement
Variable : A variable is a name that refers to a value.
variable act as containers holding values of various types,
such as numbers, characters, and strings.
data type: In Java, a data type define the type of data that a variable can hold.
variable name: Must follow Java naming conventions (e.g., camelCase).
A name can only be given to a memory location. It can be assigned values in two ways:
1. Variable Initialization
2. Assigning value by taking input
A declaration statement associates a variable with a type.
An assignment statement associates a value with a variable.
Literal : A literal is a programming-language representation of a value.
Identifiers : All Java variables must be identified with unique names.
These unique names are called identifiers.
Declaration Statement Variables
int a;
int b;
Assignment Statement a = 1234;
b = 99;
int c = a + b; Literals
Combined
Declaration and
Assignment Statement
Example : Type String
public class Main {
public static void main(String[] args) {
String name = "Man";
System.out.println(name);
}
}
Example : Type int
public class Main {
public static void main(String[] args) {
int myNum = 125;
System.out.println(myNum);
}
}
Example : Declare a variable without assigning the value
public class Main {
public static void main(String[] args) {
int myNum;
myNum = 125;
System.out.println(myNum);
}
}
Example : Assign a new value to an existing variable, it will overwrite the previous value
public class Main {
public static void main(String[] args) {
int myNum = 125;
myNum = 300; // myNum is now 300
System.out.println(myNum);
}
}
Final Variables
When a variable is declared as final, its value cannot be changed after initialization.
This is useful for creating constants or values that should remain fixed throughout the program's
execution.
A final variable must be initialized either at the time of declaration or within the constructor of the
class if it's an instance variable.
Example : Don't want others to overwrite existing values
public class Main {
public static void main(String[] args) {
final int myNum = 125;
myNum = 300; // will generate an error
System.out.println(myNum);
}
}
Example : Other Types
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
Declare Many Variables
To declare more than one variable of the same type, you can use a comma-separated list:
int x = 5;
int y = 6;
int z = 50;
You can simply write: int x = 5, y = 6, z = 50;
Example : Declare Many Variables
public class Main {
public static void main(String[] args) {
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
}
}
One Value to Multiple Variables
You can also assign the same value to multiple variables in one line:
Example : One Value to Multiple Variables
public class Main {
public static void main(String[] args) {
int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);
}
}
Identifiers
All Java variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or
more descriptive names (age, sum, totalVolume).
Note: It is recommended to use descriptive names in order to create understandable and
maintainable code:
Example : Identifiers
public class Main {
public static void main(String[] args) {
// Good
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;
System.out.println(minutesPerHour);
System.out.println(m);
}
}
Example : Identifiers
public class Main {
public static void main(String[] args) {
// Student data
String studentName = "John Doe";
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25f;
char studentGrade = 'B';
// Print variables
System.out.println("Student name: " + studentName);
System.out.println("Student id: " + studentID);
System.out.println("Student age: " + studentAge);
System.out.println("Student fee: " + studentFee);
System.out.println("Student grade: " + studentGrade);
}
}
The general rules for naming variables are
Names can contain letters, digits, underscores, and dollar signs
Names must begin with a letter
Names should start with a lowercase letter, and cannot contain whitespace
Names can also begin with $ and _
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
built-in numeric types
byte Stores whole numbers from -128 to 127
short Stores whole numbers from -32,768 to 32,767
int Stores whole numbers from -2,147,483,648 to 2,147,483,647
long Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
doubleStores fractional numbers. Sufficient for storing 15 to 16 decimal digits
Example : built-in numeric types
public class Main {
public static void main(String[] args) {
byte myNum1 = 100;
short myNum2 = 5000;
int myNum3 = 100000;
long myNum4 = 15000000000L;
float myNum5 = 5.75f;
double myNum6 = 19.99d;
System.out.println(myNum1);
System.out.println(myNum2);
System.out.println(myNum3);
System.out.println(myNum4);
System.out.println(myNum5);
System.out.println(myNum6);
}
}
Use float or 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 16 digits.
Therefore it is safer to use double for most calculations.
Types of Java Variables
Java has different types of variables which are listed as follows:
Local Variables
Instance Variables
Static Variables
Local Variables
A variable defined within a block or method or constructor is called a local variable.
The Local variable is created at the time of declaration and destroyed when the function completed
its execution.
The scope of local variables exists only within the block in which they are declared.
We first need to initialize a local variable before using it within its scope.
Example: This example show how a local variable is declared and used inside the main method and
it can not be used outside of it.
// Java Program to show the use of local variables
import java.io.*;
class Geeks {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}
}
Key aspects of variables in Java
Data Type: Specifies the kind of data a variable can store (e.g., int for integers, String for
text, float for decimal numbers).
Variable Name: A unique identifier following Java naming rules
Value: The actual data assigned to the variable.
Primitive Data Types:
byte, short, int, long: For whole numbers.
float, double: For decimal numbers.
char: For single characters.
boolean: For true or false values.
Other types:
String: For text.
Arrays: To store a fixed number of values of a single type.
Lists: To store a dynamic number of values of a single type.
Final Variables
Variables declared with the final keyword can only be assigned once and act as constants.
Initialization
Variables must be initialized before use, either at the time of declaration or later in the
program. Local variables do not have default values and must be explicitly initialized.
Scope of Variables
The scope of a variable determines where it can be accessed in the program. Local variables
are limited to their block, while instance and class variables have broader accessibility.
Note : 1. Static Variable , Instance Variable – Refer Oops Concepts
Important : Using uninitialized local variables: Accessing a local variable without initializing it
leads to a compile-time error.
Tips and Best Practices
Naming Conventions: Use meaningful variable names and follow Java naming conventions
(camelCase for variables).
camelCase Example : firstName, calculateTotalPrice, or getUserData.
Initialization: Initialize variables before use to avoid runtime errors.
Scope Awareness: Understand the scope of variables to prevent access violations and ensure proper
memory management.
Use Constants: For values that do not change, use the final keyword to declare constants.
final int MAX_VALUE = 100;
Avoid Global Variables: Minimize the use of static variables to reduce dependencies and improve
code maintainability.
Type Compatibility: Ensure that the data type of a variable is compatible with the values assigned
to it to prevent type mismatches.
Variable Reassignment: Be mindful of variable reassignment, especially with final variables, as it
can lead to errors if attempted.
Reference
Pascal Case vs. Camel Case vs snake_case vs kebab-case
https://builtin.com/articles/pascal-case-vs-camel-case