0% found this document useful (0 votes)
17 views10 pages

Java Methods: Definition and Usage

The document provides an overview of Java methods, explaining their structure, benefits, and usage, including user-defined and recursive methods. It illustrates method calling, dynamic methods with parameters, and the use of static methods. Additionally, it covers Java's standard library methods and best programming practices for writing effective code.

Uploaded by

pugalsankaran
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views10 pages

Java Methods: Definition and Usage

The document provides an overview of Java methods, explaining their structure, benefits, and usage, including user-defined and recursive methods. It illustrates method calling, dynamic methods with parameters, and the use of static methods. Additionally, it covers Java's standard library methods and best programming practices for writing effective code.

Uploaded by

pugalsankaran
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming Concept Practiced

1.​ Java Methods - Methods are used to organize our code. Methods help us divide our
program into smaller chunks to make it easier to use and understand.
a.​ Methods help to reduce and reorganize the complexity of the program. As a result, we
can focus on only a small part of the problem at one time.
b.​ A method is a verb-like function that performs specific actions so takes in some input
and gives a response

Here are the different parts of the Java Methods


a.​ Method Name - Every method has a Name. In this case greet. Note the name indicates
the work the method is going to perform like greet with “Hello, How do you do”
b.​ methodName() with Paraenthesis ( ) - A method name ends with parentheses. An
optional parameters can be added as input to the method. In the case of greet, its a
method with empty parameters which means no input is needed to perform action.
c.​ Method Body { } - Its the body of the method which has code to perform actions
indicated with the curly brackets { }. In the case of greet, the body outputs Hello, How
do you do”
d.​ Return Type - The method represents the type of data returned by the method. In the
case of greet, its return type is void which means method doesn't return any value.
2.​ Running greet() Method - The following code when run sees no output. Because the
greet method is not called or invoked
class Main {
void greet() {
[Link]("Hello, How do you do?");
}
public static void main(String[] args) {
}
}

1
3.​ Calling Method in Java - In Java, we use an object of the class to call the method, so first,
we need to create an object of the class.
Main obj = new Main();

a.​ NOTE: We haven't discussed Objects or Classes, our objective is method calling alone.
b.​ So we create the object and call its method as in
Main obj = new Main();
[Link]();

Java
class Main {

void greet() {
[Link]("Hello");
[Link]("How do you do?");
}

public static void main(String[] args) {


// create object of Main
Main obj = new Main();

// call the method


[Link]();
}
}

c.​ Working of Code - Here, we are using the object (obj) along with the dot operator (.) to
call the method

2
a.​ Step 1: When a method is called, the program's control jumps to the method definition.
In this case, the greet() method is called
b.​ Step 2: Then, the statements inside the greet() method are executed.
c.​ Step 3: After all the statements are executed, the program's control jumps back to the
main() method and moves to the next line of code after the greet() method call.

Java
class Main {

void greet() {
[Link]("Hello");
[Link]("How do you do?");
}

public static void main(String[] args) {


// create object of Main
Main obj = new Main();

// call the method


[Link]();
}
}

4.​ Using a Method Multiple Times - One of the benefits of writing methods is to write once
and use it many times in different parts of the program
5.​ Making Methods Dynamic - It is possible to create methods that take input and return
output. In programming terms:
a.​ Method Arguments or Method Parameters: Adding arguments or parameters to
methods means adding inputs to the method. We can add 0, 1, or many parameters to
the method as per the input needed to do the work
b.​ Java return keyword - Using the return keyword method can return the results
essentially returning the output of the method
6.​ Benefits of using Methods -
a.​ A method is an independent piece of working code. Write once and use it everywhere.
b.​ The method can be reused multiple times in different parts of the code.
c.​ Writing Methods make the program more modular and less error-prone.

The Following Program crates a UnitConverter class with a method convertKmToMiles


which takes in kilometer as a parameter and returns miles

3
Java
// Write a Program to convert from one unit to another unit and convert
// kilometer to miles

public class UnitConverter {

// Method To convert kilometers to miles and return the value


public double convertKmToMiles(double km) {
// Convert km to miles
double km2miles = 0.621371;
double miles = km * km2miles;

// return the value


return miles;
}

public static void main(String[] args) {


// Create a Scanner object
Scanner sc = new Scanner([Link]);

// Take input for km


[Link]("Enter the distance in kilometers: ");
double km = [Link]();

// Create a UnitConverter object


UnitConverter unitConverter = new UnitConverter();

// Call the method to convert km to miles


double miles = [Link](km);

// Display value in miles


[Link]("Distance in miles: " + miles);

// Calling the Method again to convert km to miles and display it


[Link]("Enter the distance in kilometers: ");
km = [Link]();
miles = [Link](km);
[Link]("Distance in miles: " + miles);

// Close the Scanner object


[Link]();
}
}

4
7.​ User-Defined Methods - The methods defined so far are written by us the user and hence
are called User Defined Methods. They have a return type, method name, method
parameters, and method body.
8.​ Recursive Methods - Recursive Methods are methods that call themselves in order to solve
a problem.

