Building blocks – Java

Objectives:

  • Identify and differentiate the eight built-in primitive data types in Java
  • Declare variables and assign values to them
  • Define constant values using the final keyword
  • Use the Scanner class to receive input from the keyboard
  • Outline the functionality of a method using pseudocode

Introduction

The “Hello World” program we created in first Topic is, of course, very simple. One of its main limitations is that it doesn’t work with any data. For a program to produce meaningful results, it must be able to store and manipulate data. For example, a calculator would be useless if it couldn’t store the numbers the user enters to perform addition or multiplication. That’s why, when learning any programming language, one of the first questions you should ask is: “What types of data can this language store in a program?”

Simple Data types in Java

We begin our exploration of Java’s data handling capabilities by looking at the basic data types available in the language. In programming, the kind of value a variable can hold is referred to as its data type. For instance, if you want to store the price of a cinema ticket, you’ll likely need a real number (a number with decimal places). On the other hand, if you’re storing the number of tickets sold, an integer (a whole number) would be more appropriate. Understanding what types of data can be stored is essential when learning any programming language.

Java provides several simple built-in data types known as primitive types. These are also called scalar types because they each represent a single piece of data, such as a number or a character.

The table below summarizes Java’s primitive types, the kind of values they represent, and their range:

Java TypeDescriptionRange of Values
byteVery small integers-128 to 127
shortSmall integers-32,768 to 32,767
intLarge integers-2,147,483,648 to 2,147,483,647
longVery large integers-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
floatSingle-precision real numbers±1.4 × 10⁻⁴⁵ to ±3.4 × 10³⁸
doubleDouble-precision real numbers±4.9 × 10⁻³²⁴ to ±1.8 × 10³⁰⁸
charCharactersUnicode character set
booleanTrue or false valuestrue or false

As you can see, there are multiple types available for representing integers and real numbers. For example, integers can be stored using byte, short, int, or long, each differing in the range of values they can represent. All numeric types in Java support both positive and negative values, but the size of the number each can hold varies. Importantly, these ranges are fixed across all Java compilers and operating systems, unlike in some other languages.

The char type is used to represent characters from the Unicode character set, which includes nearly all characters from the world’s languages. For simplicity, you can think of it as covering any character you can type on your keyboard.

Finally, the Boolean type holds one of two values: true or false. This is especially useful in making decisions in a program. For example, to answer the question “Did I pass my exam?” you can use a Boolean variable: true for yes, and false for no.

Declaring variables in Java

The data types listed in Table 2.1 are used to create named locations in a computer’s memory to hold values while a program is running. This process is known as declaring variables. These named memory locations are called variables because their values can change throughout the life of the program.

For example, imagine a computer game where a player’s score increases as they collect secret keys in a haunted house. This score is a piece of data that changes during the game, so it would be stored in a variable.

To create a variable in Java, you need to:

  • Choose a name for the variable
  • Decide which data type best suits the kind of data you want to store

Let’s say we want to store the player’s score. A good variable name might be score—it clearly describes the data’s purpose. While you could use a name like x, meaningful names make your code easier to read and maintain.

When naming variables in Java, follow these conventions:

  • Start variable names with a lowercase letter
  • Avoid spaces (use camelCase like playerScore or underscores like player_score)
  • Ensure the name reflects the variable’s purpose

Now, what data type should we use for score? Since a score is always a whole number, an integer type is appropriate. Java provides four integer types: byte, short, int, and long. These differ only in the range of values they can store. Unless there’s a specific need for a smaller or larger range, the int type is the most commonly used.

So, to declare a score variable, you would write:

int score;

This line sets aside a small portion of memory to hold an integer value. You can think of it as creating a labeled “box” in memory named score that’s ready to store a number.

Now suppose your game also lets players choose a difficulty level—A, B, or C. You’ll need a new variable for this. A good name might be difficultyLevel, difficulty_level, or simply level. These follow accepted Java naming conventions.

Fig: The effect of declaring a variable in Java

Because the difficulty level is stored as a character, the appropriate data type would be char. Here’s how you would declare this variable:

char level;

At this point, we have two variables:

