Java Basics, Variables and Data Types Practice Questions with Solutions

Java is one of the world’s most popular programming languages, known for its simplicity, platform independence, security, and object-oriented features. Whether you’re preparing for coding interviews, college exams, placement tests, or improving your programming skills, learning Java fundamentals is the first step toward becoming a proficient Java developer.

Every Java program starts with understanding variables, data types, identifiers, keywords, and basic input/output operations. These concepts form the foundation for advanced topics like Object-Oriented Programming (OOP), Collections Framework, Multithreading, JDBC, Spring Boot, Android Development, and Enterprise Applications.

Java follows the principle of “Write Once, Run Anywhere (WORA)”, meaning a Java program can run on any operating system that has the Java Virtual Machine (JVM) installed.

In this chapter, you’ll solve beginner-friendly Java practice questions focused on variables, data types, operators, and basic programming concepts. Each question includes a complete Java solution, sample input and output, explanation, and key concepts to help you strengthen your understanding. Java Basics, Variables and Data Types practice questions with solutions help to understand the concepts.


1. Java Program to Print “Hello, World!”

Problem Statement

Write a Java program to print Hello, World! on the screen.

Java Solution

public class Main {

    public static void main(String[] args) {

        System.out.println("Hello, World!");

    }

}

Sample Output

Hello, World!

Explanation

  • Every Java program begins with a class.
  • The main() method is the entry point of the program.
  • System.out.println() prints text on the console followed by a new line.

Concepts Covered

  • Java Program Structure
  • main() Method
  • System.out.println()
  • Java Syntax

2. Java Program to Print Your Name

Problem Statement

Write a Java program to print your name.

Java Solution

public class Main {

    public static void main(String[] args) {

        System.out.println("Rishabh Kumar");

    }

}

Sample Output

Rishabh Kumar

Explanation

This program demonstrates how to display text using the println() method.

Concepts Covered

  • Output Statements
  • String Literals
  • Java Basics

3. Java Program to Declare and Display Variables

Problem Statement

Write a Java program to declare variables of different data types and display their values.

Java Solution

public class Main {

    public static void main(String[] args) {

        int age = 22;
        double salary = 55000.75;
        char grade = 'A';
        boolean isPlaced = true;
        String city = "Delhi";

        System.out.println("Age: " + age);
        System.out.println("Salary: " + salary);
        System.out.println("Grade: " + grade);
        System.out.println("Placed: " + isPlaced);
        System.out.println("City: " + city);

    }

}

Sample Output

Age: 22
Salary: 55000.75
Grade: A
Placed: true
City: Delhi

Explanation

This program demonstrates the declaration and initialization of different Java data types.

Data TypeDescription
intStores integers
doubleStores decimal values
charStores a single character
booleanStores true or false
StringStores text

Concepts Covered

  • Variables
  • Primitive Data Types
  • String
  • Variable Initialization

4. Java Program to Add Two Numbers

Problem Statement

Write a Java program to add two numbers entered by the user.

Java Solution

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int firstNumber, secondNumber, sum;

        System.out.print("Enter First Number: ");
        firstNumber = scanner.nextInt();

        System.out.print("Enter Second Number: ");
        secondNumber = scanner.nextInt();

        sum = firstNumber + secondNumber;

        System.out.println("Sum = " + sum);

        scanner.close();
    }

}

Sample Input

Enter First Number: 25
Enter Second Number: 30

Sample Output

Sum = 55

Explanation

  • The Scanner class is used to read user input.
  • Two integer values are accepted from the keyboard.
  • The + operator adds both numbers.
  • The result is displayed using System.out.println().

Concepts Covered

  • Scanner Class
  • User Input
  • Variables
  • Arithmetic Operator
  • Integer Data Type

5. Java Program to Swap Two Numbers Using a Third Variable

Problem Statement

Write a Java program to swap two numbers using a third variable.

Java Solution

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int firstNumber, secondNumber, temp;

        System.out.print("Enter First Number: ");
        firstNumber = scanner.nextInt();

        System.out.print("Enter Second Number: ");
        secondNumber = scanner.nextInt();

        temp = firstNumber;
        firstNumber = secondNumber;
        secondNumber = temp;

        System.out.println("After Swapping:");
        System.out.println("First Number = " + firstNumber);
        System.out.println("Second Number = " + secondNumber);

        scanner.close();
    }

}

Sample Input

Enter First Number: 15
Enter Second Number: 40

Sample Output

After Swapping:
First Number = 40
Second Number = 15

Explanation

A temporary variable stores the value of the first number before the values are exchanged.

Swapping Steps

  1. Store the first number in temp.
  2. Assign the second number to the first number.
  3. Assign the value of temp to the second number.

Concepts Covered

  • Variables
  • Temporary Variable
  • Assignment Operator
  • Scanner Class

6. Java Program to Swap Two Numbers Without Using a Third Variable

Problem Statement

Write a Java program to swap two numbers without using a third variable.

