To print “I love you” in Java, create a class with a main method and print the message with System.out.println. Here is a complete program:
public class Main {
public static void main(String[] args) {
System.out.println("I love you");
}
}
Compile and run it
Save the code in a file named Main.java. Then, from a terminal in the same folder, compile and run it:
javac Main.java
java Main
The output is:
I love you
What each part does
public class Maindeclares a class. Java requires every program to sit inside a class. The file name must match the public class name, so the file isMain.java.public static void main(String[] args)is the starting point. The JVM calls this method first when you run the program, so its spelling and parameter list must match exactly.System.out.println("I love you");prints the text and then moves to a new line. UseSystem.out.printif you don’t want a line break.javaccompiles the source file intoMain.class, which holds bytecode.java Mainruns that compiled class.
Each statement ends with a semicolon.
Store the message in a variable
If you want to reuse the message, store it in a String variable:
public class Main {
public static void main(String[] args) {
String message = "I love you";
System.out.println(message);
}
}
String starts with a capital letter because it is a class from the Java library, not a basic type.
Print the message more than once
A for loop repeats the print statement. This version prints the message three times:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println("I love you");
}
}
}
The same message in C++
For comparison, here is the C++ version:
#include <iostream>
int main() {
std::cout << "I love you" << std::endl;
return 0;
}
C++ needs an #include line for input and output, and its main function does not belong to a class. std::cout with << does the job that System.out.println does in Java. For the C++ side of the same task, see how to write “I love you” in C++.
Common mistakes
- File name mismatch. If the public class is
Mainbut the file is namedhello.java,javacreports an error. The class and file names must match. - Missing semicolon. A missing semicolon stops compilation, and the compiler points to the line where it expects one.
- Single quotes.
'I love you'is an error. Single quotes hold one character (achar), so text goes in double quotes. - Wrong capitalization. Java is case-sensitive, so
system.out.printlnandstringdon’t work. - Running before compiling. Running
java Mainbeforejavac Main.javafails, because the compiledMain.classfile doesn’t exist yet.