int score;
char level;

You can also declare multiple variables of the same type in a single line. For example, if you want to track how many times a player gets hit by a ghost, you might call that variable hits. Since it’s also an integer, you can declare it alongside score:

int score, hits; // Two int variables declared at once
char level;      // Declared separately

Figure 2. (not shown here) would illustrate how each variable takes up space in memory. You’ll notice that:

Fig2: The effect of declaring many variables in Java
  • A char variable (like level) takes up half the space of an int
  • A double takes up twice the space of an int

So far, we’ve created boxes in memory to store values. But how do you actually put values into those boxes? That’s where assignment comes in—and that’s the next concept we’ll explore.


Assignments in Java

In Java, assignment statements are used to store values in variables. This is done using the assignment operator, represented by the equals sign =.

The basic format of an assignment statement is:

variableName = value;

For example, to assign the value 0 to a variable named score, you would write:

score = 0;

This can be read as:

  • “Set the value of score to zero”
  • Or “score becomes equal to zero”

Essentially, this instruction places the value 0 into the memory location labeled score.

Declaring and Assigning in One Step

Java allows you to combine a declaration and an assignment into a single line:

int score = 0;

This is functionally the same as:

int score;
score = 0;

Although Java sometimes assigns default values to variables, it’s considered good practice to explicitly initialize any variable that requires a starting value.


Type Compatibility in Assignments

Consider the following statement:

int score = 2.5;

This will not compile. Why?
Because score is declared as an int, which can only hold whole numbers, and 2.5 is a real number (a number with a decimal point). Assigning a real number to an integer variable would result in loss of information, which Java does not allow without explicit conversion.

On the other hand, assigning a whole number to a real-number variable is perfectly valid:

double someNumber = 1000;

Even though 1000 looks like an integer, Java will treat it as 1000.0 when stored in a double variable, which results in no loss of information.


Choosing the Right Data Type

When deciding which data type to use for a variable:

  • Use int for whole numbers
  • Use double if the variable needs to store real numbers (or both real and whole numbers)

Even though a double can technically store whole numbers, it’s best to use int for clarity and precision when decimal values aren’t needed.


Assigning Character Values

When assigning a value to a char variable, enclose the character in single quotes. For example:

char level = 'A';

Later in the program, you can reassign the value of a variable as needed:

level = 'B'; // changes the difficulty level

Remember, variables only need to be declared once. After that, you can assign and reassign values to them as often as necessary.


Here’s a polished and clear rewording of your explanation on creating constants in Java:


Creating Constants in Java

In some situations, programs use data values that never change. These fixed values are known as constants.

Examples of constant values include:

  • The maximum score in an exam (e.g., 100)
  • The number of hours in a day (24)
  • The mathematical value of π (approximately 3.1416)

Because these values stay the same throughout the program, they should be declared as constants, not variables.


Declaring Constants

In Java, a constant is declared similarly to a variable, but with one key difference: it is preceded by the keyword final.

final dataType CONSTANT_NAME = value;

Here’s an example:

final int HOURS = 24;

In this case:

  • final makes the variable a constant (its value cannot be changed later)
  • int is the data type
  • HOURS is the constant name
  • 24 is the assigned (and permanent) value

Naming Conventions

By Java convention, constant names are written in all uppercase letters, often using underscores to separate words:

final double PI = 3.1416;
final int MAX_SCORE = 100;

Attempting to Change a Constant

Once a constant is assigned a value, it cannot be modified. Doing so will cause a compiler error.

final int HOURS = 24;
HOURS = 12; // ❌ This will NOT compile!

This ensures that constants are truly constant and helps prevent accidental changes in your program.

Using constants improves clarity, reliability, and maintainability in your code. Instead of hard-coding values repeatedly, define them once as constants—this makes your code easier to understand and update.


Here’s a clean, clear, and student-friendly rewording of the explanation on arithmetic operators in Java:


Arithmetic Operators in Java

In Java, you can go beyond assigning simple values to variables—you can also perform arithmetic calculations using operators. Java supports the familiar arithmetic operations such as addition, subtraction, multiplication, and division, as well as a special operator to find the remainder.

