Command Palette

Search for a command to run...

Back to the lesson: Topic 3.1 — Methods: Naming a Piece of Work
Core Java · Example 1 of 3

Declare once, call many times

A method is a named block of code you can run again and again by calling its name. Methods let you write a piece of work once, give it a clear name, and reuse it, which keeps programs short, readable and easy to fix.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a program with a method printLine() that prints 20 dashes, and use it to print a framed message: a line, Welcome to Java, a line.

02

Write printSquare() that prints a 3x3 block of # using two nested loops, and call it twice with a blank line in between.

03

Write three methods morning(), afternoon() and evening() that each print a greeting, and a method fullDay() that calls all three in order. Call fullDay() from main.

Explain it without notes

01

What happens, step by step, when main calls a method and that method finishes?

02

Why does duplicating code instead of writing a method cause bugs over time?

03

Why can't main call a method that isn't marked static?

04

What makes a good method name? Give two good and two bad examples.

Declare once, call many times
Sign in to run this example in your browser.

Expected output

main starts
==========
  HECTAL  
==========
Step: wash your hands
Step: wash your hands
==========
  HECTAL  
==========
main ends