Lecture 2
Lecture 2
class AreaOfCircle
double r= s.nextDouble();
double area=(22*r*r)/7 ;
}
Java Methods
● A method is a block of code which only runs when it is called.
● Methods are used to perform certain actions, and they are also known as functions.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by parentheses
(). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own
methods to perform certain actions:
myMethod();
}}
● myMethod() is the name of the method
● static means that the method belongs to the Main class and not an object of the Main class.
● void means that this method does not have a return value.
● A method can also be called multiple times
myMethod("Liam");
myMethod("Jenny");
myMethod("Anju");
}
When a parameter is passed to the method, it is called an argument.
Multiple Parameters
public class Main {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anju", 31);
}}
Java Method Overloading
With method overloading, multiple methods can have the same name with different
parameters:
static int plusMethod(int x, int y) {
return x + y; }
return x + y; }
In the example below, we created a static method, which means that it can be accessed without creating an object
of the class, unlike public, which can only be accessed by objects:
● Default Constructor
● Parameterized Constructor
● Copy Constructor
int a;
boolean b;
System.out.println("Default Value:");
}}
2. Parameterized Constructor in Java
A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with
our own values, then use a parameterized constructor.
class Main {
String languages;
Main(String lang) {
languages = lang;
public static void main(String[] args) { // call constructor by passing a single value
private variable;
this.variable=x; }
return variable;
}} //Note: In both getter and setter, the first letter of the variable should be capital.
import java.io.*; // Importing input output classes
class GetSet { // Member variable of this class
private int num;
// Method 1 - Setter
public void setNumber(int number) {// Checking if number is between 1 to 10 exclusive
if (number < 1 || number > 10) {
throw new IllegalArgumentException();
}
num = number;
} // Method 2 - Getter
public int getNumber() { return num; }
}// Class 2
// Main class
class ABC{ // Main driver method
public static void main(String[] args)
{GetSet obj = new GetSet();
// Calling method 1 inside main() method
obj.setNumber(5);
System.out.println(obj.getNumber()); }}
Keywords
1. Final : The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
● variable
● method
● class