Saturday, 8 July 2023

Java Chapter 6 Methods

METHODS IN JAVA 

[Edited and compiled by Souradeep Roy using IntelliJ IDEA (community version)
A method is nothing but a function only which is written inside a class.Since Java is an Object Oriented Programming Language,
we need to write the method inside some class in order to use it.
For instance, if you have written instructions to draw a circle in the method,
it will do that task. You can insert values or parameters into methods,
and they will only be executed when called.

Syntax:-

dataType name()
{
//method body
}

=============================================================================================================================

Now, We will quickly take a look at the examples provided below in order to create a better understanding and clarification

of the Methods in Java.


1.1                 WAP in Java to create a Method to print your name.
_____________________________________________________________________________________________________________________________

 
CODE:-
------
import java.util.Scanner;

public class Function
{
    public static void PrintName(String name)// User defined Function

    {

        Scanner input=new Scanner(System.in);

        System.out.println("Your name is "+name);

    }
 
    public static void main(String[] args)             

 {
        Scanner input=new Scanner(System.in);

        String nam;

        System.out.println("Enter your name ");

        nam= input.nextLine();

        PrintName(nam);//Function call

    }

    }

Output:-
--------
Enter your name

Souradeep

Your name is Souradeep

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------

1.2            Write a method in Java to perform a simple addition of 2 numbers
_____________________________________________________________________________________________________________________________

CODE:-
------
/*Function to accept and add 2 numbers */

import java.util.Scanner;


public class Function
{
   public static int sumcalc(int a,int b)
{                              //method definition
       int c;

       c=a+b;

       System.out.println(a+" + "+b+" = "+c);

       return  c;
    }

    public static void main(String[] args)
 {                                       //main function
       Scanner input=new Scanner(System.in);

       int x,y;

       System.out.println("Enter 2 numbers to perform addition ");

       x= input.nextInt();

       y= input.nextInt();

       sumcalc(x,y);//Method call
    }

    }


Output:-
--------
Enter 2 numbers to perform addition

4

5

4 + 5 = 9

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.3            Wap in Java to make a basic calculator using function
_____________________________________________________________________________________________________________________________

CODE:-
------
import java.util.Scanner;

public class Function
{
   public static int calculation(int a,int b)
{
       int c,d,e,f;

       c=a+b;

       d=a-b;

       e=a*b;

       f=a/b;

       System.out.println(a+" + "+b+" = "+c);

       System.out.println(a+" - "+b+" = "+d);

       System.out.println(a+" * "+b+" = "+e);

       System.out.println(a+" / "+b+" = "+f);

       return 0;
    }

    public static void main(String[] args)
{
       Scanner input=new Scanner(System.in);

       int x,y;

       System.out.println("Enter 2 numbers to perform calculation ");

       x= input.nextInt();

       y= input.nextInt();

       calculation(x,y);//Method call

    }

    }


Output:-
--------
Enter 2 numbers to perform calculation
8
4
8 + 4 = 12
8 - 4 = 4
8 * 4 = 32
8 / 4 = 2

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.4    Write a method in Java to calculate the distance in Hectometer, Decameter, Meter, Decimeter, Centimeter, Millimeter,       Inch, Feet and Gauge if it is entered as in Kilometer
_____________________________________________________________________________________________________________________________
    

CODE:-
------
import java.util.Scanner;
public class Function
{
public static int calculation(int km)
{
       double hm=0,dcm=0,m=0,dm=0,cm=0,mm=0,in=0,ft=0,g=0;

       hm=km*10;

       dcm=hm*10;

       m=dcm*10;

       dm=m*10;

       cm=dm*10;

       mm=cm*10;

       in=cm*2.54;

       ft=in/12;

       g=ft/3;

       System.out.println("Distance in Kilometer: "+km);

       System.out.println("Distance in Hectometer: "+hm);

       System.out.println("Distance in Decameter: "+dcm);

       System.out.println("Distance in Meter: "+m);

       System.out.println("Distance in Decimeter: "+dm);

       System.out.println("Distance in Centimeter: "+cm);

       System.out.println("Distance in Millimeter: "+mm);

       System.out.println("Distance in Inch: "+in);

       System.out.println("Distance in Feet: "+ft);

       System.out.println("Distance in Gauge: "+g);

       return 0;
    }

    public static void main(String[] args) {

       Scanner input=new Scanner(System.in);

       int x;

       System.out.println("Enter a number in Km to convert ");

       x=input.nextInt();

       calculation(x);
    }

    }

Output:-
--------
Enter a number in Km to convert
5

Distance in Kilometer: 5

Distance in Hectometer: 50.0

Distance in Decameter: 500.0

Distance in Meter: 5000.0

Distance in Decimeter: 50000.0

Distance in Centimeter: 500000.0

Distance in Millimeter: 5000000.0

Distance in Inch: 1270000.0

Distance in Feet: 105833.33333333333

Distance in Gauge: 35277.777777777774

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.5                Write a program to create a salary sheet using only method    
____________________________________________________________________________________________________________________________


CODE:-
------
import java.util.Scanner;

public class Function {

   public static int calculation(int basic){

       double da,ta,hra,it,pf,gp,np;

       da=basic*0.45;

       ta=basic*0.30;

       hra=basic*0.20;

       it=basic*0.04;

       pf=basic*0.08;

       gp=da+ta+hra+basic;

       np=gp-it-pf;

       System.out.println("Basic salary is: "+basic);

       System.out.println("D.A(Dearness_Allowance) is: "+da);

       System.out.println("T.A(Travel_Allowance) is: "+ta);

       System.out.println("H.R.A(House_Rent_Allowens) is: "+hra);

       System.out.println("I.T(Income_Tax) is: "+it);

       System.out.println("P.F(Provedent_Fund) is: "+pf);

       System.out.println("G.P(Gross_Pay) is: "+gp);

       System.out.println("N.P(Net_pay) is: "+np);

       return 0;
    }

    public static void main(String[] args) {

       Scanner input=new Scanner(System.in);

        int salary;

        System.out.println("Enter your basic salary ");

        salary= input.nextInt();

        calculation(salary);
    }

    }


Output:-
--------
Enter your basic salary

20000

Basic salary is: 20000

D.A(Dearness_Allowance) is: 9000.0

T.A(Travel_Allowance) is: 6000.0

H.R.A(House_Rent_Allowens) is: 4000.0

I.T(Income_Tax) is: 800.0

P.F(Provedent_Fund) is: 1600.0

G.P(Gross_Pay) is: 39000.0

N.P(Net_pay) is: 36600.0

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.6                Wap to create a method to swap 2 numbers
____________________________________________________________________________________________________________________________

CODE:-
------
import java.util.Scanner;

public class Function
{
   public static int swap(int a,int b)
{
        a=a+b;

        b=a-b;

        a=a-b;

       System.out.println("After Swapping "+"a="+a+","+"b="+b);

       return 0;
    }

    public static void main(String[] args)
{
       Scanner input=new Scanner(System.in);

        int x,y;

        System.out.println("Enter 2 numbers to peform swap ");

        x=input.nextInt();

        y= input.nextInt();

        swap(x,y);
    }

    }



Output:-
--------
Enter 2 numbers

5

4

After Swapping a=4,b=5

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.7                    Write a method in JAVA to reverse a number
____________________________________________________________________________________________________________________________


CODE:-
------
import java.util.Scanner;

public class Function {

   public static int reverse (int n){

       int i,b=0;

       do {

           b=b*10+n%10;

           n/=10;
       }

       while(n!=0);

       System.out.println(" The output is ="+b);

       return 0;
    }

    public static void main(String[] args) {

       Scanner input=new Scanner(System.in);

        int x;

        System.out.println("Enter a number ");

        x= input.nextInt();

        reverse(x);

    }

    }


Output:-
--------
Enter a number

123

The output is = 321

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.8                    Write Method in Java to check password        
____________________________________________________________________________________________________________________________


CODE:-
------
import java.util.Scanner;

public class Function {

   public static int Password (int pass){

        if(pass==75959)
        {
            System.out.println("Entered password matched (Welcome user 587) ");
        }

        else
    {
            System.out.println("incorrect passcode access denied ");
        }

       return 0;
    }

    public static void main(String[] args) {

       Scanner input=new Scanner(System.in);

        int x;

        System.out.println("Enter Your Password to Login  ");

        x= input.nextInt();

        Password(x);
    }

    }

Output:-
--------
Enter Your Password to Login  

75959

Entered password matched (Welcome user 587)

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.9            Write a Method to check voter ability if above 18 give a choice to cast their vote
_____________________________________________________________________________________________________________________________

CODE:-
------
import java.util.Scanner;

public class Function {

   public static int vote (int age){

       Scanner input=new Scanner(System.in);

       int i;

        if(age>=18) {

            System.out.println("You are eligible to vote ");

            int number;

            System.out.println("\nPress 1 to vote TMC ");

            System.out.println("\n Press 2 to vote BJP ");

            System.out.println("\n Press 3 to vote All India Congress ");

            System.out.println("\n Press 4 to vote LEFT");

            System.out.println("\n Press 5 to vote others ");

            System.out.println("\n Enter Your Choice");

            number = input.nextInt();


            switch (number) {

                case 1:

                    System.out.println("Thanks May god bless you :)");

                    break;

                case 2:

                    System.out.println("We are grateful and honoured ;)");

                    break;

                case 3:
                    System.out.println("Faith is the Ultimatum thank You :( ");

                    break;
                case 4:

                    System.out.println("Have a good You may proceed futher ;(");

                    break;

                case 5:

                    System.out.println("Thank you Have a good day ");

                    break;

                default:

                    System.out.println("\n\nYou have entered an invalid option\nPlease try again");
            }
        }

        else {

            System.out.println("Sorry We found you are not eligible!:( ");
        }

       return 0;
    }

    public static void main(String[] args) {

       Scanner input=new Scanner(System.in);

        int x;

        System.out.println(" Welcome to Panchayat elections Enter Your Age to check voter abitlity and proceed further  ");

        x= input.nextInt();

        vote(x);
    }

    }


Output:-
--------
Welcome to Panchayat elections Enter Your Age to check voter abitlity and proceed further  

56

You are eligible to vote

Press 1 to vote TMC

 Press 2 to vote BJP

 Press 3 to vote All India Congress

 Press 4 to vote LEFT

 Press 5 to vote others

Enter Your Choice

1

Thanks May god bless you :)

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.10            Write a Method in Java to check whether a number is an Armstrong number or not     
_____________________________________________________________________________________________________________________________

