A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, and apply method abstraction in the program design.

Creating Method
Considering the following example to explain the syntax of a method −
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.vidvaan.corejava.exception01.introduction; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Scanner; // Exception Handling Program public class ExceptionHandlingDemo { public static void main(String[] args) { System.out.println("main begin"); System.out.println("Finding value for : numberOfRecordsToRead"); int numberOfRecordsToRead = -1; try { // Reading config.txt file to get value for numberOfRecordsToRead Path filePath = Paths.get("config.txt"); Scanner scanner = new Scanner(filePath); if (scanner.hasNext()) { numberOfRecordsToRead = scanner.nextInt(); } } catch (IOException e) { // Assigning default value 10 when file reading failed System.out.println("Exception raised while reading config.txt"); numberOfRecordsToRead = 10; } System.out.println("numberOfRecordsToRead : " + numberOfRecordsToRead); // This final statement also executes even exception is raised, Because // exception is handled System.out.println("main end"); } } |
Output :
main begin
Finding value for : numberOfRecordsToRead
Exception raised while reading config.txt
numberOfRecordsToRead : 10
main end