Table: Java Arithmetic Operators

OperationJava Operator
Addition+
Subtraction-
Multiplication*
Division/
Remainder%

Using Arithmetic Operators in Assignments

You can use these operators to create expressions on the right-hand side of an assignment. These expressions are calculated first, and then the result is stored in the variable on the left.

int x;
x = 10 + 25; // x now holds the value 35

The term 10 + 25 is an expression. Java calculates this first, then assigns the result to x.


A Real-World Example

Suppose you’re calculating the total price of a product after adding a sales tax of 17.5%:

double cost;
cost = 500 * (1 + 17.5 / 100);

Here, Java:

  • First evaluates 17.5 / 100 → 0.175
  • Then adds 1 → 1.175
  • Then multiplies 500 by 1.175 → 587.5

So the final value of cost is 587.5.


Operator Precedence

Java follows the standard rules of arithmetic when evaluating expressions:

  1. Brackets first
  2. Then division and multiplication (left to right)
  3. Then addition and subtraction (left to right)

So this:

1 + 17.5 / 100

is not 0.185 but 1.175, because division comes before addition.


The Remainder Operator (%)

The % operator returns the remainder after division. This is useful for many tasks, like checking for even numbers or cycling through values.

Examples:

ExpressionResult
29 % 92
6 % 86
40 % 400
10 % 20

Division and Remainders in Practice

Here’s a practical example. Let’s say you have 30 people attending an event, and you want to seat them at tables of four. You can calculate how many full tables are needed and how many people will be left without a table using both division and remainder operators:

int tablesOfFour, peopleLeftOver;

tablesOfFour = 30 / 4;     // result: 7 (integer division)
peopleLeftOver = 30 % 4;   // result: 2 (remainder)

Why is 30 / 4 equal to 7 and not 7.5?

Because both numbers are integers, Java performs integer division, which discards the decimal part.


Real vs. Integer Division

Java uses the same symbol (/) for both integer and real division. This is known as operator overloading—the operator behaves differently depending on the data types involved.

  • If both values are integers → result is an integer
  • If at least one value is a real number (like a double) → result is a real number

Example:

int result1 = 5 / 2;      // result1 = 2
double result2 = 5.0 / 2; // result2 = 2.5

Java automatically picks the correct version based on the types of the values involved.

📌 You can also force Java to treat numbers as real using a technique called type casting—we’ll explore that later.


Great! You’re diving deep into expressions, variable usage, and shorthand operations in Java. Let’s break this down and explain it clearly, step by step, to make sure all the important points are solid.


🔁 Using Variables in Expressions

You’ve already learned that a variable can appear on the left-hand side of an assignment to store a value:

double cost;
cost = 587.5;

But variables can also appear on the right-hand side, where they’re used for their current values.

Here’s a more complete example:

double price, tax, cost;
price = 500;
tax = 17.5;
cost = price * (1 + tax / 100);

The line cost = price * (1 + tax / 100);:

  • Uses the values of price and tax
  • Calculates the expression
  • Stores the result (587.5) in the cost variable

🔁 Using a Variable to Update Its Own Value

You can reuse a variable’s current value to compute its new value:

price = price * (1 + tax / 100);

This updates price to include the tax. Now price holds the final cost, so you don’t need a separate cost variable.

  • On the right-hand side: price means the old value
  • On the left-hand side: price is being updated to a new value

⚠️ Using Uninitialized Variables

This will cause a compiler error:

double price = 500;
double tax;
double cost;
cost = price * (1 + tax / 100); // ❌ Error! tax is uninitialized

✅ Always make sure variables are assigned a value before being used in expressions.


🔼 Increment & Decrement Operators

A common task is increasing a variable’s value by 1:

x = x + 1;

Java offers a shortcut:

x++;  // same as x = x + 1

Similarly:

x--;  // same as x = x - 1

⚠️ Prefix vs Postfix

Both ++x and x++ increase the value by 1, but when they do it matters:

int x = 5;
int y = x++; // y = 5, x = 6 (x is increased AFTER the assignment)
int x = 5;
int y = ++x; // y = 6, x = 6 (x is increased BEFORE the assignment)