CODE:-
------
import java.util.Scanner;

public class Function {

   public static int Armstrong (int number){

       int remainder,temp,sum=0;

       temp=number;

       do {
           remainder = temp%10;

           sum += remainder*remainder*remainder;

           temp = temp/10;
       }

       while(temp!=0);

       if ( number == sum )

           System.out.println("Entered Number is an Armstrong Number");

       else

           System.out.println("Entered Number is not an Armstrong Number");

       return 0;
    }

    public static void main(String[] args) {

       Scanner input=new Scanner(System.in);

        int x;

        System.out.println(" Enter a number to check whether the is a Armstrong number or not ");

        x= input.nextInt();

        Armstrong(x);
    }

    }

Output:-
--------
Enter a number to check whether the is a Armstrong number or not

153

Entered Number is an Armstrong Number

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.11                    Write a program to Print Star Pattern
_____________________________________________________________________________________________________________________________


CODE:-
------
import java.util.Scanner;

public class Function {

   public static int Pattern(int number){

       int i,j;

       for(i=0;i<number;i++)

       {

           for(j=0;j<=i;j++)

           {

               System.out.printf("*");

           }

           System.out.println("");
       }

       return 0;
    }

    public static void main(String[] args) {

       Scanner input=new Scanner(System.in);

        int x;

        System.out.println(" Enter the number of rows ");

        x= input.nextInt();

        Pattern(x);
    }

    }

