Chapter2: Fundamental concepts in Java

Chapter2: Fundamental concepts in Java

·

8 min read

Fundamentals

Conditionals and loops are fundamental programming constructs in Java, as well as in many other programming languages. They allow you to control the flow of your program and perform repetitive tasks. In Java, you can use the if ,elseif ,else, and switch case statement for conditionals and various loop constructs such as for, while, and do-while for looping. Let's explore how to use them

Conditional Statements (if, else if, else)

Conditional statements allow you to execute different blocks of code based on certain conditions.

1. if statement:

int age = 18;
if (age >= 18) {
    System.out.println("You are an adult.");
}

2. else if statement:

int age = 15;
if (age >= 18) {
    System.out.println("You are an adult.");
} else if (age >= 13) {
    System.out.println("You are a teenager.");
} else {
    System.out.println("You are a child.");
}

Switch Statements

  • Switch statements allow you to perform different actions based on different values of a variable.

  • The variable in a switch statement is compared against different case values.

  • Use break to exit the switch block after executing a case.

  • You can include a default case for when no other cases match.

  • Switch statements are often used when you have multiple choices to handle.

  • You can say it as, alternate for if else conditionals.

Example:

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("Other day");
}

In this example, "Wednesday" will be printed because day is set to 3. If day were 5, "Other day" would be printed due to the default case.

Loops

Loops allow us to repeatedly execute a block of code as long as a certain condition is met.

1. for loop:

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

2. while loop:

int count = 0;
while (count < 5) {
    System.out.println("Count: " + count);
    count++;
}

3. do-while loop:

int number = 1;
do {
    System.out.println("Number: " + number);
    number++;
} while (number <= 5);

In a for loop, you specify the initialization, condition, and update of the loop variable all in one place. In a while loop, you specify the condition before entering the loop, and in a do-while loop, the condition is checked after executing the loop at least once.

  1. break and continue:

    • break: Terminates the loop or switch statement it is in.

        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                break; // exit the loop when i equals 5
            }
            // Code here
        }
      
    • continue: Skips the rest of the loop's code for the current iteration and moves to the next iteration.

        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                continue; // skip the code below when i equals 5
            }
            // Code here
        }
      

These control flow statements provide the essential building blocks for writing flexible and powerful Java programs. They enable you to create logic that responds to different conditions and iterates over data structures.

Types of operators

In Java, operators are special symbols or keywords that perform operations on operands. Here's a simple breakdown of the main types of operators in Java:

Arithmetic Operators:

    • Examples: + , - , * , / , %
  1. Comparison (Relational) Operators:

    • Examples: == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to)
  2. Logical Operators:

    • Examples: && (logical AND), || (logical OR), ! (logical NOT)
  3. Assignment Operators:

    • Examples: = (assign value),+= (Add and Assign),-= (Subtract and Assign),*= (Multiply and Assign),/= (Divide and Assign),%= (Modulus and Assign)
  4. Increment and Decrement Operators:

    • Examples: ++ (increment by 1), -- (decrement by 1)
  5. Conditional (Ternary) Operator:

    • Example: ? : (conditional operator)
  6. Bitwise Operators:

    • Examples: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift), >> (right shift), >>> (unsigned right shift)

Functions and Methods

In Java, functions are often referred to as methods. Methods are blocks of code that perform a specific task and can be called (invoked) to execute that task. Here's a simple breakdown of functions/methods in Java:

1. Defining a Method:

  • You define a method using the following syntax:

      returnType methodName(parameter1Type parameter1Name, 
                            parameter2Type parameter2Name, ...) {
          // Code to be executed
          return result; // Optional, specifies the type of the value the method returns
      }
    
  • returnType: The data type of the value that the method returns. If the method doesn't return anything, use void.

  • methodName: The name of the method.

  • parameterType: The data type of the input parameters.

  • parameterName: The name of the input parameters.

  • return: Specifies the value to be returned. If the method doesn't return anything, you can omit this.

