DEV Community

Prasanth
Prasanth

Posted on • Edited on

Java Methods

What is method?

  • Method is block of code or collection(group) of statement that perform a specific task.All method in java belong to a class.method similar to function and expose the behavior of objects.which only runs when it is called.
  • method must have return type weather void or return data like int , string...etc
  • Method Naming convention in java first letter should be lowercase verb and use camel case for multiple words.

Syntax

AccessModifer returntype methodName(Parameter List)
{
// method body 
}
Enter fullscreen mode Exit fullscreen mode

Access Modifiers:-

=> public, private, protected, default – controls method access

Method overloading:

Same class same method name , different parameters
(compile-time polymorphism)

Method Overriding:-

Different class (extend(is an-relationship) )parent and child relationship and Redefining-parent method in child class( same method name and parameters)

Types of methods:

In java is contain predefined and custom method , those methods have static and non-static method, we will see the later predefined methods(Already defined in the Java class libraries(Built-method)) .

 Object (java.lang.Object)
                    ↑
             Your Custom Class

Enter fullscreen mode Exit fullscreen mode
  • In java Object class have already told static method and non static method, that object class contain mostly non-static method that method public-ally accessible and static methods have private or package-private(default-both classes have same package not to be subclass). they are not accessible for normal java developers,most of them used Jvm internally.

Predefine Static methods:

Example:-

1.Math -> Math.pow(x, y) -> Power (x^y)
2.Arrays -> Arrays.sort(arr) -> Sorts an array
3.Collections -> Collections.sort(list) ->Sorts a list.

Redefine Non-Static methods:

1.String -> str.length() Returns string length
2.String -> str.toUpperCase() Converts to 3.uppercase -> Scanner scanner.nextInt() Reads an int from user input
4.ArrayList -> list.add(x) Adds element to list

  • Static method
  • Instance method
  • Construtor(special method)

Why use methods?

To reuse code: define the code once , and use it many times

without method

public class Test_Withoutmethod {

    public static void main(String[] args) {

        int a =5 , b=3;
        int sum = a+b;
        System.out.println("Sum: "+ sum);

        int x=10, y=2;
        int result =x*y;
        System.out.println("Sum: "+result);
    }

}
Enter fullscreen mode Exit fullscreen mode

with method:


public class Test_withMethod {


    static  void  add(int a , int b)
    {
        int sum =a+b;
        System.out.println("Sum: "+ sum);
    }
public static int minFunction(int n1, int n2)
{
    int min;
//  System.out.println("Min value is : "+min); you can not initialize local variable  ,when printing came compile time error.

    if (n1>n2)
    {
        min =n2;
    System.out.println("Min:n2 is : "+min);
    return min;
    }
            else
            {   
    min=n1;
    System.out.println("Min:n1 is : "+min);
    return min;
            }
    }


    public static void main(String[] args) {

   add(5,3);// callmethod 
   add(10,2); // reuse method 
   minFunction(1,2);
    }

}

Enter fullscreen mode Exit fullscreen mode

Method Defining and Calling with return types and void :-


// method  defining and  calling
public class Method_Example1 {

    public static void main(String[] args) {
  int total= add(210,210);
  System.out.println(" Return value example => Total: 210+210 = "+total);
  twlethMark(550);
    }

    //  method using to void example 
    public static void twlethMark(int mark)
    {
        if(mark>580)
        {
            System.out.println("Rank:A1");
        }
        else if (mark >=550)
        {
            System.out.println("Rank:A2");

        }
        else
        {
            System.out.println("Rank:A3");
        }

    }

    public static int add (int n1,int n2)
    {
        int total = n1+n2;

        return total;


    }

}


Enter fullscreen mode Exit fullscreen mode

swapping values inside method:-

