0% found this document useful (1 vote)
114 views11 pages

Understanding Java Method Basics

A method in Java is a block of code that performs a specific task. Methods are used to organize code and allow for code reusability. There are two types of methods in Java: predefined methods that are part of the Java class libraries, and user-defined methods that are created by programmers. A method declaration specifies the method's visibility, return type, name, and parameters. Methods are called or invoked to execute the code within their block.

Uploaded by

M Usmitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
114 views11 pages

Understanding Java Method Basics

A method in Java is a block of code that performs a specific task. Methods are used to organize code and allow for code reusability. There are two types of methods in Java: predefined methods that are part of the Java class libraries, and user-defined methods that are created by programmers. A method declaration specifies the method's visibility, return type, name, and parameters. Methods are called or invoked to execute the code within their block.

Uploaded by

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

What is a method in Java?

A method is a block of code or collection of statements or a set of code grouped together to perform a certain
task or operation. It is used to achieve the reusability of code. We write a method once and use it many times.
We do not require to write code again and again. It also provides the easy modification and readability of code,
just by adding or removing a chunk of code. The method is executed only when we call or invoke it.

Method Declaration

The method declaration provides information about method attributes, such as visibility, return-type, name, and
arguments. It has six components that are known as method header, as we have shown in the following figure.

43.1M
757
Prime Ministers of India | List of Prime Minister of India (1947-2020)

Method Signature: Every method has a method signature. It is a part of the method declaration. It includes
the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the
method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier in our application.
o Private: When we use a private access specifier, the method is accessible only in the classes in which it is
defined.
o Protected: When we use protected access specifier, the method is accessible within the same package
or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses default access
specifier by default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the
functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method
name must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It
contains the data type and variable name. If the method has no parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed
within the pair of curly braces.

Naming a Method
While defining a method, remember that the method name must be a verb and start with a lowercase letter. If
the method name has more than two words, the first name must be a verb followed by adjective or noun. In the
multi-word method name, the first letter of each word must be in uppercase except the first word. For example:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

It is also possible that a method has the same name as another method name in the same class, it is known
as method overloading.

Types of Method
There are two types of methods in Java:

o Predefined Method
o User-defined Method

Predefined Method

In Java, predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods. It is also known as the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point. Some pre-defined methods are length(),
equals(), compareTo(), sqrt(), etc. When we call any of the predefined methods in our program, a series of
codes related to the corresponding method runs in the background that is already stored in the library.

Each and every predefined method is defined inside a class. Such as print() method is defined in
the [Link] class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.

Let's see an example of the predefined method.

public class Demo   
{  
public static void main(String[] args)   
{  
// using the max() method of Math class  
[Link]("The maximum number is: " + [Link](9,7));  
}  
}  

Output:

The maximum number is: 9

In the above example, we have used three predefined methods main(), print(), and max(). We have used
these methods directly without declaration because they are predefined. The print() method is a method
of PrintStream class that prints the result on the console. The max() method is a method of the Math class
that returns the greater of two numbers.

We can also see the method signature of any predefined method by using the link [Link]
When we go through the link and see the max() method signature, we find the following:

In the above method signature, we see that the method signature has access specifier public, non-access
modifier static, return type int, method name max(), parameter list (int a, int b). In the above example, instead
of defining the method, we have just invoked the method. This is the advantage of a predefined method. It makes
programming less complicated.

Similarly, we can also see the method signature of the print() method.

User-defined Method

The method written by the user or programmer is known as a user-defined method. These methods are
modified according to the requirement.

How to Create a User-defined Method

Let's create a user defined method that checks the number is even or odd. First, we will define the method.

/user defined method  
public static void findEvenOdd(int num)  
{  
//method body  
if(num%2==0)   
[Link](num+" is even");   
else   
[Link](num+" is odd");  
}  

We have defined the above method named findevenodd(). It has a parameter num of type int. The method does
not return any value that's why we have used void. The method body contains the steps to check the number is
even or odd. If the number is even, it prints the number is even, else prints the number is odd.

