Chapter 7

Adding Some Methods to Your Madness

In This Chapter

arrow Introducing static methods

arrow Seeing some good reasons to use methods in your programs

arrow Creating methods that return values

arrow Creating methods that accept parameters

In Java, a method is a block of statements that has a name and can be executed by calling (also called invoking) it from some other place in your program. You may not realize it, but you're already very experienced in using methods. To print text to the console, for example, you use the println or print method. To get an integer from the user, you use the nextInt method. To compare string values, you use the equals or equalsIgnoreCase method. Finally, the granddaddy of all methods — main — contains the statements that are executed when you run your program.

All the methods you've used so far (with the exception of main) have been defined by the Java API and belong to a particular Java class. The nextInt method belongs to the Scanner class, for example, and the equalsIgnoreCase method belongs to the String class. By contrast, the main method belongs to the class ...

Get Java All-in-One For Dummies, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.