Problem: The Formal Greeting
Objective: Write a program that takes two names from the user and outputs a single, formatted greeting sentence. This task is a fundamental exercise in handling string input and using the concatenation operator.
Problem Statement:
Take two names, A (Speaker) and B (Recipient), as input from the user. Print the sentence: “A says Hi to B” (without the quotation marks), where A and B are the names provided in the input.
| Constraint | Value |
| Input A & B Length | 1 ≤ length ≤ 15 |
| Characters | Lowercase English Alphabets |
Example:
| Input | Output |
| Input A: Ram Input B: Shyam | Output: Ram says Hi to Shyam |
Solution in Java
This solution requires the Scanner class to read the input and uses System.out.println() with the + operator for output formatting.
1. Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Step 1: Initialize the Scanner object to read user input.
Scanner sc = new Scanner(System.in);
// Step 2: Read the first name (Speaker A).
// sc.next() reads the next word (token) from the input.
String nameA = sc.next();
// Step 3: Read the second name (Recipient B).
String nameB = sc.next();
// Close the scanner when done (good practice).
sc.close();
// Step 4: Print the final formatted string using concatenation.
// We combine the variable 'nameA', the fixed string " says Hi to ",
// and the variable 'nameB'.
System.out.println(nameA + " says Hi to " + nameB);
}
}
2. Explanation
| Step | Concept | Description |
import java.util.Scanner; | Input Utility | Imports the Scanner class, which is necessary for reading input from the console. |
Scanner sc = new Scanner(System.in); | Scanner Object | Creates an instance of the Scanner object, preparing the program to listen for input. |
String nameA = sc.next(); | Reading String Input | The sc.next() method reads the first token (word) of input and stores it in the String variable nameA. |
String nameB = sc.next(); | Reading Second Input | Reads the second input word and stores it in nameB. |
nameA + " says Hi to " + nameB | String Concatenation | The + operator is used here exclusively for string concatenation (joining strings and variables together) to form the required output sentence. |
System.out.println() | Output | Prints the complete, concatenated sentence to the console, followed by a newline. |
