0% found this document useful (0 votes)
20 views

2 Methods and Classes

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

2 Methods and Classes

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Methods and Classes

INTRODUCTION TO JAVA PROGRAMMING

CSA6003T
BHAWANA BOTHARA
ASSISTANT PROFESSOR
Learning Objectives

 Understand the structure and purpose of classes in Java.


 Explain the concept of methods and their role in Java programming.
 Create and use methods within classes.
 Distinguish between different types of methods.
 Apply real-life analogies to better understand classes and methods.
What is method?

 A method is a block of code that performs a specific task.


 The method in Java or Methods of Java is a collection of statements that perform
some specific tasks and return the result to the caller.
 Methods are used to define the behaviour of objects created from a class.
Method Declaration
 The method declaration provides information about method attributes, such as
visibility, return-type, name, and arguments. It has six components that are known
as method header, as we have shown in the following figure.
Method Declaration
 Method Signature: Every method has a method signature. It is a part of the
method declaration. It includes the method name and parameter list.
 Access Specifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:
 Public: The method is accessible by all classes when we use public specifier in our application.
 Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
 Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
 Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
Access Modifiers
 public: Accessible from any other class.
 private: Accessible only within the declared
class.
 protected: Accessible within the same package
and subclasses.
 default: Accessible only within the same
package.
Method Declaration
 Return Type: Return type is a data type that the method returns. It may have a primitive
data type, object, collection, void, etc. If the method does not return anything, we use void
keyword.
 Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked
by its name.
 Parameter List: It is the list of parameters separated by a comma and enclosed in the pair
of parentheses. It contains the data type and variable name. If the method has no parameter,
left the parentheses blank.
 Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Example

public class Car


{
String color;
String model;

int year;
void startEngine()
{
System.out.println("Engine started");
}
}
Method Types
 In Java, there are two types of methods:
 User-defined Methods: We can create our own method based on our requirements.
 Standard Library Methods: These are built-in methods in Java that are available to use.
Predefined Method
 In Java, predefined methods are the method that is already defined in the Java
class libraries is known as predefined methods. It is also known as the standard
library method or built-in method.
 We can directly use these methods just by calling them in the program at any
point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
When we call any of the predefined methods in our program, a series of codes
related to the corresponding method runs in the background that is already stored
in the library.
 Each and every predefined method is defined inside a class. Such as print()
method is defined in the java.io.PrintStream class. It prints the statement that we
write inside the method. For example, print("Java"), it prints Java on the console.
Example

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
User-defined Method
 The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the requirement.

public static void findEvenOdd(int num)


{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
class Main {

// create a method
public int addNumbers(int a, int b) {
int sum = a + b;
// return value
return sum;
}

public static void main(String[] args) {

int num1 = 25;


int num2 = 15;

// create an object of Main


Main obj = new Main();
// calling method
int result = obj.addNumbers(num1, num2);
System.out.println("Sum is: " + result);
}
}
Ways to Create Method in Java
 There are two ways to create a method in Java:
1. Instance Method: Access the instance data using the object name.
Declared inside a class.
2. Static Method: Access the static data using class name. Declared
inside class with static keyword.
Static Method

 A method that has static keyword is known as static method. In other words, a
method that belongs to a class rather than an instance of a class is known as a
static method. We can also create a static method by using the
keyword static before the method name.
 The main advantage of a static method is that we can call it without creating an
object. It can access static data members and also change the value of it. It is used
to create an instance method. It is invoked by using the class name. The best
example of a static method is the main() method.
public class Display
{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static me
thod.");
}
}
public class InstanceMethodExample
{
Instance Method public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new
 The method of the class is known as InstanceMethodExample();
an instance method. It is a non- //invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
static method defined in the class.
}
Before calling or invoking the instance int s;
method, it is necessary to create an //user-defined method because we have not used static
object of its class. Let's see an keyword
example of an instance method. public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
}
Java Method Return Type class Main {

 A Java method may or may not return a value // create a method


public static int square(int num) {
to the function call. We use the return
statement to return any value. For example // return statement
return num * num;
}

int addNumbers() { public static void main(String[] args) {


... int result;
return sum;
} // call the method
// store returned value to result
result = square(10);

 If the method does not return any value, we System.out.println("Squared value of 10 is: " +
use the void keyword as the return type of the result);
method. For example, }
}
Method Parameters in Java
 While some methods don’t need parameters, most do. Parameters allow a method
to be generalized. That is, a parameterized method can operate on a variety of data
and/or be used in a number of slightly different situations.
 It is important to keep the two terms parameter and argument straight. A
parameter is a variable defined by a method that receives a value when the
method is called. For example, in square( ), i is a parameter. An argument is a
value that is passed to a method when it is invoked.

int square() int square(int i)


{ {
return 10 * 10; return i * i;
} }
class Test {
int a, b;
Using Objects as Test(int i, int j) {
a = i;

Parameters b = j;
}
// return true if o is equal to the invoking
 it is both correct and common object
to pass objects to methods. For boolean equalTo(Test o) {
if(o.a == a && o.b == b) return true;
example
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " +
ob1.equalTo(ob2));
System.out.println("ob1 == ob3: " +
ob1.equalTo(ob3));
}
}
Argument Passing

 The first way is call-by-value. This approach copies the value of an argument into
the formal parameter of the subroutine. Therefore, changes made to the parameter
of the subroutine have no effect on the argument.
 The second way an argument can be passed is call-by-reference. In this approach,
a reference to an argument (not the value of the argument) is passed to the
parameter. Inside the subroutine, this reference is used to access the actual
argument specified in the call. This means that changes made to the parameter
will affect the argument used to call the subroutine.
Java Argument Passing

 although Java uses call-by-value to pass all arguments, the precise effect differs
between whether a primitive type or a reference type is passed.
 When you pass a primitive type to a method, it is passed by value. Thus, a copy of
the argument is made, and what occurs to the parameter that receives the
argument has no effect outside the method.
 When you pass an object to a method, the situation changes dramatically, because
objects are passed by what is effectively call-by-reference. Keep in mind that
when you create a variable of a class type, you are only creating a reference to an
object.
Summary

 Classes and methods are fundamental concepts in Java.


 A class is a blueprint for objects, and methods define the behavior of these
objects.
 Understanding and using classes and methods effectively is crucial for Java
programming.
Assessment
1. A method that does not return any value has a return type of ______.Answer:
void
2. Which access modifier makes a method accessible from any other class?
A) private
B) protected
C) public
3. Which of the following is a correct method signature for a method that returns an
integer and takes two integer parameters?
A) int methodName(int a, int b)
B) void methodName(int a, int b)
C) methodName(int a, int b) : int
Assessment
4. What is a method in Java?
A) A blueprint for objects
B) A block of code that performs a specific task
C) A type of variable
5. A method that belongs to the class rather than an instance is called a ______
method. Answer: static
6. Which of the following is a correct method signature for a method that returns a
double and takes one double parameter?
A) double methodName(double a)
B) void methodName(double a)
C) methodName(double a) : double
Assignment

 How can you make a method in Java that can be called without creating an
instance of the class?
 What are the advantages of using methods?
 Explain how do you create methods in java.
 Create and method in class which return cube of a value passed to it.
 Explain access specifiers.

You might also like