Introduction to Java Methods Methods in Java are reusable blocks of code designed to perform specific tasks. They enhance code reusability, maintainability, and readability. Java provides predefined (built-in) and user-defined methods. 1. Declaring a Method in Java A method consists of: Access Modifier ( public , private , etc.) Return Type ( void , int , String , etc.) Method Name (should be meaningful) Parameters (optional) Method Body (code inside the method) Syntax: accessModifier returnType methodName (parameters) { // Method body return value; // Optional } Example: public class MethodExample { public static void greet () { System.out.println( "Hello, welcome to Java!" ); } public static void main (String[] args) { greet(); // Calling the method } } 2. Types of Methods in Java 2.1 Predefined (Built-in) Methods Java provides predefined methods like Math.sqrt() , length() for strings, and System.out.printl...
Control Flow Statements in Java – Loops & Conditional Statements Control flow statements in Java allow you to control the execution of your code based on conditions and loops. In this post, we will explore: Conditional Statements – if , if-else , if-else-if , switch Looping Statements – for , while , do-while Jump Statements – break , continue , return Let’s break them down with examples. 1. Conditional Statements in Java 1.1 if Statement The if statement executes a block of code if a condition is true. Syntax: if (condition) { // Code to execute if condition is true } Example: public class IfExample { public static void main (String[] args) { int age = 20 ; if (age >= 18 ) { System.out.println( "You are eligible to vote." ); } } } 1.2 if-else Statement Executes one block of code if the condition is true, otherwise executes another block. Example: public class IfElseExample { public static vo...