Output:-
--------
Enter the number of rows
5

*
**
***
****
*****

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.12            Write a program to print all natural numbers within range
_____________________________________________________________________________________________________________________________
    
CODE:-
------
import java.util.Scanner;

public class Function {

   public static int Natural(int number){

       int i,j;

       System.out.println("All natural numbers within range ");

      for(i=1;i<=number;i++)

      {

          System.out.println(""+i);

      }

       return 0;

    }

    public static void main(String[] args) {

       Scanner input=new Scanner(System.in);

        int x;

        System.out.println(" Enter the range ");

        x= input.nextInt();

        Natural(x);
    }

    }

Output:-
--------
Enter the range

10

All natural numbers within range
1
2
3
4
5
6
7
8
9
10

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.13            Write a Java program to find out value of a power number without using pow().
_____________________________________________________________________________________________________________________________

    
CODE:-
------
import java.util.Scanner;

public class Function {

   public static int Power(int n,int p){

       int calc=1,i;

        for(i=1;i<=p;i++)
       {
           calc*=n;
       }

       System.out.println(n+" Raised to "+p+" = "+calc);

       return 0;
    }

    public static void main(String[] args) {

       Scanner input=new Scanner(System.in);

        int x,y;

        System.out.println(" Enter the number ");

        x= input.nextInt();

        System.out.println("Enter the Power ");

        Power(x,y);
    }

    }


