Control Flow and Methods

Control Flow and Methods

Decision-Making Statements

  • Two main types: If Statement and Switch Statement.
Simple If Statement
  • Definition: Executes a block of code only when a specific condition is true.
  • Syntax:
  if (condition) {
      // Code to execute if the condition is true
  }
  • Example:
  import java.util.Scanner;
  class SamuelPatel {
      public static void main(String[] args) {
          int age;
          System.out.print("Enter Your Age: ");
          Scanner r = new Scanner(System.in);
          age = r.nextInt();
          if (age >= 18) {
              System.out.print("Eligible for voting..!);
          }
          System.out.print("Thank You..!");
      }
  }
  • Output:
  Enter your age: 20
  Eligible for voting..!
  Thank You..!
If-Else Statement
  • Definition: Executes different blocks of code based on a condition's truth value.
  • Syntax:
  if (condition) {
      // Statements to execute if condition is true
  } else {
      // Statements to execute if condition is false
  }
  • Example:
  import java.util.Scanner;
  class SamuelPatel {
      public static void main(String[] args) {
          int n;
          System.out.println("Enter any number: ");
          Scanner r = new Scanner(System.in);
          n = r.nextInt();
          if (n >= 0) {
              System.out.println("Positive Number");
          } else {
              System.out.println("Negative");
          }
      }
  }
  • Output:
  Enter any number: 7
  Positive Number
If-Else If Ladder Statement
  • Used for checking multiple conditions.
  • Syntax:
  if (condition1) {
      // Code to execute if condition1 is true
  } else if (condition2) {
      // Code to execute if this condition is true
  } else {
      // Code to execute if none of the conditions are true
  }
  • Example:
  import java.util.Scanner;
  public class SamuelPatel {
      public static void main(String[] args) {
          int marks;
          System.out.println("Enter marks ");
          Scanner r1 = new Scanner(System.in);
          marks = r1.nextInt();
          if (marks > 80) {
              System.out.println("First rank");
          } else if (marks <= 80 && marks >= 60) {
              System.out.println("Second rank");
          } else {
              System.out.println("Pass");
          }
      }
  }
  • Output:
  Enter the marks:
  85
  First rank
Nested If-Else Statement
  • Definition: An if-else block inside another if-else block.
  • Syntax:
  if (condition1) {
      if (condition2) {
          // Statements if both conditions are true
      } else {
          // Statements if condition2 is false
      }
  } else {
      // Statements if condition1 is false
  }
  • Example:
  class SamuelPatel {
      public static void main(String[] args) {
          int a = 10, b = 20, c = 5;
          if (a > b) {
              if (a > c) {
                  System.out.println("a is greater");
              } else {
                  System.out.println("c is greater");
              }
          } else {
              if (b > c) {
                  System.out.println("b is greater");
              } else {
                  System.out.println("c is greater");
              }
          }
      }
  }
  • Output:
  Check if (a > b) → if (10 > 20) → false
  The program moves to the else block.
  Check if (b > c) → if (20 > 5) → true
  The program prints b, which is b is greater.
Switch Statement
  • Definition: A multiple-choice decision-making statement.
  • Syntax:
  switch(expression) {
      case 1:
          statement1;
          break;
      case 2:
          statement2;
          break;
      case n:
          statementN;
          break;
      default:
          statementDefault;
  }
  • Example:
  import java.util.Scanner;
  public class SamuelPatel {
      public static void main(String[] args) {
          int a = 10, b = 20, ch;
          System.out.print("Enter User Choice...\n");
          Scanner r = new Scanner(System.in);
          ch = r.nextInt();
          switch(ch) {
              case 1:
                  System.out.print("Sum " + (a + b));
                  break;
              case 2:
                  System.out.print("Sub " + (a - b));
                  break;
              case 3:
                  System.out.print("Multi " + (a * b));
                  break;
              case 4:
                  System.out.print("Div " + (a / b));
                  break;
              default:
                  System.out.print("Invalid Choice..! ");
          }
      }
  }
  • Output:
  Enter User Choice...
  1
  Sum 30

Introduction to Loops in Java

  • Definition: Loops execute a block of code multiple times until a condition is met.
  • Types of Loops:
    1. For Loop
    2. While Loop
    3. Do-While Loop
While Loop in Java
  • Definition: Repeats a block of code as long as a condition is true.
  • Syntax:
  while(condition) {
      // Code to be executed
  }
  • Example:
  class SamuelPatel {
      public static void main(String[] args) {
          int n = 1;
          while (n <= 10) {
              System.out.println("I love Animals");
              n++;
          }
      }
  }
  • Output:
  I love Animals
  (This will repeat 10 times)
Do-While Loop in Java
  • Definition: A post-test loop: executes at least once, checks condition afterward.
  • Syntax:
  do {
      // Code to execute
  } while (condition);
  • Example:
  class SamuelPatel {
      public static void main(String[] args) {
          int n = 1;
          do {
              System.out.println(n);
              n++;
          } while (n <= 10);
      }
  }
For Loop in Java
  • Definition: The most common loop used for initialization and iteration in one line.
  • Syntax:
  for (initialization; condition; increment/decrement) {
      // Code to execute
  }
  • Example:
  for (int i = 1; i <= 5; i++) {
      System.out.print(i);
  }
  • Output:
  1 2 3 4 5

Method Parameters and Return Values

  • Categories of Methods in Java:
    1. With Parameters & with Return Value
    2. With Parameters & without Return Value
    3. Without Parameters & with Return Value
    4. Without Parameters & without Return Value
Methods with Parameters & with Return Value
  • Syntax:
  ReturnType MethodName(Parameter1, Parameter2, ...) {
      // Method body (statements)
  }
  • Example:
  class Sample {
      int min(int a, int b) {
          if (a < b) {
              return a;
          } else {
              return b;
          }
      }
      public static void main(String[] args) {
          Sample obj = new Sample();
          int result = obj.min(15, 25);
          System.out.println(result); //OUTPUT: 15
      }
  }
Methods with Parameters & without Return Value
  • Syntax:
  void MethodName(Parameter1, Parameter2, ...) {
      // Method body (statements)
  }
  • Example:
  class Sample {
      void displaySum(int a, int b) {
          int sum = a + b;
          System.out.println("Sum: " + sum);
      }
      public static void main(String[] args) {
          Sample obj = new Sample();
          obj.displaySum(10, 20); // OUTPUT: Sum: 30
      }
  }
Methods without Parameters & with Return Value
  • Syntax:
  ReturnType MethodName() {
      // Method body (statements)
  }
  • Example:
  class Sample {
      int getNumber() {
          return 42;
      }
      public static void main(String[] args) {
          Sample obj = new Sample();
          int result = obj.getNumber();
          System.out.println("Returned Number: " + result); // OUTPUT: Returned Number: 42
      }
  }
Methods without Parameters & without Return Value
  • Syntax:
  void MethodName() {
      // Method body (statements)
  }
  • Example:
  class Sample {
      void showMessage() {
          System.out.println("Hello, welcome to Java programming!");
      }
      public static void main(String[] args) {
          Sample obj = new Sample();
          obj.showMessage(); // OUTPUT: Hello, welcome to Java programming!
      }
  }
Method Overloading in Java
  • Definition: Multiple methods in a class with the same name but different parameters.
  • Benefits: Improves readability and allows for polymorphism.
  • Example:
  public String add(String a, String b) {
      return a + b; // Concatenation
  }

  public int add(int a, int b) {
      return a + b; // Addition of two numbers
  }

  public int add(int a, int b, int c) {
      return a + b + c; // Addition of three numbers
  }

Practical Examples

Program to Print Numbers from 1 to N
import java.util.Scanner;
class PrintNumbers {
    public static void main(String[] args) {
        System.out.print("Enter a number: ");
        Scanner r1 = new Scanner(System.in);
        int n = r1.nextInt();
        for (int i = 1; i <= n; i++) {
            System.out.print(i + " ");
        }
    }
}
  • Output:
  Enter a number: 5
  1 2 3 4 5
Program to Check Even or Odd
import java.util.Scanner;
class EvenOdd {
    public static void main(String[] args) {
        System.out.print("Enter a number: ");
        Scanner r1 = new Scanner(System.in);
        int num = r1.nextInt();
        if (num % 2 == 0) {
            System.out.println(num + " is Even");
        } else {
            System.out.println(num + " is Odd");
        }
    }
}
  • Output:
  Enter a number: 5
  5 is Odd
Program to Check Leap Year
import java.util.Scanner;
class LeapYearCheck {
    public static void main(String[] args) {
        Scanner r1 = new Scanner(System.in);
        System.out.print("Enter a year: ");
        int year = r1.nextInt();
        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:
  Enter a year: 2024
  2024 is Leap Year

Conclusion

  • These basics of control flow and methods provide a foundation for programming in Java, enabling developers to create robust applications with decision-making capabilities and reusable code segments through methods.