Easy Tutorial
❮ Java Applet Basics Java Arraylist ❯

Java Example – Printing a Diamond

Java Examples

Output a diamond with a specified number of lines.

Example

public class Diamond {
    public static void main(String[] args) {
        print(8); // Output an 8-line diamond
    }

    public static void print(int size) {
        if (size % 2 == 0) {
            size++; // Calculate the size of the diamond
        }
        for (int i = 0; i < size / 2 + 1; i++) {
            for (int j = size / 2 + 1; j > i + 1; j--) {
                System.out.print(" "); // Output the blank space at the upper left corner
            }
            for (int j = 0; j < 2 * i + 1; j++) {
                System.out.print("*"); // Output the upper half edge of the diamond
            }
            System.out.println(); // New line
        }
        for (int i = size / 2 + 1; i < size; i++) {
            for (int j = 0; j < i - size / 2; j++) {
                System.out.print(" "); // Output the blank space at the lower left corner
            }
            for (int j = 0; j < 2 * size - 1 - 2 * i; j++) {
                System.out.print("*"); // Output the lower half edge of the diamond
            }
            System.out.println(); // New line
        }
    }
}

Output result:

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

Java Examples

❮ Java Applet Basics Java Arraylist ❯