public class Method_SwappingValue {

public static void main(String[] args) {

    int a =30;
    int b =45;
    System.out.println("Before swapping, a =" +a+ " and b ="+b);
    swapValueinFunction(a,b);
    System.out.println("\n Now ,Before and After swapping values will be same here");
    System.out.println("After swapping, a = "+a + ", b = "+b);
}
Enter fullscreen mode Exit fullscreen mode

public static void swapValueinFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = "+a + ", b = "+b);

int c =a;  // a(30) value moved to c (),now a (empty) is  empty
a= b;  // b(45) value moved  a, because a is empty, now a is 45
b=c;  // c(30)  value   moved  to b(empty) , now b is 30
System.out.println("After swapping(Inside), a = "+a + ", b = "+b);



}
Enter fullscreen mode Exit fullscreen mode

}

Method&Calling_Passing_Parameters

public class Method_Passing_Parameters {

    static String letter = " open the letter\n \n"
            + "To Smantatha,\n"
            + "\n"
            + "You are my heartbeat 💓\n"
            + "My heart is not beeping... because you're not near to hear it.\n"
            + "Come close and make it beep again.\n"
            + "Make my heart lovable with your presence. ❤️\n"
            + "\n"
            + "Forever yours,\n"
            + "Prasanth 💌";

    public static void main(String[] args) {
     sendLetter("prasanth","Java Developer"); //passing string parameter
    }

 static void readLetter(String reader,String career,int age) {
        System.out.println(reader+" read the letter from prasanth:");
        System.out.println(reader + letter);
    }

static void sendLetter(String sender,String career) {

System.out.println(sender+" sent a letter to samantha");    
//System.out.println("Message: "+letter);
System.out.println();
readLetter("samantha","Actress",35);

    }

}

Enter fullscreen mode Exit fullscreen mode

Example: method using to return value and void

public class JavaReturnandVoid{

    public static void main(String[] args) {
        int Balance =myAccountBalance(100);
System.out.println("Balance: "+Balance);
System.out.println("\n");
samInfo(25,55);
char [] data=samInfo(25,55,5.9);
System.out.println(data);


    }

static void samInfo(int i, int j) {

    System.out.println("Age: "+i);
    System.out.println("Weight: "+j);


    }

// differen  paremeter if you have ,  how to return  ?
static char[] samInfo(int i, int j, double d) {
    System.out.println("differen  paremeter if you have ?  how to return ");
    String data = "Age:" +i+", weight"+j+", Height:"+d;
    return data.toCharArray(); //convert to char[]

}

static int myAccountBalance(int AccountBalnce ) {

    int myPurse = 1;
    int Balance =myPurse+AccountBalnce;
        return Balance;
    }


}

<u>How to different way return the value:-</u>

Enter fullscreen mode Exit fullscreen mode

public class MethodReturnExample {

public static void main(String[] args) {
    // 1. calling void method 
     greet();
     // 2. calling int return method
       int sum=add(210,210);
       System.out.println("sum: "+ sum);
       //3.calling  String return method
       String message=getMessage("Prasanth");
       System.out.println(message);
       //4. calling method that returns both and string
          Object[] data=getUserinfo();
          System.out.println("Id "+ data[0]);
          System.out.println("Name "+ data[1]);


}
Enter fullscreen mode Exit fullscreen mode

// 1.void method - just print
static void greet() {
System.out.println("Hello ,Welcome to java ");
}
//2. return int

static int add(int num1,int num2)
{
int sum= num1+num2;
return sum;

}
//3. return string

static String getMessage(String name)
{
return "Hi My name is " + name +" i am Javadeveloper";
}

//4. return int and string using object[] or Array
static Object[] getUserinfo()
{
int id =101;
String name ="Hellow";
return new Object[] {id,name};
}

}



<u> Important Return Type Scenarios</u>

Enter fullscreen mode Exit fullscreen mode

int return 5 + 3; Return a number
String return "Hello"; Return a message or text
boolean return a > b; Return true/false
char[] return name.toCharArray(); Return letters from a string
Array return new int[]{1,2,3}; Return multiple numbers
Object return new Person(...); Return class object
void System.out.println("Hi"); Just perform action, no return


// method ovlerloading and overriding we will see Java Oops concept


