Today you will learn:
By the end, you will be able to structure your code using methods and create simple objects.
A method is a block of code that performs a specific task.
public static int add(int x, int y) {
return x + y;
}
To call a method:
int result = add(5, 3);
Explanation:
int → return typex, y → parametersreturn → sends the result backParameters allow you to pass data into methods.
Return values send results back to the caller.
public static int multiply(int a, int b) {
return a * b;
}
Java is an object-oriented programming language.
Example:
class Dog {
String name;
int age;
void bark() {
System.out.println("Woof!");
}
}
public class Calculator {
public static int add(int x, int y) {
return x + y;
}
public static void main(String[] args) {
int sum = add(5, 3);
System.out.println("Sum: " + sum);
}
}
Create a class Dog with attributes and a method.
Steps:
Dogname and agebark()Example:
public class Dog {
String name;
int age;
void bark() {
System.out.println("Woof!");
}
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark();
}
}