We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 11
Java Methods
Understanding Functions in Java
What is a Method? • A method is a block of code that performs a specific task. • Used to reuse code and improve program structure. • Helps in making programs modular and manageable. Syntax of a Method • Basic Syntax: • returnType methodName(parameters) { • // method body • } • Example: • int addNumbers(int a, int b) { • return a + b; • } Types of Methods • Predefined Methods (built-in, like println()) • User-Defined Methods (created by the programmer) • Static vs Non-static methods Calling a Method • Calling Syntax: • methodName(arguments); • Example: • int sum = addNumbers(5, 10); Why Use Methods? • Reduces code repetition • Increases readability • Makes debugging easier • Promotes reuse and modularity Key Parts of a Method • Return Type: What the method returns (e.g., int, void). • Method Name: Name to call the method. • Parameters: Input values inside parentheses. • Method Body: The code inside {}. Simple Method Example • void greet() { • System.out.println("Hello, World!"); • } • void → No return value, greet → Method name, No parameters. Methods with Parameters • void greetUser(String name) { • System.out.println("Hello, " + name); • } • Method can take input and act differently! Returning a Value • int square(int x) { • return x * x; • } • return sends back the result. Conclusion • Methods make programs organized and efficient. • Help to reuse code and reduce errors. • Essential for writing clean, modular, and professional Java code. • Practice writing simple methods to master Java!