Write a java program to return a time in hh:mm:ss format?

Question:
How to write a java program to return a time in hh:mm:ss format?

Answer:
Format formatter = new SimpleDateFormat( "hh:mm:ss" );

Code:
import java.text.Format ;
import java.text.SimpleDateFormat ;
import java.util.Date ;
 
public class PrintTime {
  public static void main( String[] args ) {
    Format formatter = new SimpleDateFormat( "hh:mm:ss" );
    System.out.println( formatter.format( new Date() ) );
    }
}

Output:
$ java PrintTime
09:10:12

How to compare two ints in java?

Question:
The user is asked to enter two positive integers. The program prints them in ascending order or states that they are equal.

Code:
import java.util.Scanner;
 
public class CompareInts {
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
 
    System.out.print("Enter 1st number: ");
    int i1 = sc.nextInt();
 
    System.out.print("Enter 2nd number: ");
    int i2 = sc.nextInt();
 
    if (i1 == i2) {
      System.out.println("Equal");
    } else if (i1 < i2) {
      System.out.println(i1 + " " + i2);
    } else {
      System.out.println(i2 + " " + i1);
    }
 
  }
} 
 

Output:
$ java CompareInts
Enter 1st number: 3
Enter 2nd number: 1
1 3

Java connect four game

Question:
Connect four game in java.

Code:
import java.util.Scanner;
 
public class ConnectFour {
 
  public static String[][] createPattern() {
 
    String[][] f = new String[7][15];
 
    for (int i =0;i<f.length;i++) {
 
       for (int j =0;j<f[i].length;j++) {
        if (j% 2 == 0){
           f[i][j] ="|";
        } else {
           f[i][j] = " ";
        }
 
        if (i==6) f[i][j]= "-";
      }
 
    }
    return f;
  }
 
  public static void printPattern(String[][] f) {
    for (int i =0;i<f.length;i++) {
      for (int j=0;j<f[i].length;j++) {
        System.out.print(f[i][j]);
      }
      System.out.println();
    }
  }
 
  public static void dropRedPattern(String[][] f) {
    System.out.print("Drop a red disk at column (0–6): ");
    Scanner scan = new Scanner (System.in);
    int c = 2*scan.nextInt()+1;
    for (int i =5;i>=0;i--) {
      if (f[i][c] == " ") {
        f[i][c] = "R";
        break;
      }
    }
  }
 
  public static void dropBlackPattern(String[][] f) {
    System.out.print("Drop a black disk at column (0–6): ");
    Scanner scan = new Scanner (System.in);
    int c = 2*scan.nextInt()+1;
    for (int i =5;i>=0;i--) {
      if (f[i][c] == " ") {
        f[i][c] = "B";
        break;
      }
    }
  }
 
 
  public static String checkWinner(String[][] f) {
    for (int i =0;i<6;i++) {
      for (int j=0;j<7;j+=2) {
        if ((f[i][j+1] != " ")
        && (f[i][j+3] != " ")
        && (f[i][j+5] != " ")
        && (f[i][j+7] != " ")
        && ((f[i][j+1] == f[i][j+3])
        && (f[i][j+3] == f[i][j+5])
        && (f[i][j+5] == f[i][j+7])))
 
          return f[i][j+1]; 
      }
    }
 
    for (int i=1;i<15;i+=2) {
      for (int j =0;j<3;j++) {
            if((f[j][i] != " ")
            && (f[j+1][i] != " ")
            && (f[j+2][i] != " ")
            && (f[j+3][i] != " ")
            && ((f[j][i] == f[j+1][i])
            && (f[j+1][i] == f[j+2][i])
            && (f[j+2][i] == f[j+3][i])))
              return f[j][i]; 
      } 
    }
 
    for (int i=0;i<3;i++) {
 
      for (int j=1;j<9;j+=2) {
            if((f[i][j] != " ")
            && (f[i+1][j+2] != " ")
            && (f[i+2][j+4] != " ")
            && (f[i+3][j+6] != " ")
            && ((f[i][j] == f[i+1][j+2])
            && (f[i+1][j+2] == f[i+2][j+4])
            && (f[i+2][j+4] == f[i+3][j+6])))
              return f[i][j]; 
      } 
    }
 
    for (int i=0;i<3;i++) {
      for (int j=7;j<15;j+=2) {
            if((f[i][j] != " ")
            && (f[i+1][j-2] != " ")
            && (f[i+2][j-4] != " ")
            && (f[i+3][j-6] != " ")
            && ((f[i][j] == f[i+1][j-2])
            && (f[i+1][j-2] == f[i+2][j-4])
            && (f[i+2][j-4] == f[i+3][j-6])))
              return f[i][j]; 
      } 
    }
 
    return null;
  }
 
  public static void main (String[] args) {
    String[][] f = createPattern();
    boolean loop = true;
    int count = 0;
    printPattern(f);
    while(loop) {
      if (count % 2 == 0) dropRedPattern(f);
      else dropBlackPattern(f);
      count++;
      printPattern(f);
      if (checkWinner(f) != null) {
        if (checkWinner(f) == "R"){
           System.out.println("Red won.");
        } else if (checkWinner(f)== "B") {
          System.out.println("Black won.");
        }
        loop = false;
      }
    }
  }
}

Output:
$ java ConnectFour
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
---------------
Drop a red disk at column (0–6): 1
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| |R| | | | | |
---------------
Drop a black disk at column (0–6): 0
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|B|R| | | | | |
---------------
Drop a red disk at column (0–6): 1
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| |R| | | | | |
|B|R| | | | | |
---------------
Drop a black disk at column (0–6): 2
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| |R| | | | | |
|B|R|B| | | | |
---------------
Drop a red disk at column (0–6): 1
| | | | | | | |
| | | | | | | |
| | | | | | | |
| |R| | | | | |
| |R| | | | | |
|B|R|B| | | | |
---------------
Drop a black disk at column (0–6): 6
| | | | | | | |
| | | | | | | |
| | | | | | | |
| |R| | | | | |
| |R| | | | | |
|B|R|B| | | |B|
---------------
Drop a red disk at column (0–6): 1
| | | | | | | |
| | | | | | | |
| |R| | | | | |
| |R| | | | | |
| |R| | | | | |
|B|R|B| | | |B|
---------------
Red won.

How to test if two words are anagram using a StringBuilder in java?

Question:
How to test if two words are anagram using a StringBuilder?

Code:
import java.util.Scanner;
 
public class Anagram {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter first word: ");
    String word1 = sc.nextLine();
    System.out.print("Enter second word: ");
    String word2 = sc.nextLine();
 
    System.out.println("Anagram: " + isAnagram(word1,word2));
 
   }
 
 
  // Test if two words are Anagram using StringBuilder
  public static boolean isAnagram(String word1, String word2) {
 
    word1 = word1.toLowerCase();
    word2 = word2.toLowerCase();
 
    char[] characters = word1.toCharArray();
    StringBuilder sb = new StringBuilder(word2);
    for (char ch : characters) {
      int index = sb.indexOf("" + ch);
      if (index != -1) {
         sb.deleteCharAt(index);
      } else {
         return false;
      }
    }
    return sb.length() == 0 ? true : false;
  }
}

Output:
$ java Anagram
Enter first word: Star
Enter second word: rats
Anagram: true

$ java Anagram
Enter first word: rate
Enter second word: tree
Anagram: false

How to test if two words are anagram using Arrays.sort()?

Question:
How to test if two words are anagram using Arrays.sort()?

Code:
import java.util.*;
 
public class Anagram {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter first word: ");
    String word1 = sc.nextLine();
    System.out.print("Enter second word: ");
    String word2 = sc.nextLine();
 
    System.out.println("Anagram: " + isAnagram(word1,word2));
 
   }
 
 
  // Test if two words are Anagram using Arrays.sort()
  public static boolean isAnagram(String word1, String word2) {
 
    word1 = word1.toLowerCase();
    word2 = word2.toLowerCase();
 
    char[] char1 = word1.toCharArray();
    char[] char2 = word2.toCharArray();
 
    Arrays.sort(char1);
    Arrays.sort(char2);
 
    return Arrays.equals(char1, char2);
  }
}
 

Output:
$ java Anagram
Enter first word: Angel
Enter second word: Glean
Anagram: true

$ java Anagram
Enter first word: bob
Enter second word: bobby
Anagram: false

Java: How to test if two Strings (words) are anagram using a Character Array?

Question:
How to test if two words are anagram using Arrays.sort()?

Code:
import java.util.Scanner;
 
public class Anagram {
 
  public static void main(String[] args) {
 
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter first word: ");
    String word1 = sc.nextLine();
    System.out.print("Enter second word: ");
    String word2 = sc.nextLine();
 
    System.out.println("Anagram: " + isAnagram(word1,word2));
 
   }
 
 
  // Test if two words are Anagram using Character Array
  public static boolean isAnagram(String word1, String word2) {
 
    word1 = word1.toLowerCase();
    word2 = word2.toLowerCase();
 
    if (word1.length() != word2.length()) {
      return false;
    }
 
    char[] chars = word1.toCharArray();
    for (char c : chars) {
      int index = word2.indexOf(c);
      if (index != -1) {
        word2 = word2.substring(0, index) + word2.substring(index + 1, word2.length());
      } else {
        return false;
      }
    }
    return word2.isEmpty();
  }
}

Output:
$ java Anagram
Enter first word: Star
Enter second word: rats
Anagram: true

$ java Anagram
Enter first word: rate
Enter second word: tree
Anagram: false

Converting a double to long in java.

Question:
How to convert a double to long in java?

Answer:
1) Casting
2) Math.round()
3) Double.longValue()

Code:
public class Example {
 
  public static void main(String args[]){
    double d1 = 1234.56;
    System.out.println("d1: " + d1);
 
    // Casting
    long l1 = (long)d1;
 
    // Rounding
    long l2 = Math.round(d1);
    System.out.println("l1: " + l1);
    System.out.println("l2: " + l2);
 
    // Double.longValue()
    Double d2 = new Double(d1);
    long l3 = d2.longValue();
    System.out.println("l3: " + l3);
  }
}

Output:
$ java Example
d1: 1234.56
l1: 1234
l2: 1235
l3: 1234

Why does 1.0/0.0 not throw a java.lang.ArithmeticException: / by zero?

Question:
Why does 1.0/0.0 not throw a java.lang.ArithmeticException: / by zero?

Answer:
Floating point data types have a special value reserved to represent infinity, integer values do not.

The code 1/0 is an integer division fails. However, 1/0.0 is a floating point division and so results in Infinity.

Code:
public class Example {
 
  public static void main(String args[]){
    System.out.println("1.0 / 0.0 == " + 1.0/0.0);
  }
}

Output:
$ java Example
1.0 / 0.0 == Infinity

Is Double.MIN_VALUE greater then zero?

Question:
Is the value of Double.MIN_VALUE greater then, less then, or equal to zero?

Answer:
Greater than.

Double.MIN_VALUE is a constant holding the smallest positive nonzero value of type double, 2-1074.

Code:
public class Example {
 
  public static void main(String args[]){
    System.out.println("Double.MIN_VALUE: " +  Double.MIN_VALUE);
 
    if(Double.MIN_VALUE > 0) {
      System.out.println("Double.MIN_VALUE greater than 0");
    } else if (Double.MIN_VALUE < 0) {
      System.out.println("Double.MIN_VALUE less than 0");
    }
 
  }
}

Output:
$ java Example
Double.MIN_VALUE: 4.9E-324
Double.MIN_VALUE greater than 0

In java what does NaN mean?

Question:
What does NaN mean in java?

Answer:
Not A Number

Here are a few examples on how to generate (trigger) a NaN:

Code:
public class NaN {
  public static void main(String[] args) {
 
    Double d1 = 0d/0d;
    System.out.println("d1: "  + d1);
 
    Double d2 = Double.POSITIVE_INFINITY / Double.POSITIVE_INFINITY;
    System.out.println("d2: "  + d2);
 
    Double d3 = 0d *  Double.POSITIVE_INFINITY;
    System.out.println("d3: "  + d3);
 
    Double d4 = Math.pow(1, Double.POSITIVE_INFINITY);
    System.out.println("d4: "  + d4);
 
    Double d5 = Double.POSITIVE_INFINITY + Double.NEGATIVE_INFINITY;
    System.out.println("d5: "  + d5);
 
    Float f1 = Float.POSITIVE_INFINITY - Float.POSITIVE_INFINITY;
    System.out.println("f1: "  + f1);
 
  }
}

Output:
$ java NaN
d1: NaN
d2: NaN
d3: NaN
d4: NaN
d5: NaN
f1: NaN

If else statement using one line.