Output:-
--------

Enter the number
5
Enter the Power
2

5 Raised to 2 = 25

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.14            Write a method in Java to prove the execution and concept of array.    
_____________________________________________________________________________________________________________________________

CODE:-
------
import java.util.Scanner;

public class Function {

   public static int Array(int n){

       Scanner input = new Scanner(System.in);

       int i;

       int[] arr= new int[n];

       System.out.println("Enter the elements of  the array");

       for(i=0;i<n;i++)

       {

           arr[i]=input.nextInt();
       }

       System.out.println("Array elements are ");

       for(i=0;i<n;i++)

       {
           System.out.println(arr[i]);
       }

       return 0;
    }

    public static void main(String[] args) {

       Scanner input=new Scanner(System.in);

        int x;

        System.out.println(" Enter the size of the array ");

        x= input.nextInt();

        Array(x);
    }

    }


Output:-
--------
Enter the size of the array
5
Enter the elements of  the array
3
2
1
7
8
Array elements are
3
2
1
7
8

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.15                Write a method in JAVA to print array elements in reverse
_____________________________________________________________________________________________________________________________

CODE:-
------
import java.util.Scanner;

public class Function {

   public static int ArrayReverse(int n){

       Scanner input = new Scanner(System.in);

       int i;

       int[] arr= new int[n];

       System.out.println("Enter the elements of  the array");

       for(i=0;i<n;i++)

       {

           arr[i]=input.nextInt();
       }

       System.out.println("Array elements in reverse are ");

       for(i=n-1;i>=0;i--)

       {
           System.out.println(arr[i]);
       }

       return 0;
    }

    public static void main(String[] args) {

       Scanner input=new Scanner(System.in);

        int x;

        System.out.println(" Enter the size of the array ");

        x= input.nextInt();

        ArrayReverse(x);
    }

    }


Output:-
--------

Enter the size of the array
2
Enter the elements of  the array
6
3
Array elements in reverse are
3
6

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.16                Write a method in Java to find out the max and min element
_____________________________________________________________________________________________________________________________

CODE:-
------
import java.util.Scanner;

public class Function {

   public static int Array(int n){

       Scanner input = new Scanner(System.in);

       int i;

       int [] arr=new int[n];

       int min=Integer.MAX_VALUE;

       int max=Integer.MIN_VALUE;

       System.out.println("Enter the elements of the array ");

       for(i=0;i<n;i++)

       {

           arr[i]= input.nextInt();

       }

       for(i=0;i<n;i++)

       {

           if(arr[i]<min)

               min=arr[i];

           if(arr[i]>max)

               max=arr[i];
       }

       System.out.println("Max element is "+max);

       System.out.println("Min element is "+min);

       return 0;
   }