Java Solution

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int firstNumber, secondNumber;

        System.out.print("Enter First Number: ");
        firstNumber = scanner.nextInt();

        System.out.print("Enter Second Number: ");
        secondNumber = scanner.nextInt();

        firstNumber = firstNumber + secondNumber;
        secondNumber = firstNumber - secondNumber;
        firstNumber = firstNumber - secondNumber;

        System.out.println("After Swapping:");
        System.out.println("First Number = " + firstNumber);
        System.out.println("Second Number = " + secondNumber);

        scanner.close();
    }

}

Sample Input

Enter First Number: 10
Enter Second Number: 25

Sample Output

After Swapping:
First Number = 25
Second Number = 10

Explanation

The program swaps the values using arithmetic operations instead of a temporary variable.

Swapping Logic

a = a + b
b = a - b
a = a - b

Concepts Covered

  • Arithmetic Operators
  • Variables
  • Swapping Logic

7. Java Program to Find the Square of a Number

Problem Statement

Write a Java program to calculate the square of a number entered by the user.

Java Solution

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int number;

        System.out.print("Enter a Number: ");
        number = scanner.nextInt();

        System.out.println("Square = " + (number * number));

        scanner.close();
    }

}

Sample Input

Enter a Number: 8

Sample Output

Square = 64

Explanation

The square of a number is calculated by multiplying the number by itself.

Formula:

Square = Number × Number

Concepts Covered

  • Multiplication
  • Variables
  • Arithmetic Operators

8. Java Program to Find the Cube of a Number

Problem Statement

Write a Java program to calculate the cube of a number.

Java Solution

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int number;

        System.out.print("Enter a Number: ");
        number = scanner.nextInt();

        System.out.println("Cube = " + (number * number * number));

        scanner.close();
    }

}

Sample Input

Enter a Number: 4

Sample Output

Cube = 64

Explanation

The cube of a number is calculated by multiplying the number three times.

Formula:

Cube = Number × Number × Number

Concepts Covered

  • Arithmetic Operators
  • Variables
  • Mathematical Calculations

9. Java Program to Calculate the Area of a Rectangle

Problem Statement

Write a Java program to calculate the area of a rectangle.

Java Solution

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        double length, width;

        System.out.print("Enter Length: ");
        length = scanner.nextDouble();

        System.out.print("Enter Width: ");
        width = scanner.nextDouble();

        System.out.println("Area = " + (length * width));

        scanner.close();
    }

}

Sample Input

Enter Length: 10
Enter Width: 5

Sample Output

Area = 50.0

Explanation

Formula:

Area = Length × Width

Concepts Covered

  • Variables
  • User Input
  • Arithmetic Operations
  • Rectangle Formula

10. Java Program to Calculate the Area of a Circle

Problem Statement

Write a Java program to calculate the area of a circle.

Java Solution

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        double radius;
        double area;

        System.out.print("Enter Radius: ");
        radius = scanner.nextDouble();

        area = Math.PI * radius * radius;

        System.out.println("Area = " + area);

        scanner.close();
    }

}

Sample Input

Enter Radius: 7

Sample Output

Area = 153.93804002589985

Explanation

Formula:

Area = π × Radius²

Math.PI provides the value of π in Java, making calculations more accurate.

Concepts Covered

  • Math.PI
  • Variables
  • Mathematical Formula
  • Circle Area Calculation

11. Java Program to Calculate Simple Interest

Problem Statement

Write a Java program to calculate Simple Interest using the principal amount, rate of interest, and time entered by the user.

Java Solution

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        double principal, rate, time, simpleInterest;

        System.out.print("Enter Principal Amount: ");
        principal = scanner.nextDouble();

        System.out.print("Enter Rate of Interest: ");
        rate = scanner.nextDouble();

        System.out.print("Enter Time (Years): ");
        time = scanner.nextDouble();

        simpleInterest = (principal * rate * time) / 100;

        System.out.println("Simple Interest = " + simpleInterest);

        scanner.close();
    }

}

Sample Input

Enter Principal Amount: 5000
Enter Rate of Interest: 8
Enter Time (Years): 2

Sample Output

Simple Interest = 800.0

Explanation

Formula:

Simple Interest = (Principal × Rate × Time) / 100

The program accepts the required values from the user and calculates the Simple Interest using the standard formula.

Concepts Covered

  • Variables
  • User Input
  • Mathematical Formula
  • Arithmetic Operators

12. Java Program to Find the Average of Three Numbers

Problem Statement

Write a Java program to calculate the average of three numbers.

Java Solution

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        double firstNumber, secondNumber, thirdNumber, average;

        System.out.print("Enter First Number: ");
        firstNumber = scanner.nextDouble();

        System.out.print("Enter Second Number: ");
        secondNumber = scanner.nextDouble();

        System.out.print("Enter Third Number: ");
        thirdNumber = scanner.nextDouble();

        average = (firstNumber + secondNumber + thirdNumber) / 3;

        System.out.println("Average = " + average);

        scanner.close();
    }

}

Sample Input

