How to find the minimum and maximum number in java

Given java code snippet is to find the minimum and the maximum number from the given array of integers.
public class FindMinAndMax {
    public static void main(String[] args) {
        int[] numbers = { 2, 4, 5, 33, 34, 423 };
        int max = numbers[0];
        int min = numbers[0];
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] < min)
                min = numbers[i];
            else if (numbers[i] > max)
                max = numbers[i];
        }
        System.out.println("Min Number" + "\t" + "Max Number");
        System.out.print(min + "\t\t" + max);

    }
}

Output:


Min Number    Max Number
2                    423

How to search a word inside a string?

Using the inbuilt "indexOf" method, the word inside a String can be found. In the given example I'm trying to find the "Hello" from the String.
public class SearchString{
   public static void main(String[] args) {
   
      String strOrig = "Hello readers";
      int intIndex = strOrig.indexOf("Hello");
      if(intIndex == - 1){
         System.out.println("Hello not found");
      } else {
         System.out.println("Found Hello at index "
         + intIndex);
      }
   }
}

Output:
Found Hello at index 0

Hello World Program

public class SayHello {
   
    public static void main(String args[]) {
        
        System.out.println("Hello World!");
    }
}


Output:

Hello World!

Explanation:

 In Java everything is class and object. We can name our class pretty much what we want, there is no restriction. However, the best programming practice is to start your class name with the upper case and the subsequent word should be the upper case as well so that it will be much more readable.

In order to run and execute any java class we need a main method in it. So, we need to remember the syntax of the "main" method. In order to print something into the console we need a print method and the way we can use is by calling the System class. And, finally into the parenthesis we can type pretty much what we want.

Please share your thoughts if you have any questions.

Java code to print Asterisk Pyramid

Below java code snippet will print the asterisk(*) pyramid(triangle) of 5 lines.


public class PrintPyramidStar {

    public static void main(String args[]) {

        int c = 1;
        for (int i = 1; i <= 5; i++) {
            for (int j = i; j < 5; j++) {
                System.out.print(" ");
            }
            for (int k = 1; k <= c; k++) {
                if (k % 2 == 0)
                    System.out.print(" ");
                else
                    System.out.print("*");
            }
            System.out.println();
            c += 2;
        }
    }
}


Output:

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

You may also like
Diamond Pattern