How to Call or Invoke a User-defined Method


Once we have defined a method, it should be called. The calling of a method in a program is simple. When we
call or invoke a user-defined method, the program control transfer to the called method.

mport [Link];  
public class EvenOdd  
{  
public static void main (String args[])  
{  
//creating Scanner class object     
Scanner scan=new Scanner([Link]);  
[Link]("Enter the number: ");  
//reading value from the user  
int num=[Link]();  
//method calling  
findEvenOdd(num);  
}  

[Link]

import [Link];  
public class EvenOdd  
{  
public static void main (String args[])  
{  
//creating Scanner class object     
Scanner scan=new Scanner([Link]);  
[Link]("Enter the number: ");  
//reading value from user  
int num=[Link]();  
//method calling  
findEvenOdd(num);  
}  
//user defined method  
public static void findEvenOdd(int num)  
{  
//method body  
if(num%2==0)   
[Link](num+" is even");   
else   
[Link](num+" is odd");  
}  
}  

Output 1:

Enter the number: 12


12 is even

Output 2:

Enter the number: 99


99 is odd

[Link]
public class Addition   
{  
public static void main(String[] args)   
{  
int a = 19;  
int b = 5;  
//method calling  
int c = add(a, b);   //a and b are actual parameters  
[Link]("The sum of a and b is= " + c);  
}  
//user defined method  
public static int add(int n1, int n2)   //n1 and n2 are formal parameters  
{  
int s;  
s=n1+n2;  
return s; //returning the sum  
}  
}  

Output:

The sum of a and b is= 24

Static Method

A method that has static keyword is known as static method. In other words, a method that belongs to a class
rather than an instance of a class is known as a static method. We can also create a static method by using the
keyword static before the method name.

The main advantage of a static method is that we can call it without creating an object. It can access static data
members and also change the value of it. It is used to create an instance method. It is invoked by using the class
name. The best example of a static method is the main() method.

Example of static method

[Link]

public class Display  
{  
public static void main(String[] args)   
{  
show();  
}  
static void show()   
{  
[Link]("It is an example of static method.");  
}  
}  

Output:

It is an example of a static method.


Instance Method

The method of the class is known as an instance method. It is a non-static method defined in the class. Before
calling or invoking the instance method, it is necessary to create an object of its class. Let's see an example of an
instance method.

[Link]

public class InstanceMethodExample  
{  
public static void main(String [] args)  
{  
//Creating an object of the class  
InstanceMethodExample obj = new InstanceMethodExample();  
//invoking instance method   
[Link]("The sum is: "+[Link](12, 13));  
}  
int s;  
//user-defined method because we have not used static keyword  
public int add(int a, int b)  
{  
s = a+b;  
//returning the sum  
return s;  
}  
}  

Output:

The sum is: 25

There are two types of instance method:

o Accessor Method
o Mutator Method

Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor method. We can
easily identify it because the method is prefixed with the word get. It is also known as getters. It returns the value
of the private field. It is used to get the value of the private field.

Example

1. public int getId()    
2. {    
3. return Id;    
4. }    
5. Mutator Method: The method(s) read the instance variable(s) and also modify the values. We can easily
identify it because the method is prefixed with the word set. It is also known as setters or modifiers. It
does not return anything. It accepts a parameter of the same data type that depends on the field. It is
used to set the value of the private field.

6. Example
Example of accessor and mutator method

[Link]

1. public class Student   
2. {  
3. private int roll;  
4. private String name;  
5. public int getRoll()    //accessor method  
6. {  
7. return roll;  
8. }  
9. public void setRoll(int roll) //mutator method  
10. {  
11. [Link] = roll;  
12. }  
13. public String getName()   
14. {  
15. return name;  
16. }  
17. public void setName(String name)   
18. {  
19. [Link] = name;  
20. }  
21. public void display()  
22. {  
23. [Link]("Roll no.: "+roll);  
24. [Link]("Student name: "+name);  
25. }  
26. }  

Abstract Method

The method that does not has method body is known as abstract method. In other words, without an
implementation is known as abstract method. It always declares in the abstract class. It means the class itself
must be abstract if it has abstract method. To create an abstract method, we use the keyword abstract.

Syntax

1. abstract void method_name();  

Example of abstract method

[Link]

1. abstract class Demo //abstract class  
2. {  
3. //abstract method declaration  
4. abstract void display();  
5. }  
6. public class MyClass extends Demo  
7. {  
8. //method impelmentation  
9. void display()  
10. {  
11. [Link]("Abstract method?");  
12. }  
13. public static void main(String args[])  
14. {  
15. //creating object of abstract class  
16. Demo obj = new MyClass();  
17. //invoking abstract method  
18. [Link]();  
19. }  
20. }  

Output:

Abstract method...

Factory method

It is a method that returns an object to the class to which it belongs. All static methods are factory methods. For
example, NumberFormat obj = [Link]();