Question:
How to write this if else statement in 1 line?
    if(i1==i2){
      b1 = true;
    } else {
      b1 = false;
    }

Answer:
Using the ternary operator.
  result = condition ? value1 : value2; 

Code:
public class Example {
  public static void main(String args[]){
 
    int i1=0;
    int i2=1;
    boolean b1;
    boolean b2;
 
    if(i1==i2){
      b1 = true;
    } else {
      b1 = false;
    }
    System.out.println("b1:" + b1);
 
    // one liner 
    b2= ( (i1==i2) ? true : false );
    System.out.println("b2:" + b2);
 
  }
}

Output:
$ java Example
b1:false
b2:false

Using this() with a Constructor

Question:
How to use the keyword this in a constructor?

Answer:
From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation.

Code:
public class MyClass {
 
  int a=0;
  int b=0;
 
  MyClass(){
    this(5,8);
  }
 
  MyClass(int a, int b){
    this.a = a;
    this.b = b;
  }
 
  public static void main(String[] args) {
    MyClass mc = new MyClass();
    System.out.println("mc.a: " + mc.a);
    System.out.println("mc.b: " + mc.b);
  }
 
}

Output:
$ java MyClass
mc.a: 5
mc.b: 8

How to find common elements between two arrays in java?

Question:
How to find common elements in two different arrays?

Code:
public class CommonElements {
 
  public static void main(String a[]){
    int[] arr1 = {2,4,6,8};
    int[] arr2 = {1,2,3,4,5,6,7,8,9};
 
    for(int i=0;i<arr1.length;i++){
      for(int j=0;j<arr2.length;j++){
        if(arr1[i]==arr2[j]){
          System.out.println(arr1[i]);
        }
      }
    }
 
  }
}

Output:
$ java CommonElements
2
4
6
8

Java prime number menu driven program

Question:
Part I:

An integer is prime if it is only divisible by 1 and itself. For example, 7 is prime, but 9 is not (since it is divisible by 3). Write a method that determines if a given integer is prime. Call it isPrime. It should return a boolean value.

Note: The Java % operator is useful for determining divisibility.

Part II:

Create a menu-driven program.

Let the user choose whether they want to display a list of prime numbers or non-prime numbers. They should enter 1 for prime, 2 for non-prime and 3 to Quit.

Then ask the user how many numbers they want to display. Store this in numValues.

If the user chose to display prime numbers, display the first numValues prime numbers as a comma separated list. (For example, if the user enters 5, display "2, 3, 5, 7, 11".)

If the user chose to display non-prime numbers, display the first numValues non-prime numbers as a comma separated list. (For example, if the user enters 5, display "4, 6, 8, 9, 10".)

You should use a loop that calls the isPrime method.

Code:
import java.util.Scanner;
 
public class PrimeNumber {
 
   public static void main(String args[]) {
     Scanner sc = new Scanner(System.in);
 
     int choice=0;
     int numValues=0;
 
     while(choice != 3){
 
       System.out.println("1 : Prime ");
       System.out.println("2 : Non Prime ");
       System.out.println("3 : Quit");
       System.out.print("Enter choice: ");
       choice= sc.nextInt();
 
       if(choice != 3){
         System.out.print("Enter count: ");
         numValues = sc.nextInt();
 
         if(choice==1){
           for(int i=2,count=1;count<=numValues;i++){
             if(isPrime(i)){
               System.out.print(i);
               if(count<numValues){
                 System.out.print(", ");
               }
               count=count +1;
             }
           }
         }
 
         if(choice==2){
           for(int i=2,count=1;count<=numValues;i++){
             if(! isPrime(i)){
               System.out.print(i);
               if(count<numValues){
                 System.out.print(", ");
               }
               count=count +1;
             }
           }
         }
 
         System.out.println();
       }
     }
   }
 
   public static boolean isPrime(int x) {
      for(int i=2; i<x; i++) {
         if(x % i == 0) {
            return false; 
         }
      }
      return true; 
   }
}

Output:
$ java PrimeNumber
1 : Prime 
2 : Non Prime 
3 : Quit
Enter choice: 1
Enter count: 5
2, 3, 5, 7, 11
1 : Prime 
2 : Non Prime 
3 : Quit
Enter choice: 2
Enter count: 5
4, 6, 8, 9, 10
1 : Prime 
2 : Non Prime 
3 : Quit
Enter choice: 3