Skip to content

Commit 491b333

Browse files
committed
feat: Add StringExample class with greeting methods and user input
WHAT the code does: - Defines a `StringExample` class that demonstrates **string handling** with methods. - Uses `Scanner` to take user input (a name). - Calls `myGreet(String)` to return a personalized greeting. - Optionally has `greet()` that returns a static message ("how are you"). - Prints the personalized greeting to the console. WHY this matters: - Demonstrates how to create and return strings from methods. - Shows **string concatenation** for dynamic message creation. - Reinforces **method calling** and passing arguments in Java. - Introduces **user input handling** with `Scanner`. HOW it works: 1. Program prompts → `"Enter your name:"`. 2. Reads input using `in.next()` and stores it in `naam`. 3. Calls `myGreet(naam)` which returns `"Hello <name>"`. 4. Prints personalized greeting (e.g., `"Hello Rahul"`). 5. `greet()` exists as a simple utility returning `"how are you"` (not used in main, but available). Tips & gotchas: - `Scanner` should be closed after use (`in.close()`) to prevent resource leaks. - `in.next()` reads only a single word; use `in.nextLine()` if full names with spaces are needed. - String concatenation creates new objects internally → consider `StringBuilder` for heavy usage. - Method names could follow clearer naming conventions (e.g., `getGreeting()`). Use-cases: - Basic user interaction programs. - Teaching examples for methods and return values. - Building blocks for chatbots or text-based interfaces. - Can be extended to add multiple greeting styles (formal, casual, etc.). Short key: class-string example-greeting-user input. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent c26a7fe commit 491b333

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

Section10Methods/Methods 2.O/src/StringExample.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
11
import java.util.Scanner;
22

33
public class StringExample {
4-
54
public static void main(String[] args) {
6-
// String message = greet();
7-
// System.out.println(message);
8-
95
Scanner in = new Scanner(System.in);
106
System.out.print("Enter your name: ");
7+
118
String naam = in.next();
9+
1210
String personalised = myGreet(naam);
1311
System.out.println(personalised);
12+
13+
String message = greet();
14+
System.out.println(message);
1415
}
1516

1617
static String myGreet(String name) {
1718
String message = "Hello " + name;
1819
return message;
1920
}
2021

21-
2222
static String greet() {
2323
String greeting = "how are you";
2424
return greeting;

0 commit comments

Comments
 (0)