Print a Heart Shape in Java Console with a Single Stream Expression
This article demonstrates how to generate a heart-shaped pattern directly in the Java console using a compact IntStream‑based one‑liner, explaining the mathematical formula and stream operations that produce the visual output without external libraries.
Java developers can create an eye‑catching heart shape in the console using only a single, stream‑driven expression. The technique relies on the classic implicit heart equation (x^2 + y^2 - 1)^3 - x^2 y^3 \le 0, scaled to fit typical console dimensions.
Core Code
IntStream.range(-15, 15)
.map(y -> -y)
.forEach(y -> IntStream.range(-30, 30)
.forEach(x -> System.out.print(
Math.pow(Math.pow(x * 0.05, 2) + Math.pow(y * 0.1, 2) - 1, 3)
- Math.pow(x * 0.05, 2) * Math.pow(y * 0.1, 3) <= 0
? "love".charAt(Math.abs((y - x) % 4))
: " " + (x == 29 ? "
" : "")
)));The outer IntStream.range(-15, 15) iterates over the vertical axis (y). Each y value is negated to align the coordinate system with the console's top‑down layout. For every y, an inner IntStream.range(-30, 30) walks across the horizontal axis (x).
Inside the innermost forEach, the expression evaluates the scaled heart equation. The factors 0.05 for x and 0.1 for y compress the shape so it fits within the typical 60‑column width of a terminal. If the equation yields a value less than or equal to zero, a character from the string "love" is printed; the character index cycles using Math.abs((y - x) % 4) to add visual variety. Otherwise, a space is printed, and when the column reaches the rightmost position ( x == 29), a newline character is appended to start the next row.
Running the program prints a heart made of the letters l, o, v, e that resembles the classic ASCII‑art heart. No external libraries or graphics APIs are required—only the standard Java java.util.stream package.
Usage notes :
The scaling factors can be tweaked to change the heart's size or aspect ratio.
Replacing the string "love" with any other word or symbol customizes the visual pattern.
This approach works with any Java version that supports IntStream (Java 8+).
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
