Data Types

 

PRIMITIVE DATA TYPES


Boolean: Representing whether a light switch is turned on (true) or off (false).

boolean isRaining = true;

boolean isButtonClicked = false;

// Listen for button clicks and set isButtonClicked to true when clicked


Byte: Storing a person’s age in a school application.

byte age = 25;


Short: Representing the number of students in a class.

short temperature = -10;

short numberOfStudents = 2500;

short yearOfBirth = 1995


Int: Storing the population of a city, where the count is within the range of the int data type.

int population = 1000000;


Long: Recording the distance traveled by a vehicle, where the distance can be very large.

long distance = 3000000000L;


Float: Storing the temperature readings in a weather application, where the data may have decimal points.

float weightPounds = 150.7f;

float temperatureCelsius = 25.5f;


Double: Double is for super precise decimal numbers used in math, science, money, and important calculations.

double interestRate = 0.045; // 4.5% interest rate

double investmentReturn = 0.072; // 7.2% return on investment

double distanceInMeters = 458.92;

double atomicMass = 45.56;


Char: Storing a single character, such as a letter or digit, like ‘A’, ‘b’, ‘5’. ‘$’, etc.

char grade = ‘A’;

char symbol = ‘$’;


REFERENCE DATA TYPES: Do not have a fixed size in terms of bits and bytes.

  • Reference data types in Java are used to store memory addresses that point to objects created in the heap. They do not directly hold the object’s data but instead store the memory location where the object is stored.

String: In real life, strings are widely used for handling names, messages, and textual data.

String name = “John”;

// The reference variable ‘name’ points to a String object in memory.

String message = “Hello, World!”;

/ The ‘message’ variable references a String object.


Arrays: Arrays used to store collections of elements of the same type. In real life, arrays can represent lists of items like student names or temperatures.

int[] studentGrades = {85, 92, 78, 90, 88};

// Each element in the array represents the grade of an individual student.

double[] dailyTemperatures = {25.5, 28.2, 26.8, 24.0, 27.3, 29.1, 30.5};

// Each element represents the temperature on a specific day.

String[] shoppingList = {“Milk”, “Bread”, “Eggs”, “Fruits”, “Vegetables”};

// used to represent a shopping list, where each element is an item to buy.


Data Type Group Assignment

  • Initialize new variables for each data type. Use println() to display the value of each variable.
  • Start here