Java
public class RecursiveExample {
// Recursive Method to calculate factorial
public static int factorial(int n) {
if (n == 0) { // Base case: factorial of 0 is 1
return 1;
} else {
return n * factorial(n - 1); // Recursive case
}
}

public static void main(String[] args) {


int number = 5;
[Link]("Factorial of " + number + " is: " +
factorial(number));
}
}

9.​ Java Static Method - A static method in Java is a method that belongs to the class rather
than any specific object. You can call it directly using the class name without creating an
object of the class. Key Characteristics of Static Methods
a.​ Belongs to the Class: Declared with the static keyword, it can be accessed using the
class name.
b.​ Cannot Access Instance Variables: Since static methods are not tied to a specific
object, they can only access other static members (variables or methods) directly.
c.​ Useful for Utility Methods: Commonly used for utility or helper functions.

5
Java
// Write a Program to convert from one unit to another unit as in convert
// kilometer to miles

public class UnitConverter {

// Method To convert kilometers to miles and return the value


public static double convertKmToMiles(double km) {
// Convert km to miles
double km2miles = 0.621371;
double miles = km * km2miles;

// return the value


return miles;
}

public static void main(String[] args) {


// Create a Scanner object
Scanner sc = new Scanner([Link]);

// Take input for km


[Link]("Enter the distance in kilometers: ");
double km = [Link]();

// Call the method to convert km to miles


double miles = [Link](km);

// Display value in miles


[Link]("Distance in miles: " + miles);

// Close the Scanner object


[Link]();
}
}

6
10.​Java Standard Library Methods - The Java Standard Library provides a vast collection of
pre-defined classes and methods organized into packages. These methods simplify
common programming tasks like string manipulation, mathematical operations, and working
with collections. Commonly Used Java Standard Library Methods
a.​ [Link] Package – This package is automatically imported in every Java program.
Commonly used Methods are from Math and String class. We have so far used
[Link]("") which is a System class defined in [Link] package.

b.​ [Link] Package – This package provides utility classes like Scanner, ArrayList,
and HashMap. We have so far used the Scanner class to take user input.

11.​[Link] class – For all the Mathematical operations are defined inside the Math
class. Most commonly used methods of Math class are
a.​ [Link]() – The sqrt() method is used to find the square root of a number.
class Main {
public static void main(String[] args) {
// find the square root
int number = 25;
double squareRoot = [Link](number);
[Link]("Square root of " + number + " is " + squareRoot);
}
}

b.​ [Link]() – The pow() is used to find the power of a number. It takes two arguments
(base value and power value) and returns the power raised to the base.
class Main {
public static void main(String[] args) {
3
// find the power of a number whose base is 2 and power is 3 i.e. 2
int base = 2, power = 3;
double result = [Link](base, power);
[Link]("The result is " + result);
}
}

7
c.​ [Link]() – The random() method to get a random number from 0.0 to less
than 1.0.

d.​ [Link]() between 0.0 and 5.0 – We can modify this program to generate
random numbers from 0.0 to less than 5.0. by multiplying the random number by 5 as in
double randomNumber = [Link]() * 5;

e.​ Integer [Link]() between 1.0 and 10.0 – We can get an Integer random number
between 0.0 and 10.0 by multiplying the random result by 10 and then adding 1. Finally
type casting to int as in
int randomNumber = (int) ([Link]() * 10 + 1);

Java
class Main {
public static void main(String[] args) {
// random number between 0.0 and 1.0
double randomNumber1 = [Link]();
double randomNumber2 = [Link]();
[Link]("The random numbers are " + randomNumber1 +
" and " + randomNumber2);

// random number 0.0 to 4.999


double randomNumber3 = [Link]() * 5;
[Link]("The random number between 0 & 5.0 is “ +
randomNumber3);

// integer random number from 1 to 10


int randomNumber4 = (int) ([Link]() * 10 + 1);
[Link]("The integer random number between 0 & 10 is “ +
randomNumber4);
}
}

8
Best Programming Practice
1.​ All values as variables including Fixed, User Inputs, and Results
2.​ Proper naming conventions for all variables
3.​ Proper Program Name and Class Name
4.​ Proper Method Name which indicates action taking inputs and providing result

Sample Program 1: Create a program to find the sum of all the digits of a number given by a
user using an array and display the sum.
a.​ Use [Link]() and get a 4-digit random integer number
b.​ Write a method to count digits in the number
c.​ Write a method to return an array of digits from a given number.
d.​ Write a method to Find the sum of the digits of the number in the array
e.​ Finally, display the sum of the digits of the number

