In this example, we define two methods: add
and greet
. The add
method accepts two integer parameters, calculates their sum, and returns the result. The greet
method accepts a String parameter (name
) and prints a greeting message. Within the main method, we call add(10, 20)
, storing the result in the variable result
, and then print it. We also call greet("Alice")
to display a personalized greeting.
Now, try changing the values yourself!
Can you call add(50, 70)
and see what sum you get?
What happens if you call greet("John")
or even try your name?
Feel free to experiment by passing different numbers to the add
method, or use different names in greet
. Playing with the code like this helps you understand how parameters work in real programs.
In Java, input refers to data or information received from users or external sources, typically through the keyboard, files, or other devices. The most common and straightforward way to handle user input is through the Scanner class.
On the other hand, output means displaying data or information back to users, commonly via the console. Java provides built-in methods like print(), println(), and printf() for displaying output clearly and conveniently.
Combining these two concepts allows your programs to interact dynamically with users, taking information from them, processing it, and presenting the results.
Note: Before running the code, enter your name and age in the input section below the widget, each on a separate line, as follows: