Java Program to display "Hello World!" (enclosed in double quotes).
Objective
Write a Java program to display "Hello World!" by creating an object of a class and calling its method.
Algorithm / Approach
- Create a class named
Test. - Inside the class, define a method named
display(). - Inside
display(), useSystem.out.print()to print the literal string"Hello World!"including double quotes. - Create the
mainmethod. - Inside
main, instantiate an object of theTestclass:Test t = new Test();. - Call the display method using the object:
t.display();.
Test.java
class Test {
void display() {
System.out.print("\"Hello World!\"");
}
public static void main(String[] a)
{
Test t = new Test();
t.display();
}
}
Expected Output
"Hello World!"
Explanation of the Program
- This program introduces the most basic concept of Object-Oriented Programming (OOP) in Java.
- Instead of writing logic directly inside the
mainmethod, we define a behavior (thedisplaymethod) inside a blueprint (theTestclass). - To use that behavior, we must first create an instance of the class (an object) using the
newkeyword. - To print literal double quotes inside a string, we escape them using a backslash
\".
Complexity
Time Complexity
O(1)
Space Complexity
O(1)