Java
// Create SumOfDigit Class to compute the sum of 4 digits random number
class SumOfDigits {
// Get a 4 digit random number
public int get4DigitRandomNumber() {
return (int) ([Link]() * 9000) + 1000;
}

// Find the count of digits in the number


public int countDigits(int number) {
int count = 0, temp = number;
while (temp > 0) {
count++;
temp /= 10;
}
return count;
}

// Store the digits of the number in an array


public int[] getDigits(int number, int count) {
int[] digits = new int[count];
int temp = number;
for (int i = count - 1; i >= 0; i--) {
digits[i] = temp % 10;
temp /= 10;
}
return digits;
}

9
// Find the sum of the elements in an array
public int sumArray(int[] array) {
int sum = 0;
for (int i = 0; i < [Link]; i++) {
sum += array[i];
}
return sum;
}

public static void main(String[] args) {


// Get 4 digit random integer number
SumOfDigits sumOfDigits = new SumOfDigits();
int number = sumOfDigits.get4DigitRandomNumber();
[Link]("The Random Mumber is: " + number);

// Get the count of digits


int count = [Link](number);​
[Link]("The count of digit is: " + count);

// Get the array of digits from the number


int[] digits = [Link](number, count);

// Find the sum of the digits of the number


int sum = [Link](digits);

// Display the sum of the digits of the number


[Link]("\nSum of Digits: " + sum);
}
}

10

Common questions

Powered by AI

Methods in Java are crucial for managing complexity in code as they allow developers to break down programs into smaller, more manageable sections. This modular approach enables focusing on individual parts of the code independently, enhancing understanding and reducing errors. Methods also promote code reuse since a single method can be invoked multiple times throughout a program, thereby reducing redundancy. By encapsulating specific actions in methods, they contribute to a modular design where independent pieces of code can be easily maintained and updated without affecting other parts of the program .

Utilizing methods like 'convertKmToMiles' within a UnitConverter class significantly enhances code modularity. It segregates the conversion logic into a self-contained unit, improving readability and simplifying changes. Should the conversion formula need adjustments, modifications are isolated to a single section, minimizing ripple effects on the remainder of the code. This method also facilitates straightforward testing and reuse across varied scenarios, supporting maintainability. Moreover, modular methods ease extendability, allowing additional conversion methods to be seamlessly integrated into the unit without disrupting the existing workflow .

The 'main' method in Java serves as the entry point for program execution. It is where the flow of a Java application begins. When a Java program is run, the Java Virtual Machine (JVM) invokes the main method, transferring control to it. Structurally, it is defined as 'public static void main(String[] args)'. The method facilitates execution flow by orchestrating method invocations and executing statements sequentially. Once the 'main' method completes, the JVM exits, thereby ending the program execution .

Classes from the java.lang package are fundamental to Java programming as they provide essential classes necessary for Java's basic functionalities, including Math for mathematical operations, String for fundamental string manipulation, and System for input/output operations. The java.util package complements this by offering utility classes that simplify common operations, such as collections (ArrayList, HashMap) for data structure manipulation and Scanner for reading user inputs. These packages together provide robust tools that enhance productivity by abstracting complex operations into simple, reusable methods that reduce the need for redundant code .

Parameters in Java methods allow the passing of data inputs necessary for method operations, adding flexibility by enabling methods to perform actions based on varying inputs. Return types specify the nature of data returned by the method, which is essential for conveying the results of computations or transformations performed within the method. Together, parameters and return types significantly enhance a method's utility and reusability, as they allow the same method logic to be applied broadly across different parts of a program while catering to specific data-driven tasks .

The Math class in Java offers a suite of methods that perform various mathematical operations, freeing developers from implementing such common computations manually. Among its commonly used methods are Math.sqrt() for calculating square roots, Math.pow() for exponentiation operations, and Math.random() for generating random numbers. These methods provide precise and optimized ways to perform everyday mathematical tasks, making programming more efficient and helping ensure accurate results .

Static methods in Java belong to the class rather than any specific object, meaning they can be called without creating an instance of the class. This design choice is suitable for utility functions that do not require object state, but it also implies that static methods cannot access instance variables or call instance methods directly, limiting their flexibility. While advantageous for certain tasks, overuse of static methods can lead to less encapsulated code and difficulties in testing and maintaining codebases, particularly when transitioning to designs that leverage polymorphism and inheritance .

To generate a four-digit integer random number using Math.random(), one can multiply the result of Math.random() by 9000 and add 1000, then typecast to an integer. The formula is: int randomNumber = (int)(Math.random() * 9000) + 1000. This method ensures the random number falls within the range of 1000 to 9999, as Math.random() yields a value between 0.0 and 1.0. This nuance of controlling random value ranges is crucial in applications requiring unique identifiers or testing scenarios needing predictable input domains .

User-defined methods in Java are implemented by the programmer, comprising method names, parameters, return types, and bodies determined by specific program needs. Their primary advantage over standard library methods lies in customization, enabling developers to tailor operations precisely to application requirements. They promote code encapsulation and reuse within programs, shaping modular designs where execution logic is structured around problem-specific tasks. While standard library methods offer generic solutions, user-defined methods provide bespoke operations integral to custom application logic and unique business needs .

A recursive method is a method that calls itself to solve a problem, whereas an iterative method uses loops to achieve the same goal. The key difference is in approach; recursion is often more elegant for problems that naturally fit into smaller subproblems, like calculating factorials or navigating data structures like trees. When implementing recursion, it is crucial to define a base case to prevent infinite recursion and stack overflow errors. Ensuring that each recursive call progresses towards the base case is essential for the correctness and efficiency of the solution .

You might also like