Home > Java > javaTutorial > body text

Methods in Java

WBOY
Release: 2024-08-30 15:54:38
Original
559 people have browsed it

A java method can be defined as a set of logical java statements written to perform a specific task. They provide a way to reuse code without writing the code again. In Java, any method should be part of a different class from Python, C, and C++. The existence of methods is not possible without a java class. Here is the list of components involved while creating java methods:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Components for Creating Java Methods

Here is the list of components involved while creating java methods:

  • Access Modifier: In java, there exist four different types of access modifiers:
    • Public: Methods declared as public are accessible from all classes within an application.
    • Protected: Methods declared as protected are accessible from the class within which it is defined and all subclasses of that class.
    • Private: Methods declared as private are only accessible from the class within which it is defined.
    • Default: Methods declared as default are accessible from the class within which it is defined and from classes declared within the same package as the class enclosing the method.
  • Return Type: This contains the data type of the value the method is supposed to return, or it is void if the method does not return anything.
  • Method Name: This is the name assigned to the method, which may or may not be unique. It is to be noted that the method name should be verbs, and words used show follow camel case notation.
  • Parameters: This includes a list of input parameters separated by commas with their data types. If the method does not require any input parameters, then () is used.
  • Exceptions: In case a method may throw one or more exceptions, we can list exceptions separated by commas.
  • Method Body: It is the programming content enclosed between braces. The method body contains one or more logical statements for executing a particular task.

Syntax:

Here is a basic syntax of methods:

//declare Enclosing class
public class Myclass{
//declare java method
public String concat(String s1, String s2){
// combine two strings with space
String s3= s1 + " " + s2 ;
//return resulting string
return s3;
}
}
Copy after login

Types of Methods in Java

Methods can be categorized into the following two types:

  • Build-in Methods: These methods are available in the java library and do not need to be created by a developer. For example, the max() method is present in Math class in java.
  • User-defined Methods: A developer in java classes explicitly defines these methods.

Moreover, you can also get and set methods in Java by addressing experts from AssignmentCore who will provide you with Java homework help of any complexity.

Calling a Java Method

When a calling program calls a method, the control goes into the method body. After control goes to the method body, it returns to the calling program under the following three conditions:

  • All statements written inside the method body are executed successfully.
  • Any return statement is encountered.
  • An Exception is thrown.

Static methods are called using the class name, and non-static methods are called using object instance.

Example #1

Now we will see java code examples show how methods are declared and called using java. In this example, we will see how to create a static method and how is it called.

Code:

package com.edubca.methods;
public class MethodDemo{
public static int getMaximum(int a , int b){
if(a>b){
return a;
}else {
return b;
}
}
public static void main (String args[]){
int maxvalue1 = getMaximum(10,23);
System.out.println("Out of 10 and 23, " + maxvalue1 + " is greater" );
int maxvalue2= getMaximum(40,20);
System.out.println("Out of 40 and 20, " + maxvalue2 + " is greater" );
}
}
Copy after login

Output:

Methods in Java

Example #2

In the next example, we will see how to call non–static methods.

Code:

package com.edubca.methods;
public class MethodDemo{
public  int getMinimum(int a , int b){
if(a<b){
return a;
}else {
return b;
}
}
public static void main (String args[]){
MethodDemo demo =new MethodDemo();
int minvalue1 = demo.getMinimum(10,23);
System.out.println("Out of 10 and 23, " + minvalue1 + " is smaller" );
int minvalue2= demo.getMinimum(40,20);
System.out.println("Out of 40 and 20, " + minvalue2 + " is smaller" );
}
}
Copy after login

As we can see above, an instance of an enclosing class is required to call a non-static method. The above code will produce the following output:

Output:

Methods in Java

Example #3

In the next example, we how to create methods throwing exceptions.

Code:

import java.io.*;
package com.edubca.methods;
public class MethodDemo{
public  void mymethod() throws IOException{
throw new IOException("IO Exception occurred...");
}
public static void main (String args[]){
MethodDemo demo =new MethodDemo();
try{
demo.mymethod();
}catch(Exception e){
e.printStackTrace();
}
}
}
Copy after login

As we can see from the above code, whenever a method throws an exception caller, the method must handle the exception using try-catch or any other suitable error handling mechanism. The above code shows the below output on screen:

Output:

Methods in Java

Conclusion

From the above article, we have a clear idea about methods in java. Therefore will the help of methods, we can achieve any task. Using methods make our code reusable and easy to test, understand and debug.

The above is the detailed content of Methods in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!