In this lesson, you will learn
Here is a method square() that returns the square of the number 10.
int square()
{
return 10*10;
}
The above method will return only the square of the number 10 always. Its use is very limited. We have to create a general-purpose method that can calculate the square of any number.
You can add a parameter to the above method. Here is the modified version of method square().
int square(int i)
{
return i * i;
}
Now, square(int i) will return the square of whatever value it is called with.
int x=square(10); // x equals 100
int y=square(15); // y equals 225
package ch7;
class Calculator {
int add(int a, int b) {
return a + b;
}
int multiply(int a, int b) {
return a * b;
}
}
public class CalculatorMain {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Addition: " + calc.add(5, 3));
System.out.println("Multiplication: " + calc.multiply(4, 2));
}
}
Addition: 8
Multiplication: 8
The add() method is declared with two parameters of type int. This method calculates the addition of two numbers using the formula a+b and returns the result.
The following examples demonstrate an instance method to initialize instance variables.
public class Rectangle {
double length;
double width;
void setDimensions(double newLength, double newWidth) {
length = newLength;
width = newWidth;
}
double calculateArea() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
Rectangle rect1 = new Rectangle();
rect1.setDimensions(5.0, 3.0);
Rectangle rect2 = new Rectangle();
rect2.setDimensions(6.0, 4.0);
System.out.println("Area of rect1: " + rect1.calculateArea());
System.out.println("Area of rect2: " + rect2.calculateArea());
}
}
Area of rect1: 15.0
Area of rect2: 24.0
public class Book {
String title;
int pages;
void setTitle(String newTitle) {
title = newTitle;
}
void setPages(int newPages) {
pages = newPages;
}
void displayInfo() {
System.out.println("Title: " + title + ", Pages: " + pages);
}
}
public class Main {
public static void main(String[] args) {
Book book1 = new Book();
book1.setTitle("Java Programming");
book1.setPages(500);
Book book2 = new Book();
book2.setTitle("Effective Java");
book2.setPages(300);
book1.displayInfo();
book2.displayInfo();
}
}
Area of rect1: 15.0
Area of rect2: 24.0
Very nice content.
You must be logged in to submit a review.