Day 3 Programming (JAVA) (User-input ) (Operators) (Conditional Statements if-else ) (Loops for and while )

·

14 min read


User input

Almost every application or website we encounter requires some form of user input, whether it's for a signup/login page or capturing user details. In Java, this can be achieved using the following way:

  1. Using the Scanner class

Scanner Class ( Easy-Beginner friendly)

The Scanner class in Java is part of the java.util package. It is used to read input from various sources, such as:

  1. Keyboard (Standard Input)

  2. Files

  3. Strings

It allows programmers to easily and efficiently fetch user input during program execution.


Steps to Use Scanner:

  1. Import the java.util.Scanner package.

  2. Create a Scanner object.

  3. Use its methods to read input.

Key Methods in Scanner:

MethodPurposeExample Input
nextLine()Reads a full line of textJohn Doe
next()Reads a single wordJohn
nextInt()Reads an integer25
nextDouble()Reads a double/float number25000.50
nextBoolean()Reads a boolean valuetrue or false

Here's an example of a code where I prompt the user to enter their details, such as name, age, salary, and marital status.




import java.util.Scanner;  // Step 1: Import Scanner

public class Main {
    public static void main(String[] args) {

        InputExample.inputexample();
    }
}

 class InputExample {
    public static void inputexample () {
        Scanner scanner = new Scanner(System.in);  // Step 2: Create Scanner object

        // Taking different types of inputs
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();  // Reading a string

        System.out.print("Enter your surname: ");
        String surname = scanner.nextLine();  // Reading a string


        System.out.print("Enter your age: ");
        int age = scanner.nextInt();  // Reading an integer

        System.out.print("Enter your salary: ");
        double salary = scanner.nextDouble();  // Reading a double

          System.out.print("Are you Married: ");
        boolean marriage = scanner.nextBoolean();  // Reading Boolean   


        // Displaying the inputs
        System.out.println("Name: " + name);
        System.out.println("surname: " + surname);
        System.out.println("Age: " + age);
        System.out.println("Salary: " + salary);
        System.out.println("Married: " + marriage);

        scanner.close();  // Step 3: Close the scanner
    }
}

In the code above, we import the Scanner class from the java.util package to read user input. A Scanner object is created to capture input from the keyboard (System.in). The program collects various inputs such as the user's name (String), surname (String), age (int), salary (double), and marital status (boolean).

Each input is displayed back to the user. Finally, the scanner.close() method is used to release the underlying system resources associated with the Scanner object. Closing the scanner is a good practice to prevent resource leaks, especially in larger applications.


Operators

Operators are symbols like + , - , &&, or = that tell Java what to do with the data. The data you work with are called operands. e.g. int a = 27 ;

Let's explore the different categories of operators in Java and how they can be used.

Arithmetic Operators

These are used for basic math calculations.

OperatorWhat it doesExample (a = 10, b = 5)Result
+Adds two numbersa + b15
-Subtracts one from anothera - b5
*Multiplies two numbersa * b50
/Divides one by anothera / b2
%Finds the remaindera % b0

Example:

codeint a = 10, b = 3;
System.out.println(a / b); // Output: 3
System.out.println(a % b); // Output: 1

Relational (Comparison) Operators

These help you compare two values and return true or false.

OperatorWhat it doesExample (a = 10, b = 5)Result
==Checks if equala == bfalse
!=Checks if not equala != btrue
>Checks if greater thana > btrue
<Checks if less thana < bfalse
>=Greater than or equal toa >= btrue
<=Less than or equal toa <= bfalse

Example:

code int a = 10, b = 5;
System.out.println(a > b); // Output: true
System.out.println(a == b); // Output: false

Logical Operators

These are used to combine multiple conditions.

OperatorWhat it doesExampleResult
&&Logical AND(a > 5 && b < 10)true
``Logical OR
!Logical NOT (reverse)!(a > 5)false

Example:

code int a = 10, b = 5;
System.out.println(a > 5 && b < 10); // Output: true
System.out.println(a > 5 || b > 10); // Output: true
System.out.println(!(a > 5)); // Output: false

  1. Assignment Operators

    Used to assign values to variables.

    | Operator | What it does | Example | | --- | --- | --- | | = | Assigns value | a = 5 | | += | Adds and assigns | a += 5 (a = a + 5) | | -= | Subtracts and assigns | a -= 5 (a = a - 5) | | *= | Multiplies and assigns | a *= 5 (a = a * 5) | | /= | Divides and assigns | a /= 5 (a = a / 5) | | %= | Modulus and assigns | a %= 5 (a = a % 5) |

    Example:

     code int a = 10;
     a += 5; // a = a + 5 → 15
     System.out.println(a); // Output: 15
    

