Java

Methods in Java

Methods in Java

Java Methods are blocks of code that can be used to perform specific operations within a Java program. They provide an efficient way for developers to create reusable functions which can then be called from anywhere in the application allowing for more 
DRY code and improved readability. This allows any changes made to the method’s logic, such as bug fixes or new features, to propagate throughout the entire project without having duplicate pieces of identical source code cluttering up one’s workspace. 

Java provides several types of methods, including 
● Instance methods: These methods are associated with an instance of a class and can access the state of the object. They are declared with the keyword "void" or with a return type. 
● Static methods: These methods are associated with a class and can be called without creating an instance of the class. The keyword "static" is used to declare the static methods. 
● Constructor methods: The Constructor methods are used to create and initialize an object. They are declared with the same name as the class and are invoked using the keyword "new". 

Instance method example: 

class MyClass { 
int a; 
int b; 
public void assignValues(int a, int b) { 
this.a = a; 
this. b = b; 
} 
} 

This class has an instance method called assignValues, which takes two parameters and assigns them to the instance variables a and b. 

Static method example: 

class MyClass { 
static int x; 
static int y; 
public static void setValues(int x, int y) { 
MyClass.x = x; 
MyClass.y = y; 
} 
} 

This class has a static method called setValues, which takes two parameters and assigns them to the static variables x and y 

Constructor method example: 

class MyClass { 
int x; 
int y; 
public MyClass(int x, int y) { 
this.x = x; 
this.y = y; 
} 
} 

This class has a constructor method with the same name as the class, which takes two parameters and assigns them to the instance variables x and y. 
The method also returns values, look at the example below: 

public int add(int x, int y) { 
return x + y; 
} 

This method takes two integers as a parameter and returns the sum of those integers. 
 

Top course recommendations for you

    ETTTYGGEGERGERWG1342SFGDFG
    1 hrs
    Intermediate
    760 Learners
    4.5  (8)
    MySQL Basics
    5 hrs
    Beginner
    37.1K+ Learners
    4.46  (13362)
    Introduction to Python
    4 hrs
    Beginner
    1.5K+ Learners
    4.82  (38)
    Linked List in C
    1 hrs
    Beginner
    1.1K+ Learners
    Introduction to JUnit
    2 hrs
    Beginner
    1.6K+ Learners
    4.56  (107)
    Introduction to Spring Cloud
    2 hrs
    Beginner
    710 Learners
    4.43  (53)
    Computational Thinking for Programming
    2 hrs
    Beginner
    835 Learners