Intro:
In this article, I would like to share some insights about...
Functions/Methods Works
Scoping
Shadowing
Variable Arguments
Function Overloading
let’s goooo..🙂🔥🔥🔥✌
Functions:
A Function/Method is a block of code that only runs when called. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. In Java, a method must be part of some class that is different from some languages like C, C++, and Python.
Syntax:
public static int sum(int x, int y) {
// body
return x + y;
}
We can explain functions in simple terms. Suppose we have two variables and we want to calculate their sum; we can write the code as “x + y.” If we want to add two more variables, we would write the same line of code again. This can be a waste of time. Instead, we can create a function to handle the addition and then call that function in the main method. This approach makes our work easier and saves a lot of time.
class Main {
public static void main(String[] args) {
int n1 = 25;
int n2 = 20;
int ans = sum(n1, n2);
System.out.println("The Sum of two numbers is: " + ans);
}
// Here’s how we declare and initialize a function.
public static int sum(int num1, int num2){
return num1 + num2;
}
}
Now, we can talk about Method Declaration:
Modifier:
It specifies how your method can be accessed within your application. There are four types of access modifiers.
Public
Private
Default
Protected
Return Type:
A return statement causes the program control to transfer back to the caller of a method. A return type may be a primitive type like int, char, boolean (or) Void type (which returns nothing).
A few important points to remember about return type,
The type of data returned by a method must be compatible with the return type specified by the method. e.g.:- If the return type of some method is boolean we cannot return an integer.
The variable receiving the value returned by a method must also be compatible with the return type specified for the method.
“In Java, there is no pass-by-reference, there is only pass-by-value.”
Function Name:
When specifying the name of a function, the rules for field names also apply to function names, though the convention is slightly different.
Parameter-List:
In this list input parameters are defined, preceded by their data type, within the parentheses. If there is no input we should leave it with empty parentheses.
Scoping:
Scoping refers to the visibility and lifetime of variables or functions within a program. It defines where in the code a variable or method can be accessed or used.
Types of Scoping in Java:
Function Scope
A variable declared inside a method/function scope can’t be accessed outside the method.
class Main {
public static void main(String[] args) {
a = 20; // this shows error because 'a' variable cannot be accessed in
// main method which declared in the function
}
public static int multiple(int ans) {
int a = 1;
}
}
Block Scope
Variables declared inside blocks of code (e.g., loops, if-else blocks) are accessible only within that block.
public class ScopeExample {
public void display() {
if (true) {
int a = 5; // Block scoped variable
System.out.println(a);
}
// System.out.println(a); // Error: a is not accessible outside the block
}
}
Instance Scope
Variables declared inside a class but outside any method are instance variables. They belong to an object (instance of a class). These variables are accessible within the class and are tied to the lifetime of the object.
public class ScopeExample {
int y = 20; // Instance variable
public void display() {
System.out.println(y); // Accessible here
}
}
Shadowing:
Shadowing in Java refers to the practice of using variables with the same name in overlapping scopes, where a variable in a lower-level scope overrides a variable in a higher-level scope. In this case, the variable in the higher-level scope is shadowed by the variable in the lower-level scope.
public class Shadowing {
static int x = 40; // this will be shadowed at line 8
public static void main(String[] args) {
System.out.println(x); // 40
int x; // the class variable at line 4 shadowed by this
// System.out.println(x); // scope will begin when value is initialised
x = 90;
System.out.println(x); // 90,
fun(); // 40
}
static void fun() {
System.out.println(x);
}
}
Variable Arguments:
Variable Arguments are used to take a variable number of argument. A method that takes a variable number of arguments is a Varargs method.
// Syntax:
static void fun (int ...a) {
// body
}
Here, Parameters would be an array of type int[] parameters.
Function Overloading:
Function Overloading happens when a class has multiple methods with the same name but with different parameters.The methods are differentiated based on the number of parameters, types of parameters, or the order of parameters.
Rules for Function Overloading
Methods must have the same name.
The parameter list must be different (varying in type, number, or order of parameters).
The return type alone cannot differentiate methods.
Methods can have different access modifiers (public, private, etc.
public class OverLoading {
public static void main(String[] args) {
fun(5);
fun("Pavan");
int ans = sum(3, 4);
System.out.println(ans);
int res = sum(4, 5, 6);
System.out.println(ans);
}
static int sum(int a, int b) {
return a + b;
}
static int sum(int a, int b, int c){
return a + b + c;
}
static void fun(int a){
System.out.println("first one");
System.out.println(a);
}
static void fun(String name){
System.out.println("second one");
System.out.println(name);
}
}
Conclusion:
In Java, functions are essential for optimizing code and saving developers a considerable amount of time. I hope that anyone reading this article will gain a solid understanding of functions, scoping, shadowing, and overloading. I will also provide several challenging problems for you to solve using functions.
Function Practice:
Write a function that returns all prime numbers between two given numbers
Define a program to find out whether a given number is even or odd.
Define two methods to print the maximum and the minimum number
respectively among three numbers entered by the user.Define a method that returns the product of two numbers entered by the user.
Write a program to print the factorial of a number by defining a method.
Thank you, :)
STAY HARD!!