<u>Method&Block Scope:-</u>

Enter fullscreen mode Exit fullscreen mode

public class MethodandBlock_Scope_Example {

public static void main(String[] args) {
Enter fullscreen mode Exit fullscreen mode

//System.out.println(x);
int a =100;
System.out.println(a);
//method Scope: x is visible any where inside main method
//Anywhere in the method
int x =100;
System.out.println("x in method:"+x);

    if(x>50)
    {
        //Block Scope: y is only visible inside this if block
        //only inside the block
        int y =200;
        System.out.println("Y in if block: "+y);

    }
    // try to access y outside the block
//  System.out.println("y is outside if block: "+y); //error not visible out of block

    }
Enter fullscreen mode Exit fullscreen mode

}



<u>Java Recursion:-</u>



Enter fullscreen mode Exit fullscreen mode

package java_Method;

// Factorial Using Recursion
public class Recursion_Example {

int fact(int n)
{
    int result;

    if (n==1)

        return 1;
        result =fact(n-1) * n;

        /*fact(3-1) *3 -> fact (2) * 3  becomes -> (fact(1) *2)*3)
         * fact(4-1) *4 -> fact (3) * 3  
         * 
         * 
         * 
         * 
         */
        return result ;


}


public static void main(String[] args) {

    Recursion_Example obj1 = new Recursion_Example();
    System.out.println("Factorial of 3 is "+ obj1.fact(3));
    System.out.println("Factorial of 4 is "+ obj1.fact(4));
    System.out.println("Factorial of 5 is "+ obj1.fact(5));
Enter fullscreen mode Exit fullscreen mode
  • fact(5) = 5 x 4 x 3 x 2 x 1 =120
  • fact(1) = 1
  • fact(2) =1*2 =3
  • fact(3) =2*3 =6
  • fact(4) =6*4 = 24
  • fact(5) =24*5 =120
  • ------------------
  • fact(4) = 4 × 3 × 2 × 1 = 24
  • fact(1) =1
  • fact(2) =1*2 =3
  • fact(3) =2*3 =6
  • fact(4) =6*4 =24
  • fact(4) =24
  • ------------------
  • fact(3) = 3 × 2 × 1 = 6
  • fact(1) =1
  • fact(2) =1*2 =2
  • fact(3) =2*3 =6
  • ------------
  • *

    }

}


Enter fullscreen mode Exit fullscreen mode

// Sum of Natural Numbers Using Recursion
public class RecursionExample1 {

public static void main(String[] args) {


    int result = sum(10);
    System.out.println(result);


}

public static int sum(int k)
{
    if(k>0)
    {
        return k+ sum(k-1);
    }

    else
    {
        return 0;
    }
}
Enter fullscreen mode Exit fullscreen mode

}






<u>Feature of Static Method:-</u>

- A static Method  in java manage to the class, not with object (or) instance.
- It can be accessed by all instance  of in  the class, but it does not relay on specific instance.
- static method can accessed directly  static variable without need to create object ,you can access directly. but can not  access non-static member  directly you need to create to object. 

- you can call static method directly another static method and non-static method.

<u>Features of Non-static Method:-</u>

-  In an instance method, you can access both instance and static members (field(use) and methods(calling) directly, without creating an object.
-static variable can not declare to instance and non-static method is useless , you can use only class level not inside of methods. 


Types of instance Method:-
1.Accessor Method (Getters)

Used to read/access the value of a private instance variable, start with the  get.

Enter fullscreen mode Exit fullscreen mode

public class Person {
private String name; /private variable

//Accessor method (getter)
public String getName()
{
return name;
}



2.Mutator methods (Setters)

used to update/modify  the value of private instance variable.Also supports encapsulation.start with set.

Enter fullscreen mode Exit fullscreen mode

public class person
private String name;

//Mutator method (setter)
public void setName(String name)
{
this.name =name;
}
{
this.name = name;
}




Enter fullscreen mode Exit fullscreen mode

Top comments (0)