2. Example of a Simple Method:

public class Example {
    // Method definition
    public static void sayHello() {
        System.out.println("Hello, World!");
    }

    // Main method (entry point of the program)
    public static void main(String[] args) {
        // Calling the method
        sayHello();
    }
}

In this example, sayHello is a method that prints "Hello, World!" when called. The main method is the entry point of the program, and it calls the sayHello method.

3. Method with Parameters:

public class Calculator {
    // Method definition with parameters
    public static int add(int num1, int num2) {
        return num1 + num2;
    }

    public static void main(String[] args) {
        // Calling the method with arguments
        int result = add(5, 7);
        System.out.println("The sum is: " + result);
    }
}

In this example, the add method takes two parameters (num1 and num2), adds them, and returns the result. The main method then calls add with arguments (5 and 7) and prints the result.

4. Method with Return Value:

public class Square {
    // Method definition with a return value
    public static int square(int number) {
        return number * number;
    }

    public static void main(String[] args) {
        // Calling the method and using the returned value
        int result = square(4);
        System.out.println("The square is: " + result);
    }
}

In this example, the square method takes a parameter, squares it, and returns the result. The main method calls square with an argument (4) and prints the squared result.

In summary, methods in Java are blocks of code that perform a specific task. They can take parameters, execute code, and return a value. Methods are reusable and help in organizing code into modular and manageable units.

Scope in Java

In Java, scope refers to the region of your code where a particular variable can be accessed or used. Understanding the scope of variables is essential for writing error-free and maintainable code. Java has several types of variable scope:

Local Scope:

  • Variables declared within a method, constructor, or block of code have local scope.

  • They can only be accessed within that method, constructor, or block.

  • Local variables are not visible outside of their enclosing block, and they are destroyed when the block exits.

void myMethod() {
    int localVar = 42; // localVar is only accessible inside myMethod()
    System.out.println(localVar); // This is valid
}

Method or Parameter Scope:

  • Method parameters have scope within the method they are declared in.

  • They can shadow (hide) class-level fields with the same name.

int myVar = 10; // Class-level variable

void myMethod(int myVar) {
    System.out.println(myVar); // This will print the parameter myVar, not the class-level one
}

Class Scope (Instance Variables):

  • Instance variables (also called fields) are declared within a class but outside of any method, constructor, or block.

  • They have class scope and can be accessed by any method within the same class, as well as by objects of that class.

  • Each instance (object) of the class has its own copy of instance variables.

class MyClass {
    int instanceVar = 42; // Instance variable
}

Static Scope (Class Variables):

  • Static variables are declared using the static keyword within a class but outside of any method, constructor, or block.

  • They have class scope, just like instance variables.

  • However, there is only one copy of a static variable shared among all instances of the class.

class MyClass {
    static int staticVar = 42; // Static variable
}

Block Scope (Local Blocks):

  • Java allows you to create local blocks within methods, constructors, or other blocks.

  • Variables declared within these local blocks have scope limited to the block itself.

void myMethod() {
    int localVar = 42;

    {
        int blockVar = 10;
        System.out.println(localVar); // Accessible
        System.out.println(blockVar); // Accessible
    }

    System.out.println(localVar); // Accessible
    // System.out.println(blockVar); // Error: blockVar is not accessible here
}

Remember that the principle of variable scope is vital for preventing naming conflicts, understanding where variables are accessible, and managing memory efficiently in your Java programs.

Conclusion

In this blog post, we've embarked on a journey into the core concepts of Java programming. We've explored conditional statements, loops, methods, operators, and variable scope, all of which are foundational elements of Java development. Understanding these fundamentals is crucial as they provide the building blocks for writing organized, efficient, and maintainable Java code.

Keep practicing, exploring, and expanding your Java skills, and remember that each day brings us closer to becoming accomplished Java developers. Stay tuned for more informations. Cheers to all, Happy coding!