Same rules apply to --x and x--.


Shortcut for Adding/Subtracting Values

Java also provides shortcuts for doing math and assigning back to the same variable:

y += x;  // same as y = y + x;
y -= x;  // same as y = y - x;

You’ll see these often in real-world code, even if your course doesn’t use them much.


💻 Program Example: FindCost

Here’s a complete Java program that calculates and displays the total cost after adding tax:

/* A program to calculate the cost of a product after a sales tax has been added */
public class FindCost {
    public static void main(String[] args) {
        double price, tax;
        price = 500;
        tax = 17.5;
        price = price * (1 + tax / 100);

        // Output the result
        System.out.println("The final cost of the product is: " + price);
    }
}

🧾 Output

When you run this version of the program, you’ll see:

The final cost of the product is: 587.5

You’re really building a solid foundation in Java programming — nice work so far! Now we’re moving from hardcoded values to getting user input at runtime, which makes your programs dynamic and interactive.


🧾Output in Java

You already know that you can use System.out.println() or System.out.print() to display:

  • Literal strings: System.out.println("Hello, world!");
  • Calculated values: System.out.println(10 * 10); // prints: 100
  • Concatenated text + value: System.out.println("The square of 10 is " + (10 * 10)); // prints: The square of 10 is 100

Always use + to join strings with values.


📥 Introducing Input: Making the Program Interactive

To get input from the user while the program runs, Java provides a class called Scanner.

🧾 Step-by-step: Using Scanner for Input

  1. Import Scanner import java.util.Scanner;
  2. Create a Scanner object Scanner input = new Scanner(System.in);
  3. Prompt the user and read values
    • For a double: System.out.print("Enter price: "); double price = input.nextDouble();
    • For an int: int count = input.nextInt();
  4. Use the input in calculations or output

✅ Full Program Example: User-Driven Product Cost Calculator

import java.util.Scanner;

public class FindCostInteractive {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in); // Step 1: Create scanner

        // Step 2: Get user input
        System.out.print("Enter the product price: ");
        double price = input.nextDouble();

        System.out.print("Enter the sales tax percentage: ");
        double tax = input.nextDouble();

        // Step 3: Calculate total cost
        price = price * (1 + tax / 100);

        // Step 4: Display result
        System.out.println("\n*** Product Price Check ***");
        System.out.println("Cost after tax = " + price);
    }
}

🧪 Sample Run

Enter the product price: 1000
Enter the sales tax percentage: 10

*** Product Price Check ***
Cost after tax = 1100.0

📝 Summary

ConceptExample
Print valueSystem.out.println(price);
Combine strings"Price: " + price
Get user inputScanner input = new Scanner(...);
Read numberinput.nextDouble();

🔑 Key Takeaways from This Section

✅ Importing the Scanner Class

To read user input, we import the Scanner class from the java.util package:

import java.util.*;

This makes all classes in java.util accessible, including Scanner.

✅ Creating a Scanner Object

Scanner keyboard = new Scanner(System.in);

This tells Java to take input from the keyboard (i.e., standard input).

✅ Getting Different Types of Input

TypeMethod Example
intint x = keyboard.nextInt();
doubledouble y = keyboard.nextDouble();
charchar c = keyboard.next().charAt(0);
StringString name = keyboard.next(); (More in Chapter 7)

🛠️ Input/Output Program Example: FindCost3

Here’s the cleaned-up version of Program 2.3, using proper syntax for quotes (which sometimes get messed up when copying from documents):

import java.util.*; // access the Scanner class

/* A program to input the initial price of a product and then 
   calculate and display its cost after tax has been added */
public class FindCost3 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in); // Scanner object

        double price, tax;

        System.out.println("*** Product Price Check ***");

        System.out.print("Enter initial price: "); // prompt user
        price = keyboard.nextDouble();             // input price

        System.out.print("Enter tax rate: ");      // prompt user
        tax = keyboard.nextDouble();               // input tax

        price = price * (1 + tax / 100);           // calculate new price

        System.out.println("Cost after tax = " + price); // display result
    }
}

💡 Sample Run

