Corporate Training Study Material: Naming Conventions & Control Flow Statements in Java

Rashmi Mishra
0

 

Corporate Training Study Material

Naming Conventions & Control Flow Statements in Java

🔹 Session Objectives

By the end of this session, participants will:
Understand best practices for naming identifiers in Java.
Learn about if-else statements and how to use them for decision-making.
Implement switch-case statements for multi-way branching.
Explore looping constructs (for, while, do-while) to handle repetitive tasks.


📌 1. Java Naming Conventions

Naming conventions in Java help make the code readable, maintainable, and consistent. The Java community follows these widely accepted standards.

🔹 Best Practices for Naming Identifiers

1️ Class Names

  • Use PascalCase (CamelCase with first letter capitalized).
  • Should be a noun (representing an object or concept).
  • Example:

class EmployeeDetails { }

class BankAccount { }

2️ Variable Names

  • Use camelCase (first letter lowercase, following words capitalized).
  • Should be meaningful and descriptive.
  • Example:

int employeeId;

double accountBalance;

3️ Method Names

  • Use camelCase, starting with a verb (action).
  • Example:

void calculateSalary() { }

int getAge() { return age; }

4️ Constant Variables

  • Use UPPER_CASE with underscores.
  • Example:

final int MAX_AGE = 60;

final double INTEREST_RATE = 4.5;

5️ Package Names

  • Use lowercase words, separated by dots (.).
  • Example:

package com.companyname.projectname;


📌 2. Control Flow Statements

Control flow statements help define the logic flow of the program. They determine which parts of code execute and how many times.

🔹 1️ Decision-Making Statements

Used to execute specific blocks of code based on conditions.

1️ If-Else Statement

Syntax:

if (condition) {

    // Code executes if condition is true

} else {

    // Code executes if condition is false

}

Example:

public class IfElseExample {

    public static void main(String[] args) {

        int age = 18;

        if (age >= 18) {

            System.out.println("You are eligible to vote.");

        } else {

            System.out.println("You are not eligible to vote.");

        }

    }

}

Output:

You are eligible to vote.

2️ If-Else If Ladder

Used when there are multiple conditions to check.

Example:

public class IfElseIfExample {

    public static void main(String[] args) {

        int marks = 85;

        if (marks >= 90) {

            System.out.println("Grade: A");

        } else if (marks >= 75) {

            System.out.println("Grade: B");

        } else {

            System.out.println("Grade: C");

        }

    }

}

Output:

Grade: B


🔹 2️ Switch-Case Statement

Used when multiple conditions need to be checked on the same variable.

Syntax:

switch (expression) {

    case value1:

        // Code block

        break;

    case value2:

        // Code block

        break;

    default:

        // Default block (if no cases match)

}

Example:

public class SwitchExample {

    public static void main(String[] args) {

        int day = 3;

        switch (day) {

            case 1:

                System.out.println("Monday");

                break;

            case 2:

                System.out.println("Tuesday");

                break;

            case 3:

                System.out.println("Wednesday");

                break;

            default:

                System.out.println("Invalid Day");

        }

    }

}

Output:

Wednesday


🔹 3️ Looping Constructs

Loops allow us to execute a block of code multiple times.

1️ For Loop

Used when the number of iterations is known.
Syntax:

for(initialization; condition; increment/decrement) {

    // Code to execute

}

Example:

public class ForLoopExample {

    public static void main(String[] args) {

        for (int i = 1; i <= 5; i++) {

            System.out.println("Iteration: " + i);

        }

    }

}

Output:

Iteration: 1 

Iteration: 2 

Iteration: 3 

Iteration: 4 

Iteration: 5 


2️ While Loop

Used when the number of iterations is unknown.
Syntax:

while(condition) {

    // Code to execute

}

Example:

public class WhileLoopExample {

    public static void main(String[] args) {

        int count = 1;

        while (count <= 5) {

            System.out.println("Count: " + count);

            count++;

        }

    }

}

Output:

Count: 1 

Count: 2 

Count: 3 

Count: 4 

Count: 5 


3️ Do-While Loop

Ensures the loop executes at least once.
Syntax:

do {

    // Code to execute

} while (condition);

Example:

public class DoWhileExample {

    public static void main(String[] args) {

        int num = 1;

        do {

            System.out.println("Number: " + num);

            num++;

        } while (num <= 5);

    }

}

Output:

Number: 1 

Number: 2 

Number: 3 

Number: 4 

Number: 5 