    public static void main(String[] args) {

       Scanner input=new Scanner(System.in);

        int x;

        System.out.println(" Enter the size of the array ");

        x= input.nextInt();

        Array(x);
    }

    }


Output:-
--------
Enter the size of the array

5

Enter the elements of the array
2
3
4
5
6

Max element is 6

Min element is 2

Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.17            Write a program in Java to find out the frequency of an element using a method
_____________________________________________________________________________________________________________________________


CODE:-
------
import java.util.Scanner;

public class Function {

   public static int Arrayfrequent(int n){

       Scanner input = new Scanner(System.in);

       int [] num=new int[n];

       int i,count=0;

       System.out.printf("Enter 10 Elements of array");

       for(i=0;i<=n;i++)

       {
           System.out.printf("\n%d => ",i);

           num[i]=input.nextInt();
       }

       System.out.printf("Enter the Element to search ");

       n= input.nextInt();

       for(i=0;i<=n;i++)

       {
           if (num[i]==n)

               count++;

       }

       System.out.printf("\n The Number %d found %d time(s) in the Array",n,count);

       return 0;
   }

    public static void main(String[] args) {

       Scanner input=new Scanner(System.in);

        int x;

        System.out.println(" Enter the size of the array ");

        x= input.nextInt();

        Arrayfrequent(x);
    }

    }

Output:-
--------
"C:\Program Files\Java\jdk-20\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.1.2\lib\idea_rt.jar=57308:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.1.2\bin" -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath C:\Users\hp\IdeaProjects\justforfun\out\production\justforfun Function
Enter the size of the array
5

Enter 10 Elements of array

0 => 2

1 => 2

2 => 3

3 => 4

4 => 5

5 => 6

Enter the Element to search
2

The Number 2 found 2 time(s) in the Array
Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------
1.18            Write a method to print the sum of 2 arrays(Matrix format)
_____________________________________________________________________________________________________________________________

CODE:-
------
import java.util.Scanner;
public class Function {
   public static int Arrayfrequent(int n){
       Scanner sc=new Scanner(System.in);

       int [] a=new int[n];

       int [] b=new int[n];

       int [] c=new int[n];

       int i;

       System.out.printf("\n 1st Array..............\n\n");

       for(i=0;i<n;i++)

       {
           System.out.printf("Enter the Element %d ",i);

           a[i]= sc.nextInt();

       }

       System.out.printf("\n 2nd Array..............\n\n");

       for(i=0;i<n;i++)

       {
           System.out.printf("Enter the Element %d ",i);

           b[i]= sc.nextInt();
       }

       System.out.printf("\n Result Array..............\n\n");

       for(i=0;i<n;i++)

       {

           c[i]=a[i]+b[i];

           System.out.printf(" %d + %d = %d\n",a[i],b[i],c[i]);

       }

       System.out.printf("Press Any Key to Exit");
       return 0;
   }
    public static void main(String[] args) {
       Scanner input=new Scanner(System.in);
        int x;
        System.out.print("Enter the  array size : ");
        x= input.nextInt();
        Arrayfrequent(x);
    }
    }


Output:-
--------
Enter the  array size : 5

 1st Array..............

Enter the Element 0 1
Enter the Element 1 2
Enter the Element 2 3
Enter the Element 3 4
Enter the Element 4 7

 2nd Array..............

Enter the Element 0 5
Enter the Element 1 6
Enter the Element 2 4
Enter the Element 3 1
Enter the Element 4 3

 Result Array..............

 1 + 5 = 6
 2 + 6 = 8
 3 + 4 = 7
 4 + 1 = 5
 7 + 3 = 10
Press Any Key to Exit
Process finished with exit code 0
-----------------------------------------------------------------------------------------------------------------------------

Good bye and happyCoding<____________________________________________________



No comments:

Post a Comment

JAVA PROGRAMMING - OOPS CHAPTER 1

Object-Oriented Programming Chapter 1: Basics by Souradeep Roy Using IntelliJ IDEA Community version:- _____________________________________...