Increment and Decrement Operators

Quickly increase or decrease a value by 1.

OperatorWhat it doesExample (a = 5)Result
++Increases by 1 (increment)++a or a++6
--Decreases by 1 (decrement)--a or a--4

Example:

int a = 5;
System.out.println(++a); // Output: 6 (pre-increment)
System.out.println(a++); // Output: 6 (post-increment, then a becomes 7)

Conditional statement if-else

A conditional statement is a feature in programming that allows the computer to make decisions based on certain conditions. It checks whether something is true or false and then decides what to do next.

In programming, conditional statements work the same way. They let you tell the computer, "If this happens, do this. Otherwise, do something else."

For example:

If you are 18 , you can opt for an Driving License.
Else (if not), You are still a minor .

Using the Scanner input from the above section, here's a simple program that determines whether a user is eligible for a driving license or not.





import java.util.Scanner;  // Step 1: Import Scanner

class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Age: ");
        int  age = scanner.nextInt();


        if (age >=18) { //Checking first condition if use is elegible

            System.out.println("You are eligible and can opt for a license");
        }
        else{ //Second condition  where user is not elegible 
            System.out.println("You are still a minor");
        }    


    }
}

In the given code, we prompt the user to confirm their age and determine whether they are eligible for a driving license. To achieve this, We import the Scanner class from the java.util package . A Scanner object is then created within the main class. Using a conditional statement, we logically check if the provided age meets the eligibility criteria for a driving license and print the corresponding message based on the result.

Next, I’ve created a simple calculator program that prompts the user to choose an operation (e.g., +, -, *,/), takes two numerical inputs, and performs the selected operation.



import java.util.Scanner;  // Step 1: Import Scanner

class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your Operation: ");
        String  operation = scanner.nextLine();  // Reading user input for operation ("+","-","/","*")

        System.out.print("Enter your num1: "); // Reading user input first number
        int num1  = scanner.nextInt();

        System.out.print("Enter your num2: ");  // Reading user input for second number
        int num2  = scanner.nextInt();  

        if (operation.equals("+")){

            int addition = num1 +  num2 ;   // performs addition and stores the value in addition variable
            System.out.println(addition);

        }else if (operation.equals("-")) {

            int subtraction =  num1 -  num2;  // performs subtratction and stores the value in subtraction variable
             System.out.println(subtraction);

        }else if (operation.equals("*")) {

            int multiply =  num1 *  num2; // performs multiplication and stores the value in multiplication variable
             System.out.println(multiply);


        }else if (operation.equals("/")) {

            int div =  num1 /  num2;    // performs divison and stores the value in divison variable
             System.out.println(div);

        }else{
            System.out.println("Wrong input"); // 
        }    


    }
}

The key highlight in the code is the use of operation.equals("+") method to check the user's input for the operation, which is a string. This is necessary because the == operator is used for comparing integers, not strings. Additionally, a third variable is used as a storage holder to perform the operation between two user-provided integer inputs.

Next, let's create a program that prompts the user to select a number between 1 and 7, and based on the input, it will display the corresponding day of the week.


import java.util.Scanner;

public class WeekDayIfElse {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Prompt user to input a number for a weekday
        System.out.println("Enter a number (1-7) to display the corresponding weekday: ");
        int day = scanner.nextInt();

        // If-else conditions to print the corresponding weekday
        if (day == 1) {
            System.out.println("Monday");
        } else if (day == 2) {
            System.out.println("Tuesday");
        } else if (day == 3) {
            System.out.println("Wednesday");
        } else if (day == 4) {
            System.out.println("Thursday");
        } else if (day == 5) {
            System.out.println("Friday");
        } else if (day == 6) {
            System.out.println("Saturday");
        } else if (day == 7) {
            System.out.println("Sunday");
        } else {
            System.out.println("Invalid input! Please enter a number between 1 and 7.");
        }

        scanner.close();
    }
}

The main issue with the code is that it appears lengthy and contains an excessive number of if-else conditions, which can make it harder to read and maintain. Let’s explore how we can optimize and improve the code.


import java.util.Scanner;

public class WeekDaySwitchCase {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Prompt user to input a number for a weekday
        System.out.println("Enter a number (1-7) to display the corresponding weekday: ");
        int day = scanner.nextInt();

        // Switch-case to print the corresponding weekday
        switch (day) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            case 6:
                System.out.println("Saturday");
                break;
            case 7:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("Invalid input! Please enter a number between 1 and 7.");
                break;
        }

        scanner.close();
    }
}

The above code appears cleaner compared to the if-else conditions used in the previous version. Here's a brief comparison between the two approaches.

