Real-Life Examples
Java Variables - Examples
In our examples, we frequently shorten variable names to reflect the type of data they represent (for example, myChar for char types, myInt or myNum for int types). Confusion is avoided by doing this.
However, we have developed a software that keeps various pieces of information on a college student as a useful example of utilizing variables:
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 practical example, we write a program that multiplies the length and breadth to find a rectangle’s area:
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);