Enter First Number: 10
Enter Second Number: 20
Enter Third Number: 30

Sample Output

Average = 20.0

Explanation

The average is calculated by adding all numbers and dividing the total by the number of values.

Formula:

Average = (A + B + C) / 3

Concepts Covered

  • Arithmetic Operators
  • Variables
  • User Input
  • Average Formula

13. Java Program to Convert Celsius to Fahrenheit

Problem Statement

Write a Java program to convert temperature from Celsius to Fahrenheit.

Java Solution

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        double celsius, fahrenheit;

        System.out.print("Enter Temperature in Celsius: ");
        celsius = scanner.nextDouble();

        fahrenheit = (celsius * 9 / 5) + 32;

        System.out.println("Temperature in Fahrenheit = " + fahrenheit);

        scanner.close();
    }

}

Sample Input

Enter Temperature in Celsius: 25

Sample Output

Temperature in Fahrenheit = 77.0

Explanation

Formula:

F = (C × 9/5) + 32

Concepts Covered

  • Temperature Conversion
  • Mathematical Formula
  • Variables
  • User Input

14. Java Program to Convert Fahrenheit to Celsius

Problem Statement

Write a Java program to convert temperature from Fahrenheit to Celsius.

Java Solution

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        double fahrenheit, celsius;

        System.out.print("Enter Temperature in Fahrenheit: ");
        fahrenheit = scanner.nextDouble();

        celsius = (fahrenheit - 32) * 5 / 9;

        System.out.println("Temperature in Celsius = " + celsius);

        scanner.close();
    }

}

Sample Input

Enter Temperature in Fahrenheit: 98.6

Sample Output

Temperature in Celsius = 37.0

Explanation

Formula:

C = (F − 32) × 5/9

Concepts Covered

  • Temperature Conversion
  • Variables
  • Arithmetic Operators
  • User Input

15. Java Program to Display ASCII Value of a Character

Problem Statement

Write a Java program to display the ASCII value of a character.

Java Solution

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        char character;

        System.out.print("Enter a Character: ");
        character = scanner.next().charAt(0);

        int asciiValue = (int) character;

        System.out.println("ASCII Value = " + asciiValue);

        scanner.close();
    }

}

Sample Input

Enter a Character: A

Sample Output

ASCII Value = 65

Explanation

In Java, every character has a corresponding ASCII (Unicode) value. Type casting a char to an int returns its numeric value.

Example:

A → 65
a → 97
0 → 48

Concepts Covered

  • Character Data Type
  • Type Casting
  • ASCII Values
  • Unicode Representation

Chapter Summary

In this chapter, you learned the fundamentals of Java programming by solving beginner-friendly practice questions based on variables, data types, user input, arithmetic operations, mathematical formulas, and type casting. These concepts form the foundation for advanced Java topics such as operators, conditional statements, loops, methods, object-oriented programming (OOP), collections, multithreading, and Spring Boot development.

You practiced writing Java programs to display output, read user input using the Scanner class, perform calculations, convert temperatures, calculate areas, swap numbers, compute averages, determine ASCII values, and apply basic mathematical formulas.

Mastering these core concepts will make it easier to understand more advanced Java programming topics and improve your problem-solving skills.


Key Takeaways

  • Every Java program starts execution from the main() method.
  • Variables are used to store data in memory.
  • Java provides primitive data types such as int, double, char, boolean, and long.
  • The Scanner class is commonly used to accept user input.
  • Arithmetic operators perform mathematical calculations.
  • Java supports automatic and explicit type casting.
  • Math.PI provides an accurate value of π.
  • Characters can be converted into ASCII (Unicode) values through type casting.
  • Writing small practice programs strengthens Java programming fundamentals.
  • A strong understanding of Java basics is essential before learning OOP, Collections, JDBC, and Spring Framework.

Frequently Asked Questions (FAQs)

1. What is Java?

Java is a high-level, object-oriented programming language developed by Sun Microsystems (now Oracle). It follows the Write Once, Run Anywhere (WORA) principle.


2. What is the purpose of the main() method?

The main() method is the entry point of every Java application. Program execution begins from this method.


3. What are variables in Java?

Variables are named memory locations used to store data that can be accessed and modified during program execution.

Example:

int age = 20;

4. What are primitive data types in Java?

Java provides eight primitive data types:

  • byte
  • short
  • int
  • long
  • float
  • double
  • char
  • boolean

5. Why is the Scanner class used in Java?

The Scanner class is used to accept input from the keyboard during program execution.

Example:

Scanner scanner = new Scanner(System.in);

6. What is type casting in Java?

Type casting converts one data type into another.

Example:

double value = 10.5;
int number = (int) value;

7. What is the difference between print() and println()?

  • print() displays output without moving to the next line.
  • println() displays output and moves the cursor to the next line.

8. Why should beginners practice Java programming questions?

Practicing Java programs improves logical thinking, strengthens programming fundamentals, and prepares you for coding interviews, placement tests, university exams, and real-world software development.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top