AspectSwitch CaseConditional Statement (if-else)

Structure

A switch evaluates a single expression/variable and matches it against several possible cases.

if-else checks conditions, which can be more complex and involve multiple expressions.

Use Case

Best for scenarios where you are comparing one variable to multiple fixed values.

Used for a wider range of conditions, including relational, logical, and combined expressions.

Readability

Cleaner and easier to read when dealing with many discrete cases.

Can become difficult to read when there are many if-else branches.

Evaluation

Only one case gets executed based on a matching value. Execution jumps directly to the matched case.

Conditions are evaluated sequentially until one condition evaluates to true.

Range of Values

Works with discrete values (like int, char, enum, etc.) in most programming languages.

Works with any condition (e.g., comparisons, ranges, logical operations).

Data Types Supported

Limited to certain data types (e.g., int, char, string in modern languages like Java).

Supports all data types and complex logical expressions.

Default Case

default case handles any unmatched values.

Equivalent to the else block in conditional statements.

Fall-through Behavior

By default, cases "fall through" to the next unless a break is used.

Each if block is independent; no fall-through occurs.

Performance

More efficient when comparing one value against many fixed options, as it may use jump tables.

Can be slower when there are many conditions to evaluate sequentially.

When to Use What?

  • Switch Case: Use it when you have a single variable being compared against multiple constant values, as it is cleaner and often more efficient.

  • If-Else Statement: Use it when the conditions involve comparisons, logical operations, or ranges, as switch cases don’t handle complex conditions.


Loops (for-loop) (while loop) (do-while )

for loop:

  • Purpose: Used when you know how many times you want to iterate over a condition.

  • Structure: Typically used when the number of iterations is known in advance (e.g., looping over a fixed range).

Syntax

for (initialization; condition; update) {
    // Loop body
}
  • Initialization: Initializes the loop variable (executed once).

  • Condition: The condition to continue the loop (checked before each iteration).

Update: The increment or update to the loop variable (executed after each iteration).

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

Key Point: The for loop is ideal when you know the exact number of iterations beforehand (like when you know the range of numbers or a set number of steps).

Here's a link to GeeksforGeeks that provides a detailed explanation of how a loop is executed step by step.

https://www.geeksforgeeks.org/java-for-loop-with-examples/?ref=lbp

Here's a simple code example that prints a multiplication table based on user input.



import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

         System.out.println("Enter a number: ");
         int n = scanner.nextInt();

        for (int i = 1 ; (i <= n) ; i ++) {  //condition will always be boolean

             System.out.println( n + "*" + i +"="+(n * i)); // since i is intialised to 1 it will be multiplied by user input 
        }
    }
}

The condition (int i = 1 ; (i <= n) ; i ++) in the for loop is indeed a boolean expression. This ensures that the loop runs a fixed number of times (based on the input n), and does not involve any arithmetic operation. The loop keeps running as long as the value of i is less than or equal to n.

  • The arithmetic operation happens inside the System.out.println() statement, where the program calculates n * i and prints the result in a formatted manner.

while loop:

  • Purpose: Used when you want to repeat an action as long as a condition is true, but you don't necessarily know how many iterations you'll need.

  • Structure: The loop checks the condition before executing the body, so if the condition is false at the beginning, the loop may not execute at all.

    Syntax

      while (condition) {
          // Loop body
      }
    

Example (Printing numbers from 1 to 5 using a while loop):

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++; // increment i
}

Key Point: The while loop is best used when the number of iterations is not known beforehand, and the loop should continue running as long as the condition remains true. If the condition is false initially, the loop may never execute.


do-while loop:

  • Purpose: Similar to the while loop, but with one key difference: the do-while loop guarantees that the body of the loop will execute at least once before checking the condition.

  • Structure: The condition is checked after the loop body is executed, meaning the loop will always run at least once even if the condition is initially false.

Syntax

do {
    // Loop body
} while (condition);
int i = 1;
do {
    System.out.println(i);
    i++; // increment i
} while (i <= 5);

Key Point: The do-while loop is useful when you need to execute the loop body at least once, regardless of the condition. After the first execution, it will check the condition to determine whether to repeat the loop.


Loop TypeCondition CheckExecution GuaranteeUse Case
for loopCondition checked before loopExecutes a known number of timesWhen you know the number of iterations (e.g., looping through a fixed range).
while loopCondition checked before loopMay not execute if condition is false initiallyWhen you want to repeat an action as long as a condition is true, and you don't know the number of iterations in advance.
do-while loopCondition checked after loopExecutes at least onceWhen you need to guarantee the loop runs at least once before checking the condition (e.g., prompting the user until they enter valid input).

Thank you

Happy Learing :)