 pass Arrays to Methods in Java?


You can pass arrays to a method just like normal variables. When we pass an array to a method as an
argument, actually the address of the array in the memory is passed (reference). Therefore, any changes to this
array in the method will affect the array.
Suppose we have two methods min() and max() which accepts an array and these methods calculates the
minimum and maximum values of the given array respectively:

Example

import [Link];

public class ArraysToMethod {


   public int max(int [] array) {
      int max = 0;

      for(int i=0; i<[Link]; i++ ) {


         if(array[i]>max) {
            max = array[i];
         }
   }
      return max;
   }
public int min(int [] array) {
      int min = array[0];
  
      for(int i = 0; i<[Link]; i++ ) {
         if(array[i]<min) {
            min = array[i];
         }
   }
      return min;
   }

   public static void main(String args[]) {


      Scanner sc = new Scanner([Link]);
      [Link]("Enter the size of the array that is to be created::");
      int size = [Link]();
      int[] myArray = new int[size];
      [Link]("Enter the elements of the array ::");

      for(int i=0; i<size; i++) {


         myArray[i] = [Link]();
   }
      ArraysToMethod m = new ArraysToMethod();
      [Link]("Maximum value in the array is::"+[Link](myArray));
      [Link]("Minimum value in the array is::"+[Link](myArray));
   }
}

Output
Enter the size of the array that is to be created ::
5
Enter the elements of the array ::
45
12
48
53
55
Maximum value in the array is ::55
Minimum value in the array is ::12

pass objects as an argument in Java


you can pass objects as arguments in Java. Consider the following example: Here we have a class with name
Employee

Example
In the following Java example, we a have a class with two instance variables name and age and a
parameterized constructor initializing these variables.
We have a method coypObject() which accepts an object of the current class and initializes the instance
variables with the variables of this object and returns it.
In the main method we are instantiating the Student class and making a copy by passing it as an argument to
the coypObject() method.
import [Link];
public class Student {
   private String name;
   private int age;
   public Student(){
   }
   public Student(String name, int age){
      [Link] = name;
      [Link] = age;
   }
   public Student copyObject(Student std){
      [Link] = [Link];
      [Link] = [Link];
      return std;
   }
   public void displayData(){
      [Link]("Name : "+[Link]);
      [Link]("Age : "+[Link]);
   }
   public static void main(String[] args) {
      Scanner sc =new Scanner([Link]);
      [Link]("Enter your name ");
      String name = [Link]();
      [Link]("Enter your age ");
      int age = [Link]();
      Student std = new Student(name, age);
      [Link]("Contents of the original object");
      [Link]();
      [Link]("Contents of the copied object");
      Student copyOfStd = new Student().copyObject(std);
      [Link]();
   }
}

Output
Enter your name
Krishna
Enter your age
20
Contents of the original object
Name : Krishna
Age : 20
Contents of the copied object
Name : Krishna
Age : 20

Java this Keyword
Definition and Usage
The this keyword refers to the current object in a method or constructor.
The most common use of the this keyword is to eliminate the confusion between class attributes and
parameters with the same name (because a class attribute is shadowed by a method or constructor
parameter). If you omit the keyword in the example above, the output would be "0" instead of "5".

this can also be used to:

