Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Method in Java

    Java methods are a set of instructions designed to execute a particular task efficiently. method offer a easy way to modify code as needed. Within this segment, we will deep dive into the concept of Java methods, explore various types of methods, understand their utilization, and the process of invoking them in Java.So let's start this journey


Table Of Content

  • Method in Java
  • Types of Method
  • Method Overloading in Java
  • Static Method
  • Abstract Method


What is a method in Java?

  • At their core, methods are a collection of statements or a block of code that work harmoniously to accomplish a specific task or operation. Think of them as little code superheroes, ready to swoop in and execute your commands with precision and efficiency. The primary purpose of methods is to promote code reusability. Instead of continuous writing the same lines of code multiple times, we can encapsulate those instructions into a method and then reuse it whenever needed. This not only saves us from the chore of repetition but also keeps our code tidy and organized.
  • A method is similar to a function in Procedural programming that it is used to expose the behaviour of an object.




Method Declaration

  • Modifier: It specifies the method's access type, or where it can be accessed in your application. There are four types of access specifiers in Java.
    • public:When we apply the public specifier in our code, all classes have access to that paticular method.The program can access any class, method, or data member that has been declared public. The range of public data members is unrestricted.
    • protected:When the protected access specifier is used in program for any method, we can access that method from within the same package or from subclasses in a different package.
    • private:When the private access specifier is used in program for any method.It is only available within the class in which it is declared.
    • default:When no access specifier is specified in the method declaration tehn Java uses the default access specifier. It is only available from the same package.
  • The return type: Return type is nothing but data type of the method's returned value, or void if the method does not return anything
  • Method Name: A method name is a unique identifier name given to any specific method during declaration. It is essential for the method to have a name that will be easy to call any method and remove ambiguity Consider that if we were to create a method for addition two numbers, it would have to be called addition (). By using name ( addition() ), a method is called.
  • Parameter list: The parameter list are part of method definition in which we provide input parameters, along with their data types, are specified within brackets and separated by commas. If a method does not need any parameters, an empty set of brackets is used.
  • Method Body: Method Body is the method declaration . It includes every action that needs to be taken.

Types of Method

  • There are two types of methods in Java:
    • Predefined Method
    • User-defined Method




Predefined Method

  • predefined methods play a pivotal role. These methods, also referred to as built-in or standard library methods, are already defined within the Java class libraries. As a result, developers can readily tap into their power and convenience by simply calling them within their programs at any desired location.
  • The beauty of predefined methods lies in their ability to save time and effort. Instead of writing code again and again for different small things
  • In a class, there are numerous pre-defined methods, with each one being defined within its respective class. Some examples of these methods include length(), sqrt(), max(), and print().
 // Java  program using class and object   
class Student{  
	public static void main(String args[]){  
		System.out.print("The maximum number is: " + Math.sqrt(64));  
	} 
}  

Output:

8  


User-defined Method


  • A user-defined method are the methods that are define or written by a user or programmer. These techniques are adjusted based on the situation.

How to Create a User-defined Method
 // Java  program using class and object   
class Student{  
	public static void main(String args[]){  
		int x = 10;  
		int y = 20;  		
		int z = addition(x, y);   //Here x and y are actual parameters  & add method is called
		System.out.println("The sum of x and y is = " + z);  
	}  
		
	public static int addition(int a, int b)   //a and b are formal parameters 
        // Here Method is static so that we can access without object
	{  
		int sum;  
		sum=a+b;  
		return sum; //returning the sum  
	}
}  
 

Output:

The sum of x and y is = 30  

In the above example, we have used add method it is not already define so we have define it first and access in main method, we have made add method static because we can access static method without object. you wil learn about static method below this page



Rules for Naming for Methods

A method name typically consists of one or more words first name of method should be a lowercase letter and use a verb. If the method name consists of more than two words then first name should be start with a verb and followed with an adjective or noun.


Rules to Name a Method

  • When declaring a method, make sure the name of the method should be in lowercase and be a verb.
  • Every word in the multi-word method name, except for the first word, should start with a capital letter. For instance, consider examples like "findSum," "getMax," and "setLow."
  • Normally, a method in a class has a name that is clearly different from other methods in that class, but because Java allows for method overloading, this can occasionally happen.

Method Overloading in Java

Programmers can define multiple methods with the same name but different parameters thanks to method overloading. Based on the quantity, nature, and arrangement of the parameters, Java can distinguish between them. This implies that as long as their parameter lists vary, we can have multiple methods with the same name.This function offers flexibility and improves the readability of the code.