📌 Summary

Concept

Key Points

Naming Conventions

Follow best practices for readability and maintainability.

If-Else Statement

Used for conditional execution.

Switch-Case Statement

Used for multi-way branching.

For Loop

Executes for a known number of times.

While Loop

Executes as long as the condition is true.

Do-While Loop

Executes at least once before checking the condition.


Practice Assignments

1️ Write a program to check if a number is positive, negative, or zero using if-else.
2️
Implement a switch-case program that takes a month number and prints the month name.
3️
Write a for loop to print the first 10 natural numbers.
4️
Use a while loop to find the sum of digits of a given number.
5️
Create a do-while loop to print numbers from 10 to 1.


1.   Naming Conventions

2.   Decision-Making Statements (If-Else, Switch-Case)

3.   Looping Constructs (For, While, Do-While)

🔹 Section 1: Naming Conventions (5 Assignments)

Assignment 1: Follow Proper Naming Conventions

🔹 Task: Create a Java class named EmployeeDetails with variables employeeId, employeeName, and employeeSalary.

🔹 Code:

class EmployeeDetails {

    int employeeId;

    String employeeName;

    double employeeSalary;

    void displayEmployeeInfo() {

        System.out.println("Employee ID: " + employeeId);

        System.out.println("Employee Name: " + employeeName);

        System.out.println("Employee Salary: " + employeeSalary);

    }

}

public class NamingConventionExample {

    public static void main(String[] args) {

        EmployeeDetails emp = new EmployeeDetails();

        emp.employeeId = 101;

        emp.employeeName = "John Doe";

        emp.employeeSalary = 50000;

        emp.displayEmployeeInfo();

    }

}

🔹 Output:

Employee ID: 101 

Employee Name: John Doe 

Employee Salary: 50000.0 


Assignment 2: PascalCase for Class Name

🔹 Task: Create a class BankAccount with methods depositAmount and withdrawAmount.

🔹 Code:

class BankAccount {

    double balance = 0;

    void depositAmount(double amount) {

        balance += amount;

    }

    void withdrawAmount(double amount) {

        if (amount <= balance) {

            balance -= amount;

        } else {

            System.out.println("Insufficient Balance");

        }

    }

}

public class BankTransaction {

    public static void main(String[] args) {

        BankAccount account = new BankAccount();

        account.depositAmount(1000);

        account.withdrawAmount(500);

        System.out.println("Remaining Balance: " + account.balance);

    }

}

🔹 Output:

Remaining Balance: 500.0 


Assignment 3: Use of Constants in Java

🔹 Task: Define a constant PI and use it to calculate the area of a circle.

🔹 Code:

class Circle {

    final double PI = 3.14159;

    double calculateArea(double radius) {

        return PI * radius * radius;

    }

}

public class ConstantExample {

    public static void main(String[] args) {

        Circle circle = new Circle();

        System.out.println("Area: " + circle.calculateArea(5));

    }

}

🔹 Output:

Area: 78.53975 


Assignment 4: CamelCase for Method Names

🔹 Task: Create a class StudentMarks with a method calculatePercentage().

🔹 Code:

class StudentMarks {

    double calculatePercentage(int marks, int totalMarks) {

        return (marks * 100.0) / totalMarks;

    }

}

public class StudentTest {

    public static void main(String[] args) {

        StudentMarks student = new StudentMarks();

        System.out.println("Percentage: " + student.calculatePercentage(450, 500) + "%");

    }

}

🔹 Output:

Percentage: 90.0% 


Assignment 5: Package Naming Conventions

🔹 Task: Create a package named com.company.hr and add a class Employee.

🔹 Code:

package com.company.hr;

class Employee {

    String name;

    Employee(String name) {

        this.name = name;

    }

    void display() {

        System.out.println("Employee: " + name);

    }

}


🔹 Section 2: Decision-Making Statements (5 Assignments)

Assignment 6: Check Positive, Negative, or Zero

🔹 Task: Use if-else to check if a number is positive, negative, or zero.

🔹 Code:

public class NumberCheck {

    public static void main(String[] args) {

        int num = -5;

        if (num > 0)

            System.out.println("Positive Number");

        else if (num < 0)

            System.out.println("Negative Number");

        else

            System.out.println("Zero");

    }

}

🔹 Output:

Negative Number 


Assignment 7: Check Leap Year

🔹 Task: Use if-else to check if a year is a leap year.

🔹 Code:

public class LeapYearCheck {

