Java Method - Programming Examples

  1. How to overload methods?



    Solution:

    This example displays the way of overloading a method depending on type and number of parameters.



    class MyClass {
       int height;
       MyClass() {
          System.out.println("bricks");
          height = 0;
       }
       MyClass(int i) {
          System.out.println("Building new House that is "
          + i + " feet tall");
          height = i;
       }
       void info() {
          System.out.println("House is " + height
          + " feet tall");
       }
       void info(String s) {
          System.out.println(s + ": House is "
          + height + " feet tall");
       }
    }
    public class MainClass {
       public static void main(String[] args) {
          MyClass t = new MyClass(0);
          t.info();
          t.info("overloaded method");
          //Overloaded constructor:
          new MyClass();
       }
    }
    The above code sample will produce the following result.



    Building new House that is 0 feet tall.
    House is 0 feet tall.
    Overloaded method: House  is 0 feet tall.
    bricks
  2. How to use method overloading for printing different types of array?



    Solution:

    This example displays the way of using overloaded method for printing types of array (integer, double and character).



    public class MainClass {
       public static void printArray(Integer[] inputArray) {
          for (Integer element : inputArray){
             System.out.printf("%s ", element);
             System.out.println();
          }
       }
       public static void printArray(Double[] inputArray) {
          for (Double element : inputArray){
             System.out.printf("%s ", element);
             System.out.println();
          }
       }
       public static void printArray(Character[] inputArray) {
          for (Character element : inputArray){
             System.out.printf("%s ", element);
             System.out.println();
          }
       }
       public static void main(String args[]) {
          Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
          Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4,
          5.5, 6.6, 7.7 };
          Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };
          System.out.println("Array integerArray contains:");
          printArray(integerArray);
          System.out.println("\nArray doubleArray contains:");
          printArray(doubleArray);
          System.out.println("\nArray characterArray contains:");
          printArray(characterArray);
       }
    }

    Result:

    The above code sample will produce the following result.



    Array integerArray contains:
    1 
    2 
    3 
    4 
    5 
    6 
    
    Array doubleArray contains:
    1.1 
    2.2 
    3.3 
    4.4 
    5.5 
    6.6 
    7.7 
    
    Array characterArray contains:
    H 
    E 
    L 
    L 
    O 
  3. How to use method for solving Tower of Hanoi problem?
    This example displays the way of using method for solving Tower of Hanoi problem( for 3 disks).



    public class MainClass {
       public static void main(String[] args) {
          int nDisks = 3;
          doTowers(nDisks, 'A', 'B', 'C');
       }
       public static void doTowers(int topN, char from,
       char inter, char to) {
          if (topN == 1){
             System.out.println("Disk 1 from "
             + from + " to " + to);
          }else {
             doTowers(topN - 1, from, to, inter);
             System.out.println("Disk "
             + topN + " from " + from + " to " + to);
             doTowers(topN - 1, inter, from, to);
          }
       }
    }

    Result:

    The above code sample will produce the following result.



    Disk 1 from A to C
    Disk 2 from A to B
    Disk 1 from C to B
    Disk 3 from A to C
    Disk 1 from B to A
    Disk 2 from B to C
    Disk 1 from A to C
  4. How to use method for calculating Fibonacci series?

    This example shows the way of using method for calculating Fibonacci Series upto n numbers.



    public class MainClass {
       public static long fibonacci(long number) {
          if ((number == 0) || (number == 1))
             return number;
          else
             return fibonacci(number - 1) + fibonacci(number - 2);
       }
       public static void main(String[] args) {
          for (int counter = 0; counter <= 10; counter++){
             System.out.printf("Fibonacci of %d is: %d\n",
             counter, fibonacci(counter));
          }
       }
    }

    Result:

    The above code sample will produce the following result.



    Fibonacci of 0 is: 0
    Fibonacci of 1 is: 1
    Fibonacci of 2 is: 1
    Fibonacci of 3 is: 2
    Fibonacci of 4 is: 3
    Fibonacci of 5 is: 5
    Fibonacci of 6 is: 8
    Fibonacci of 7 is: 13
    Fibonacci of 8 is: 21
    Fibonacci of 9 is: 34
    Fibonacci of 10 is: 55
  5. How to use method for calculating Factorial of a number?
    This example shows the way of using method for calculating Factorial of 9(nine) numbers.



    public class MainClass {
       public static void main(String args[]) {
          for (int counter = 0; counter <= 10; counter++){
             System.out.printf("%d! = %d\n", counter,
             factorial(counter));
          }
       }
       public static long factorial(long number) {
          if (number <= 1)
             return 1;
          else
             return number * factorial(number - 1);
       }
    }

    Result:

    The above code sample will produce the following result.



    0! = 1
    1! = 1
    2! = 2
    3! = 6
    4! = 24
    5! = 120
    6! = 720
    7! = 5040
    8! = 40320
    9! = 362880
    10! = 3628800
  6. How to use method overriding in Inheritance for subclasses?
    This example demonstrates the way of method overriding by subclasses with different number and type of parameters.



    public class Findareas{
       public static void main (String []agrs){
          Figure f= new Figure(10 , 10);
          Rectangle r= new Rectangle(9 , 5);
          Figure figref;
          figref=f;
          System.out.println("Area is :"+figref.area());
          figref=r;
          System.out.println("Area is :"+figref.area());
       }
    }
    class Figure{
       double dim1;
       double dim2;
       Figure(double a , double b) {
          dim1=a;
          dim2=b;
       }
       Double area() {
          System.out.println("Inside area for figure.");
          return(dim1*dim2);
       }
    }
    class Rectangle extends Figure {
       Rectangle(double a, double b) {
          super(a ,b);
       }
       Double area() {
          System.out.println("Inside area for rectangle.");
          return(dim1*dim2);
       }
    }

    Result:

    The above code sample will produce the following result.



    Inside area for figure.
    Area is :100.0
    Inside area for rectangle.
    Area is :45.0


  7. How to display Object class using instanceOf keyword?
    This example makes displayObjectClass() method to display the Class of the Object that is passed in this method as an argument.



    import java.util.ArrayList;
    import java.util.Vector;
    
    public class Main {
    
    public static void main(String[] args) {
       Object testObject = new ArrayList();
          displayObjectClass(testObject);
       }
       public static void displayObjectClass(Object o) {
          if (o instanceof Vector)
          System.out.println("Object was an instance 
          of the class java.util.Vector");
          else if (o instanceof ArrayList)
          System.out.println("Object was an instance of 
          the class java.util.ArrayList");
          else
          System.out.println("Object was an instance of the " 
          + o.getClass());
       }
    }

    Result:

    The above code sample will produce the following result.



    Object was an instance of the class java.util.ArrayList
  8. How to use break to jump out of a loop in a method?
    This example uses the 'break' to jump out of the loop.



    public class Main {
       public static void main(String[] args) {
          int[] intary = { 99,12,22,34,45,67,5678,8990 };
          int no = 5678;
          int i = 0;
          boolean found = false;
          for ( ; i < intary.length; i++) {
             if (intary[i] == no) {
                found = true;
                break;
             }
          }
          if (found) {
             System.out.println("Found the no: " + no 
             + " at  index: " + i);
          } 
          else {
             System.out.println(no + "not found  in the array");
          }
       }
    }

    Result:

    The above code sample will produce the following result.



    Found the no: 5678 at  index: 6
  9. How to use continue in a method?
    This example uses continue statement to jump out of a loop in a method.



    public class Main {
       public static void main(String[] args) {
          StringBuffer searchstr = new StringBuffer(
          "hello how are you. ");
          int length = searchstr.length();
          int count = 0;
          for (int i = 0; i < length; i++) {
             if (searchstr.charAt(i) != 'h')
             continue;
             count++;
             searchstr.setCharAt(i, 'h');
          }
          System.out.println("Found " + count 
          + " h's in the string.");
          System.out.println(searchstr);
       }
    }

    Result:

    The above code sample will produce the following result.



    Found 2 h's in the string.
    hello how are you. 
  10. How to use Label in a method?(pleasse not use this ;)       

    This example shows how to jump to a particular label when break or continue statements occour in a loop.



    public class Main {
       public static void main(String[] args) {
          String strSearch = "This is the string in which you 
          have to search for a substring.";
          String substring = "substring";
          boolean found = false;
          int max = strSearch.length() - substring.length();
          testlbl:
          for (int i = 0; i < = max; i++) {
             int length = substring.length();
             int j = i;
             int k = 0;
             while (length-- != 0) {
                if(strSearch.charAt(j++) != substring.charAt(k++){
                   continue testlbl;
                }
             }
             found = true;
             break testlbl;
          }
          if (found) {
             System.out.println("Found the substring .");
          }
          else {
             System.out.println("did not find the 
             substing in the string.");
          }
       }
    }

    Result:

    The above code sample will produce the following result.



    Found the substring .
     
  11. This example displays how to check which enum member is selected using Switch statements.

    enum Car {
       lamborghini,tata,audi,fiat,honda
    }
    public class Main {
       public static void main(String args[]){
          Car c;
          c = Car.tata;
          switch(c) {
             case lamborghini:
             System.out.println("You choose lamborghini!");
             break;
             case tata:
             System.out.println("You choose tata!");
             break;
             case audi:
             System.out.println("You choose audi!");
             break;
             case fiat:
             System.out.println("You choose fiat!");
             break;
             case honda:
             System.out.println("You choose honda!");
             break;
             default:
             System.out.println("I don't know your car.");
             break;
          }
       }
    }

    Result:

    The above code sample will produce the following result.

    You choose tata!

  12. How to make enum constructor, instance variable & method?
    This example initializes enum using a costructor &; getPrice() method & display values of enums.



    enum Car {
       lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
       private int price;
       Car(int p) {
          price = p;
       }
       int getPrice() {
          return price;
       } 
    }
    public class Main {
       public static void main(String args[]){
          System.out.println("All car prices:");
          for (Car c : Car.values())
          System.out.println(c + " costs " 
          + c.getPrice() + " thousand dollars.");
       }
    }

    Result:

    The above code sample will produce the following result.



    All car prices:
    lamborghini costs 900 thousand dollars.
    tata costs 2 thousand dollars.
    audi costs 50 thousand dollars.
    fiat costs 15 thousand dollars.
    honda costs 12 thousand dollars.

  13. How to use for and foreach loop for printing values of an array ?
This example displays an integer array using for loop & foreach loops.
public class Main {
   public static void main(String[] args) {
      int[] intary = { 1,2,3,4};
      forDisplay(intary);
      foreachDisplay(intary);
   }
   public static void forDisplay(int[] a){  
      System.out.println("Display an array using for loop");
      for (int i = 0; i < a.length; i++) {
         System.out.print(a[i] + " ");
      }
      System.out.println();
   }
   public static void foreachDisplay(int[] data){
      System.out.println("Display an array using for 
      each loop");
      for (int a  : data) {
         System.out.print(a+ " ");
      }
   }
}

Result:

The above code sample will produce the following result.
Display an array using for loop
1 2 3 4 
Display an array using for each loop
1 2 3 4 
  1. How to make a method take variable lentgth argument as an input?
This example creates sumvarargs() method which takes variable no of int numbers as an argument and returns the sum of these arguments as an output.
public class Main {
   static int  sumvarargs(int... intArrays){
      int sum, i;
      sum=0;
      for(i=0; i< intArrays.length; i++) {
         sum += intArrays[i];
      }
      return(sum);
   }
   public static void main(String args[]){
      int sum=0;
      sum = sumvarargs(new int[]{10,12,33});
      System.out.println("The sum of the numbers is: " + sum);
   }
}

Result:

The above code sample will produce the following result.
The sum of the numbers is: 55
  1. How to use variable arguments as an input when dealing with method overloading?

    This example displays how to overload methods which have variable arguments as an input.
    public class Main {
       static void vaTest(int ... no) {
          System.out.print("vaTest(int ...): " 
          + "Number of args: " + no.length +" Contents: ");
          for(int n : no)
          System.out.print(n + " ");
          System.out.println();
       }
       static void vaTest(boolean ... bl) {
          System.out.print("vaTest(boolean ...) " +
          "Number of args: " + bl.length + " Contents: ");
          for(boolean b : bl)
          System.out.print(b + " ");
          System.out.println();
       }
       static void vaTest(String msg, int ... no) {
          System.out.print("vaTest(String, int ...): " +
          msg +"no. of arguments: "+ no.length +" Contents: ");
          for(int  n : no)
          System.out.print(n + " ");
          System.out.println();
       }
       public static void main(String args[]){
          vaTest(1, 2, 3);
          vaTest("Testing: ", 10, 20);
          vaTest(true, false, false);
       }
    }

    Result:

    The above code sample will produce the following result.
    vaTest(int ...): Number of args: 3 Contents: 1 2 3 
    vaTest(String, int ...): Testing: no. of arguments: 2 
    Contents: 10 20 
    vaTest(boolean ...) Number of args: 3 Contents: 
    true false false 

QUARKUS & GraphQL

 QUARKUS & GraphQL https://www.geeksforgeeks.org/graphql-tutorial/ https://quarkus.io/guides/smallrye-graphql-client https://www.mastert...