
Welcome to Java! is the very first problem in HackerRank's Java track. The code is two lines long, but it is worth reading the explanation below if you are new to Java, because the same structure (a class, a main method and System.out) is in every Java program you will write.
Problem
The editor gives you a class called Solution with a main method. Complete it so that it prints exactly two lines:
Hello, World.
Hello, Java.
There is no input for this challenge.
Solution in Java
public class Solution {
public static void main(String[] args) {
System.out.println("Hello, World.");
System.out.println("Hello, Java.");
}
}
What each part means
public class Solutiondeclares a class. In Java all code lives inside a class. If a class is public, the file must have the same name, so this one goes inSolution.java.public static void main(String[] args)is where the program starts.publiclets the JVM call it,staticmeans it can run without creating an object,voidmeans it returns nothing, andargsholds any command-line arguments.System.out.println(...)prints the text and then moves to a new line.System.out.print(...)prints without the new line, so the two messages would end up on the same line.
Running it on your own computer
javac Solution.java
java Solution
The first command compiles the source into Solution.class (bytecode), and the second runs it on the JVM. On Java 11 and later you can also run a single file directly with java Solution.java.
Why submissions fail on this problem
It sounds silly, but plenty of first attempts get a wrong answer here. HackerRank compares your output character by character, so check these:
- The full stops at the end of both lines. "Hello, World" without the dot is wrong.
- The capital letters and the space after each comma.
- Extra output. A debug line such as "Program started" also counts as output and makes the answer wrong.
- Renaming the class. Keep it as
Solution, since that is what the judge runs.
Next, try Java Stdin and Stdout I to learn reading input with Scanner, or test your basics with our Java MCQs, Set I.
Tip: try to solve the problem yourself before reading the solution. Use the code as a reference to check your approach, and make sure you understand why it works.
More HackerRank solutions More Java solutions All coding problems MCQ practice
See everything in one place: Coding Problems and Solutions
Comments
Post a Comment