Java Methods
Method is block of code or collections(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
Syntax
AccessModifer returntype methodName(Parameter List)
{
// method body
}
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:
- 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);
}
}
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);
}
}
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;
}
}
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);
}
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);
}
}
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);
}
}
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>
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]);
}
// 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>
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>
public class MethodandBlock_Scope_Example {
public static void main(String[] args) {
//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
}
}
<u>Java Recursion:-</u>
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));
/*
- 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
- ------------
-
*/
}
}
package java_Method;
// 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;
}
}
}