2.2 ppt java
2.2 ppt java
(UNIT 2)
times.
We do not require to write code again and
invoke it.
METHOD DECLARATION
NAMING A METHOD
method.
It reaches a return statement.
Throws an exception.
WAYS TO CREATE METHOD IN
JAVA
Method Overloading.
ADVANTAGES OF USING
METHODS
Reusability : Methods allow you to write code once and use it many times,
making your code more modular and easier to maintain.
Abstraction : Methods allow you to abstract away complex logic and provide
a simple interface for others to use. This makes your code more readable and
easier to understand.
Improved readability : By breaking up your code into smaller, well-named
methods, you can make your code more readable and easier to understand.
Encapsulation : Methods allow you to encapsulate complex logic and data,
making it easier to manage and maintain.
Separation of concern s: By using methods, you can separate different parts
of your code and assign different responsibilities to different methods,
improving the structure and organization of your code.
Improved modularity : Methods allow you to break up your code into
smaller, more manageable units, improving the modularity of your code.
Improved testability : By breaking up your code into smaller, more
manageable units, you can make it easier to test and debug your code.
Improved performance: By organizing your code into well-structured
methods, you can improve performance by reducing the amount of code that
needs to be executed and by making it easier to cache and optimize your
code.
CONSTRUCTOR
Java constructors or constructors in Java is a
terminology used to construct something in
our programs. A constructor in Java is
a special method that is used to initialize
objects. The constructor is called when an
object of a class is created. It can be used to
set initial values for object attributes.
WHEN JAVA CONSTRUCTOR IS
CALLED?
Outpu
int result;
Calculator(int initialValue) {
this.result = initialValue;
}
t:
public Calculator add(int value) {
this.result += value;
return this;
}
public Calculator subtract(int value) {
Final
this.result -= value;
return this;
}
}
public class ObjectReturningExample
resul
{
public static void main(String[] args) {
Calculator calculator = new Calculator(
10);
int finalResult = calculator.add(5).subt
t: 12
ract(3).rsult;
System.out.println("Final result: " + fi
nalResult)
}
}
TYPES OF OBJECT PASSING
Pass by Value
Output:
public class PassByValueExample {
public static void modifyValue
Before modification:
(int value) 10
{
value = 20; After modification: 10
}
public static void main(String[] ags
){
int x = 10;
System.out.println("Before modi
fication: " + x);
modifyValue(x);
System.out.println("After modifi
cation: " + x);
}
}
PASS BY REFERENCE
PASSING OBJECTS THROUGH CONSTRUCTORS