*** Product Price Check ***
Enter initial price: 750
Enter tax rate: 15
Cost after tax = 862.5

📌 Notes

  • Don’t enter symbols like $ or % when prompted — just numbers.
  • Input always moves to the next line after pressing Enter.
  • You must perform calculations before displaying results.
  • Good habit: Sketch your logic out on paper or in pseudocode before typing.

🧠 Tip: Pseudocode for This Program

Before writing Java code, you might think about it like this:

  1. Display header.
  2. Ask user for price.
  3. Ask user for tax.
  4. Calculate total cost.
  5. Display total cost.

Which maps directly to the Java code blocks you wrote — this kind of thinking really helps avoid silly mistakes.


Program Design and Pseudocode

As you’ve just highlighted, program design is essential before diving into writing code. It helps break down a problem into manageable steps, making it easier to implement the solution. Let’s explore the concept of pseudocode more deeply and how it helps in program design.

📌 What is Pseudocode?

Pseudocode is a way to express the logic of a program using plain, human-readable instructions. It is like a blueprint for the code that does not worry about specific syntax of a programming language (like Java). Instead, it focuses on the steps the program should follow.

Pseudocode is useful in planning out programs before implementing them. It can be translated into actual code once the logic is clear.


🧩 Benefits of Using Pseudocode

  1. Clarity: Helps you focus on the logic and flow of the program without getting bogged down by syntax.
  2. Simplicity: You can easily change or adjust the logic without worrying about code structure.
  3. Communication: It’s a good way to explain your solution to others before jumping into coding.

🛠️ Pseudocode Example:

Let’s take a look at your FindCost3 program and break it down using pseudocode. This will help us understand how we could represent the program’s flow logically, without focusing on Java syntax.

Pseudocode for FindCost3:

BEGIN
    DISPLAY "*** Product Price Check ***"
    DISPLAY "Enter initial price:"
    GET user input for price
    DISPLAY "Enter tax rate:"
    GET user input for tax rate
    CALCULATE new price = price * (1 + tax / 100)
    DISPLAY "Cost after tax = " followed by the new price
END

💡 Pseudocode Steps Explained:

  • DISPLAY: This instruction shows a message to the user (e.g., prompting for input).
  • GET: This represents obtaining user input. In the Java code, this would be where we use keyboard.nextDouble().
  • CALCULATE: We perform the calculation of the new price based on the price and tax rate.
  • DISPLAY (again): This prints out the result of the calculation.

📚 Translation to Java Code:

Once the pseudocode is clear, it’s easy to translate it into Java syntax. For example:

import java.util.*; // access the Scanner class

public class FindCost3 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in); // Scanner object

        double price, tax;

        // DISPLAY program title
        System.out.println("*** Product Price Check ***");

        // DISPLAY and GET user input for price
        System.out.print("Enter initial price: ");
        price = keyboard.nextDouble();

        // DISPLAY and GET user input for tax
        System.out.print("Enter tax rate: ");
        tax = keyboard.nextDouble();

        // CALCULATE new price after tax
        price = price * (1 + tax / 100);

        // DISPLAY result
        System.out.println("Cost after tax = " + price);
    }
}

Notice how the pseudocode translates directly into Java code. Having the pseudocode first makes the actual coding process smoother because you already know the program flow.


🧠 Using Pseudocode for Complex Methods:

As the programs grow more complex, pseudocode becomes especially helpful. For example, if you were to write a program that involves loops, conditional statements, and multiple methods, using pseudocode will help you visualize how each part of the program interacts with the other.


📝 Your Next Step: Write Your Own Pseudocode!

Let’s try using pseudocode in action. Imagine you need to write a program that:

  • Takes the cost of an item.
  • Takes the number of items the user wants to buy.
  • Calculates the total cost.
  • Displays the result.

Try writing the pseudocode for this program! Once you’ve got that, we can work on translating it into Java code together.

Self-test questions

Great! Let’s go through each of the questions one by one.


1. Most Appropriate Java Data Types

  • Maximum number of people on a bus: int
    (Whole numbers only, no decimals, e.g. 50)
  • Weight of a food item in a supermarket: double
    (Can be fractional, e.g. 1.25 kg)
  • Grade awarded to a student (e.g. ‘A’, ‘B’, ‘C’): char
    (Single character)

