Functions in Java

 In Java, functions (more correctly called methods) are blocks of code that perform a specific task. They help in code reusability, modularity, and readability.


✅ What is a Function/Method in Java?

A method in Java is a block of code that:

  • Has a name

  • Can take input (parameters)

  • May return a value

  • Is called (invoked) when needed


πŸ”Ή Syntax of a Method


returnType methodName(parameter1, parameter2, ...) { // Method body return value; // if returnType is not void }

πŸ”Ή Types of Methods in Java

  1. Predefined methods – like System.out.println(), Math.sqrt()

  2. User-defined methods – you define these based on your requirements


πŸ”Έ Example 1: Method without Parameters and without Return Value


public class HelloWorld { static void greet() { System.out.println("Hello, welcome to Java!"); } public static void main(String[] args) { greet(); // Method call } }

πŸ”Έ Example 2: Method with Parameters


public class Calculator { static void add(int a, int b) { int sum = a + b; System.out.println("Sum: " + sum); } public static void main(String[] args) { add(5, 7); // Output: Sum: 12 } }

πŸ”Έ Example 3: Method with Return Value


public class Square { static int square(int num) { return num * num; } public static void main(String[] args) { int result = square(4); System.out.println("Square: " + result); } }

πŸ”Ή Key Components of a Method

ComponentDescription
returnTypeType of value the method returns (e.g., int, void)
methodNameName of the method (should be meaningful)
parametersInput values (optional)
returnUsed to return value from method (if not void)

πŸ”Ή Method Overloading (Same name, different parameters)


public class OverloadExample { static void greet() { System.out.println("Hello!"); } static void greet(String name) { System.out.println("Hello, " + name + "!"); } public static void main(String[] args) { greet(); // Output: Hello! greet("Alice"); // Output: Hello, Alice! } }

πŸ“ Best Practices

  • Method names should be verbs and start with lowercase.

  • Keep methods short and do one thing well.

  • Use static if the method doesn't need to access instance variables.

Comments

Popular posts from this blog

Object Oriented Programming PBCST 304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Object Oriented Programming PBCST 304 Course Details and Syllabus

Type casting in Java