Java Variables - Examples with Real-Life Applications

Explore practical examples of Java variables used to store real-life data, such as information about a college student. Learn how to use different data types effectively, with clear examples and explanations.



Java Variables - Examples

Real-Life Examples

Oftentimes in examples, variable names are simplified to match their data type (like myInt or myNum for int types, myChar for char types, etc.) to avoid confusion. Here's a practical example using variables to store data about a college student:

Student Data Example
// 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);

Calculate the Area of a Rectangle

In this example, we create a program to calculate the area of a rectangle by multiplying its length and width:

Rectangle Area Calculation Example
// Create integer variables
int length = 4;
int width = 6;
int area;

// Calculate the area of a rectangle
area = length * width;

// Print variables
System.out.println("Length is: " + length);
System.out.println("Width is: " + width);
System.out.println("Area of the rectangle is: " + area);