
Understanding Methods in Java with Simple Example
What is a Method in Java? A method in Java is a block of code that performs a specific task. It helps you reuse code, improve readability, and organize programs. Basic Syntax returnType methodName ( parameters ) { // method body // code to execute return value ; // optional } Example Program public class Calculator { public static void main ( String [] args ){ Calculator casio = new Calculator (); casio . add ( 10 , 5 ); casio . sub ( 10 , 5 ); casio . multiply ( 10 , 5 ); casio . div ( 10 , 5 ); } void add ( int a , int b ){ System . out . println ( a + b ); } void sub ( int a , int b ){ System . out . println ( a - b ); } void multiply ( int a , int b ){ System . out . println ( a * b ); } void div ( int a , int b ){ System . out . println ( a / b ); } } Output Flow of Execution Program starts in main() Object casio is created Methods are called one by one: add() → prints 15 sub() → prints 5 multiply() → prints 50 div() → prints 2 Program ends Types of Methods in Java 1. Predefined M
Continue reading on Dev.to
Opens in a new tab




