Example 1: Constructor and Instance Method
public class Person {
// Instance variables
String name;
int age;
// Constructor
public Person(String n, int a) {
name = n;
age = a;
}
// Instance method
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
// Creating an object using the constructor
Person person1 = new Person("John", 25);
// Calling the method to display information
person1.displayInfo();
}
}
Output:
Name: John
Age: 25
Example 2: Parameterized Method
public class Calculator {
// Method to add two numbers
public int add(int num1, int num2) {
return num1 + num2;
}
public static void main(String[] args) {
// Creating an object of the class
Calculator calc = new Calculator();
// Calling the method and displaying the result
System.out.println("Sum: " + calc.add(10, 20));
}
}
Output:
Sum: 30
Example 3: Overloaded Constructors
public class Book {
// Instance variables
String title;
String author;
// Constructors
public Book(String t, String a) {
title = t;
author = a;
}
public Book(String t) {
title = t;
author = "Unknown";
}
// Instance method
public void displayInfo() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
}
public static void main(String[] args) {
// Creating objects using different constructors
Book book1 = new Book("Java Programming", "John Doe");
Book book2 = new Book("Python Basics");
// Calling the method to display information
book1.displayInfo();
System.out.println();
book2.displayInfo();
}
}
Output:
Title: Java Programming
Author: John Doe
Title: Python Basics
Author: Unknown
Example 4: Static Method
public class MathOperations {
// Static method to calculate square
public static int square(int num) {
return num * num;
}
public static void main(String[] args) {
// Calling the static method directly
int result = MathOperations.square(5);
// Displaying the result
System.out.println("Square: " + result);
}
}
Output:
Square: 25
Example 5: Method with Return Value
import java.util.Scanner;
public class CircleArea {
// Method to calculate area of a circle
public double calculateArea(double radius) {
return Math.PI * radius * radius;
}
public static void main(String[] args) {
// Creating an object of the class
CircleArea circle = new CircleArea();
// Taking user input for radius
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
double userRadius = scanner.nextDouble();
// Calling the method and displaying the result
double area = circle.calculateArea(userRadius);
System.out.println("Area of the circle: " + area);
}
}
Output:
Enter the radius of the circle: 3.5
Area of the circle: 38.48451000647496
If you have any question then comment below - We will answer your questions. And do not forget to follow
0 Comments
If you have any doubts, Please let me know