    public static void main(String[] args) {

        int year = 2024;

        if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {

            System.out.println(year + " is a Leap Year");

        } else {

            System.out.println(year + " is not a Leap Year");

        }

    }

}

🔹 Output:

2024 is a Leap Year 


Assignment 8: Find Maximum of Three Numbers

🔹 Task: Use if-else to find the largest of three numbers.

🔹 Code:

public class MaxNumber {

    public static void main(String[] args) {

        int a = 10, b = 20, c = 15;

        if (a > b && a > c)

            System.out.println(a + " is the largest");

        else if (b > c)

            System.out.println(b + " is the largest");

        else

            System.out.println(c + " is the largest");

    }

}

🔹 Output:

20 is the largest 


Assignment 9: Switch Case for Days of the Week

🔹 Task: Use switch-case to print the day of the week.

🔹 Code:

public class WeekDay {

    public static void main(String[] args) {

        int day = 3;

        switch (day) {

            case 1: System.out.println("Monday"); break;

            case 2: System.out.println("Tuesday"); break;

            case 3: System.out.println("Wednesday"); break;

            default: System.out.println("Invalid day");

        }

    }

}

🔹 Output:

Wednesday 


Assignment 10: Switch Case for Vowel Check

🔹 Task: Check if a character is a vowel using switch-case.

🔹 Code:

public class VowelCheck {

    public static void main(String[] args) {

        char ch = 'e';

        switch (ch) {

            case 'a': case 'e': case 'i': case 'o': case 'u':

                System.out.println("Vowel");

                break;

            default:

                System.out.println("Consonant");

        }

    }

}

🔹 Output:

Vowel 


🔹 Section 3: Looping Statements (5 Assignments)

🔹 Assignment 11: Print Numbers from 1 to 10 using for Loop

🔹 Task: Write a Java program that prints numbers from 1 to 10 using a for loop.

🔹 Code:

public class ForLoopExample {

    public static void main(String[] args) {

        for (int i = 1; i <= 10; i++) {

            System.out.print(i + " ");

        }

    }

}

🔹 Output:

1 2 3 4 5 6 7 8 9 10


🔹 Assignment 12: Find Sum of Digits of a Number using while Loop

🔹 Task: Write a Java program to find the sum of digits of a given number using a while loop.

🔹 Code:

import java.util.Scanner;

public class SumOfDigits {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int number = scanner.nextInt();

        int sum = 0;

        while (number > 0) {

            sum += number % 10;

            number /= 10;

        }

        System.out.println("Sum of digits: " + sum);

        scanner.close();

    }

}

🔹 Input:

Enter a number: 1234

🔹 Output:

Sum of digits: 10

(Explanation: 1 + 2 + 3 + 4 = 10)


🔹 Assignment 13: Reverse a Number using while Loop

🔹 Task: Write a Java program to reverse a given number using a while loop.

🔹 Code:

import java.util.Scanner;

public class ReverseNumber {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int number = scanner.nextInt();

        int reverse = 0;

        while (number > 0) {

            int digit = number % 10;

            reverse = reverse * 10 + digit;

            number /= 10;

        }

        System.out.println("Reversed number: " + reverse);

        scanner.close();

    }

}

🔹 Input:

Enter a number: 1234

🔹 Output:

Reversed number: 4321


🔹 Assignment 14: Print Fibonacci Series using for Loop

🔹 Task: Write a Java program to print the Fibonacci series up to n terms using a for loop.

🔹 Code:

import java.util.Scanner;

public class FibonacciSeries {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of terms: ");

        int n = scanner.nextInt();

        int first = 0, second = 1;

        System.out.print("Fibonacci Series: " + first + " " + second + " ");

        for (int i = 3; i <= n; i++) {

            int next = first + second;

            System.out.print(next + " ");

            first = second;

            second = next;

        }

        scanner.close();

    }

}

🔹 Input:

Enter the number of terms: 7

🔹 Output:

Fibonacci Series: 0 1 1 2 3 5 8


🔹 Assignment 15: Print Numbers from 10 to 1 using do-while Loop

🔹 Task: Write a Java program to print numbers from 10 to 1 using a do-while loop.

🔹 Code:

public class DoWhileExample {

    public static void main(String[] args) {

        int i = 10;

        do {

            System.out.print(i + " ");

            i--;

        } while (i >= 1);

    }

}

🔹 Output:

10 9 8 7 6 5 4 3 2 1



Tags

Post a Comment

0Comments

Post a Comment (0)