 Invoke current class constructor


 Invoke current class method

 Return the current class object

 Pass an argument in the method call

 Pass an argument in the constructor call

Common questions

Powered by AI

Static methods in Java belong to the class itself rather than any instance of the class, allowing them to be invoked without creating an object. They can access static variables but cannot directly access instance variables. Instance methods, conversely, belong to objects and require an object to be invoked; they can access both instance and static variables. The choice between static and instance methods impacts object-oriented design, as static methods provide utility-like functions while instance methods maintain encapsulation and state management .

Passing objects as arguments in Java methods differs from primitive types as it involves passing the reference to the object rather than a direct value. This means that changes to the object within the method affect the original object outside the method, a behavior not observed with primitives which are passed by value. The potential advantages include memory efficiency and the ability to modify the original object, while the side effects might include unintended modifications and side effects if the method does not handle the object safely .

When passing an array as an argument to a method in Java, the reference to the array is passed, not a copy of the array itself. This means that any changes made to the array elements within the method affect the original array, highlighting a key aspect of memory management. The memory address of the array is passed, demonstrating Java's approach to handle memory references efficiently. This behavior underscores Java's design to manage resources where direct manipulation of memory addresses is minimized .

The 'this' keyword in Java is crucial for distinguishing between class attributes and method or constructor parameters with the same names, a scenario known as shadowing. By prefixing a variable with 'this', the programmer clarifies that the reference is to the class attribute rather than the parameter, maintaining code clarity and correctness. Beyond resolving attribute shadowing, 'this' is also employed for invoking other constructors, class methods, and managing object references, showcasing its versatile role in object-oriented programming .

A method signature in Java includes the method name and parameter list, and it uniquely identifies a method within a class. It influences method behavior and usability by enabling method overloading, where multiple methods can share the same name but differ in their parameter lists, allowing for diverse operations while maintaining consistent naming. The signature enables the compiler to understand which method to invoke based on the arguments provided, improving code clarity and facilitating method reuse and polymorphism .

Predefined methods in Java are advantageous because they simplify programming by allowing developers to use pre-built methods from Java's class libraries, reducing the need to write code from scratch. This makes programming less complicated and reduces the development time. Unlike user-defined methods, which are created and defined by the programmer and can be adapted to specific requirements, predefined methods are static and universally available across Java applications without needing additional declaration .

Abstract methods in Java are defined in abstract classes and lack a method body, meaning they provide no implementation. Instead, they serve as placeholders for declared method signatures that must be implemented in subclasses. Regular methods, on the other hand, have complete method bodies and can be executed without additional subclass requirements. Abstract methods enforce a design framework where subclasses extend the abstract class, ensuring a consistent method structure while allowing the flexibility for specific behavior in subclasses .

Method overloading allows multiple methods in the same class to have the same name but differing in the parameter list (method signature). This contributes to flexibility by enabling different implementations of a method name that can handle different data types or differing numbers of parameters, enhancing code readability and reuse. Overloading specifically relies on variations in the method signature, as it involves creating multiple methods with the same name differentiated by their parameter lists .

Accessor methods in Java, commonly known as getters, retrieve values from private instance variables and are named with a "get" prefix. Mutator methods, also known as setters, modify the values of private instance variables and typically begin with "set." Accessors return a value, while mutators do not return any value but accept parameters for updating the object's state. Accessors provide controlled read access to the object's fields, while mutators manage write access, maintaining encapsulation principles .

Access specifiers in Java, such as public, private, protected, and default, determine the visibility and accessibility of methods. Public specifiers allow methods to be accessible from any class, whereas private limits accessibility to the defining class. Protected permits access within the same package and subclasses outside the package. The default, applied implicitly with no explicit specifier, restricts method access to the package only. These specifiers enable controlled interaction with methods, supporting encapsulation and secure data handling by defining clear boundaries for method visibility based on the design needs .

You might also like