2. Compiler Errors

int x = 75.5; // ❌ Error – trying to assign a double value to an int.
double y = 75; // ✅ OK – implicit conversion from int to double.

3. Correcting the Age Program

Original Code (with issues):

final int YEAR;

Error: Constant not initialized

age = keyboard.nextDouble();

Error: Reading a double into an int variable

System.out.print(How old are you this year? );

Error: Missing quotes around string

System.out.println("I think you were born in " + BornIn);

Error: BornIn should be bornIn

✅ Corrected Code:

import java.util.*;

public class SomeProg {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        final int YEAR = 2025;
        int age, bornIn;

        System.out.print("How old are you this year? ");
        age = keyboard.nextInt(); // changed to nextInt
        bornIn = YEAR - age;

        System.out.println("I think you were born in " + bornIn);
    }
}

4. Output if User Enters 10

num1 = keyboard.nextInt(); // 10
num1 = num1 + 2; // 12
num2 = num1 / num2; // 12 / 6 = 2
System.out.println("result = " + num2); // result = 2

Final Output:

result = 2

5. Rectangle Program Pseudocode

BEGIN
  DISPLAY "Enter the length of the rectangle:"
  ENTER length
  DISPLAY "Enter the height of the rectangle:"
  ENTER height
  SET area TO length * height
  SET perimeter TO 2 * (length + height)
  DISPLAY area
  DISPLAY perimeter
END

6. Swapping Values – Errors & Fix

a) Why it fails:

x = y;
y = x;

After x = y, both x and y have the same value. So the original value of x is lost before being assigned to y.

b) Actual Output (e.g. if user enters 5 for x and 10 for y):

x = 10
y = 10

c) ✅ Fixed Version using a temporary variable:

import java.util.*;

public class SwapFixed {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int x, y, temp;

        System.out.print("Enter value for x: ");
        x = keyboard.nextInt();
        System.out.print("Enter value for y: ");
        y = keyboard.nextInt();

        temp = x;
        x = y;
        y = temp;

        System.out.println("x = " + x);
        System.out.println("y = " + y);
    }
}

✅ Programming Exercises Implementation Suggestions

1. Implement Q3, Q4, Q6 — Already Done Above


2. Rectangle Program in Java

import java.util.*;

public class Rectangle {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        double length, height, area, perimeter;

        System.out.print("Enter length: ");
        length = keyboard.nextDouble();
        System.out.print("Enter height: ");
        height = keyboard.nextDouble();

        area = length * height;
        perimeter = 2 * (length + height);

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

3. Pounds to Kilograms Converter

import java.util.*;

public class WeightConverter {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        double pounds, kilos;

        System.out.print("Enter weight in pounds: ");
        pounds = keyboard.nextDouble();
        kilos = pounds / 2.2;

        System.out.println("Equivalent weight in kilos = " + kilos);
    }
}

4. Student Teams Program

import java.util.*;

public class TeamMaker {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int students, teamSize, teams, remainder;

        System.out.print("Enter number of students: ");
        students = keyboard.nextInt();
        System.out.print("Enter team size: ");
        teamSize = keyboard.nextInt();

        teams = students / teamSize;
        remainder = students % teamSize;

        System.out.println("Number of full teams = " + teams);
        System.out.println("Students left without a team = " + remainder);
    }
}

5. Circle Area and Circumference

import java.util.*;

public class CircleMath {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        final double PI = 3.1416;
        double radius, area, circumference;

        System.out.print("Enter radius of circle: ");
        radius = keyboard.nextDouble();

        area = PI * radius * radius;
        circumference = 2 * PI * radius;

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

***END OF THE TOPIC***

If you want to learn Java in Hindi, you can watch the Java course on the YouTube channel CodeWithHarry:
🔗 CodeWithHarry – Java in Hindi

If you prefer to learn Java in English, check out the Java course by Telusko on YouTube:
🔗 Telusko – Java in English

Leave a Comment

Your email address will not be published. Required fields are marked *