In this Java program, we will learn how to print a semicolon (;) without using a semicolon anywhere in the program.
This is a common Java programming puzzle and interview question that demonstrates how Java expressions can be used inside control statements.
Java Program
public class PrintSemicolon {
public static void main(String[] args) {
if (System.out.printf("%c", 59) != null) {
}
}
}
Output
;
Explanation
The ASCII value of the semicolon character (;) is 59.
; → ASCII value = 59
We use the following statement:
System.out.printf("%c", 59)
The %c format specifier tells printf() to print the value as a character. Therefore, 59 is printed as the semicolon character.
The interesting part is that we don’t write the printf() call as a normal statement. Instead, we place it inside an if condition:
if (System.out.printf("%c", 59) != null) {
}
An if condition is an expression and does not require a semicolon at the end. printf() returns a PrintStream object, so its result can be compared with null.
As a result, the semicolon is printed without using a semicolon to terminate the statement.
Key Points
- The ASCII value of
;is 59. %cis used to print a character.System.out.printf()returns aPrintStreamobject.- The
printf()call is placed inside anifcondition. - The program contains no semicolon character (
;) in the source code.
Note: This is a programming puzzle rather than a recommended coding practice. In normal Java programs, semicolons should be used wherever the Java syntax requires them.