Example of Method Overloading
 // Java  program using class and object   
class Addition{  
	static int add(int x,int y){
		return x+y;
	}  
	static int add(int p,int q,int r){
		return p+q+q;
	}  
} 
class Student{  
	public static void main(String args[]){  
		System.out.println(Addition.add(10,20));  
		System.out.println(Addition.add(10,20,30)); 
	}  
}  

Output:

30 
50  


Static Method

A static method in Java is associated with the class itself, not with any particular instance of the class. It can be used even without producing a class object. This makes it convenient for utility methods or operations that don't need instance-specific data because you can access the method directly using the class name.


The primary benefit of static methods is their capacity to offer shared functionality for all instances of a class. You can guarantee that any object or method in the same class, or even in other classes, can access and use a method by declaring it static. This encourages code organisation and reuse.



Example of static method
 // Java  program using class and object   
class Student{	
	public static void main(String args[]){  		  
           add(10, 20);
        } 
       static void add(int x,int y){
            System.out.println(x+y);
        }  	
}  

Output:

30 

Abstract Method

The term "abstract method" refers to a method without a method body. In other words, an abstract method is one that does not have an implementation. The abstract class is where it always declares. If a class has an abstract method, then the class itself must also be abstract. We use the keyword abstract to create an abstract method.



Syntax

 abstract void  method_name();




Example of Abstract Method
 // Java  program using class and object   
abstract class Exam //abstract class  
{  
    abstract void displayMarks();  //abstract method declaration   
}  
public class Student extends Exam  
{  
    void displayMarks()   //method implementation  
    {  
    System.out.println("My First Abstract method");  
    }  
    public static void main(String args[])  
    {  
        Exam obj = new Student();   //creating object of abstract class   
        obj.displayMarks();   //invoking abstract method 
    }  
}  
     

Output:

My First Abstract method 

Factory method

It is a method that sends an object back to its class of origin. Factory methods are all static methods.



Instance Method

An instance method in Java is a type of method that belongs to a specific object or instance of a class.Instance method is fundamental unit of object-oriented programming in Java.Instance methods are linked to paticular objects, unlike to static methods, which are connected to the class as a whole. A class's objects can each have their own set of instance variables and the ability to use instance methods to manipulate those variables.


As part of the class definition, Java requires you to define an instance method. The access modifier, return type (void if the method returns null), method name, optional parameters enclosed in parentheses, and the method body enclosed in curly braces make up the method declaration.




Syntax

 abstract void  method_name();


Example of Instance Method
 // Java  program using class and object   
abstract class Exam //abstract class  
{  
    abstract void displayMarks();  //abstract method declaration   
}  
public class Student extends Exam  
{  
    void displayMarks()   //method implementation  
    {  
    System.out.println("My First Abstract method");  
    }  
    public static void main(String args[])  
    {  
        Exam obj = new Student();   //creating object of abstract class   
        obj.displayMarks();   //invoking abstract method 
    }  
}  
     

Output:

My First Abstract method 

  • There are two types of instance method in Java:
    • Accessor Method
    • Mutator Method



Accessor Method:The accessor method is the name given to the method(s) that read the instance variable(s). The word "get" is prefixed to the method, making it simple to recognise. Getters is another name for it. It gives back the private field's value. It is used to obtain the private field's value.


Example

 public int  getName() 
 { 
    return   name;
 } 


 // Java  program using class and object   
public class Student   
{  
    private static int roll=102;  
    public static int getRoll()    //accessor method  
    {  
        return roll;  
    }     
    public static void main(String[] args) {
        System.out.println(getRoll());  
    }
}
    


Output:

102 

Mutator Method:The method(s) both read and modify the values of the instance variable(s). The word "set" is prefixed to the method, making it simple to recognise. Modifiers or setters are other names for it. It gives no results back. It accepts a field-dependent parameter of the same data type. The private field's value is set using it.


Example

 public int setId(int Id) 
 { 
    this .Id = Id;  
 } 


 // Java  program using class and object   
public class Student   
{  
    private  int roll=102;  
    public void setRoll(int roll) //mutator method  
    {  
        this.roll = roll;  
    }  
    public void displayRoll() 
    {  
        System.out.println(roll);
    }
    public static void main(String[] args) {
        Student objStudent=new Student();
        objStudent.displayRoll();
    }
} 
    


Output:

102 
Java Constructor Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.