DEV Community

Rittwick Bhabak
Rittwick Bhabak

Posted on

6. Expressions, Statements, if-then-else , Methods, Method Overloading

1. Expressions

Example:

int score = 100;
if (score > 99){
    System.out.println("You got the high score!");
    score = 0;
}
Enter fullscreen mode Exit fullscreen mode

In the above code score = 100, You got the high score! and score = 0 are expressions only.

2. Keywords

Java has 52 reserved key words

3. if-then-else

Example:

if(score>100) {
    return "Grade A";
} else if(score > 50) {
    return "Grade B";
} else {
    return "Grade C";
}
Enter fullscreen mode Exit fullscreen mode

4. Method

Example:

public static String greetUser(String username) {
        return "Welcome" + username;
}
Enter fullscreen mode Exit fullscreen mode

5. Method Overloading

Example 1:

    public static int loggedIn(int a, int b) {
        return 0;
    }
    public static int loggedIn(int a) {
        return a + 5;
    }
    public static boolean loggedIn(int a) {
        return true;
    }
    public static String loggedIn(String name) {
        return name + " is dancing";
    }
Enter fullscreen mode Exit fullscreen mode

All of the above are valid method overloading, but the example below is not valid:

    public static int loggedIn(int a, int b) {
        return 0;
    }
    public static boolean loggedIn(int a, int b) {
        return true;
    }
Enter fullscreen mode Exit fullscreen mode

This is an error.

Another example of method overloading:

    public static int sum (int a, int b, int c, int d) {
        return sum(a,b,c) + d;
    }
    public  static int sum (int a, int b, int c) {
        return sum(a,b) + c;
    }
    public static int sum (int a, int b) {
        return a + b;
    }
Enter fullscreen mode Exit fullscreen mode

Method overloading is a feature that allows us to have more than one method with the same name, so long as we use different parameters.
It is the ability to create multiple methods of the same name with different implementations.
Calls to an overloaded method will run a specific implementation of that method.

public static void main(String[] args) {
    System.out.println("Hello!");
    System.out.println(5);
    System.out.println(10.75);
}
Enter fullscreen mode Exit fullscreen mode

println method is a great example of method overloading in the Java language. There are actually 10 methods with name println. We can print an integer, double, string, and so on...

Top comments (0)