Methods_1750263724
Methods_1750263724
A method in Java is a block of code that performs a specific task and can be called
(invoked) when needed. It helps in organizing code, promoting reuse, and
improving readability.
-> Predefined methods are methods that are already defined in Java’s standard
library (Java API).
-> These methods are part of various Java packages (like java.lang, java.util,
java.io, etc.) and are ready to use, saving developers time and effort.
-> Example: Integer.toBinaryString();
Integer.toOctalString();
Math.sqrt();
2. User-defined Method:
Explanation of Syntax
Part Description
->Example:
Access Modifier:
Access modifiers in Java control who can access a method — from where in the
program the method can be called. They are an essential part of encapsulation in
object-oriented programming.
-> We use the public modifier when we want a method to be accessible from
anywhere — even from outside the class or outside the package.
Output:hello
Note: Define a method in one class (Sample)
-> And call it from another class (Test) using an object.
Output:
The sum is : 30
• They act like placeholders for the values that will be passed to the method.
• The data type of each formal argument must be specified.
-> This is useful when you don’t know how many arguments you’ll need to pass.
->Example: