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

5. Java Methods

The document provides an overview of methods in Java, explaining their definition, syntax, and types, including built-in and user-defined methods. It details the key components of method definitions such as access modifiers, return types, method names, parameters, and method bodies. Additionally, it covers how to create and call both static and instance methods, along with the importance of parameters and arguments in method calls.

Uploaded by

Pashal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

5. Java Methods

The document provides an overview of methods in Java, explaining their definition, syntax, and types, including built-in and user-defined methods. It details the key components of method definitions such as access modifiers, return types, method names, parameters, and method bodies. Additionally, it covers how to create and call both static and instance methods, along with the importance of parameters and arguments in method calls.

Uploaded by

Pashal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

RUCU

OBJECT ORIENTED
PROGRAMMING I RCS 122

Vincent Pius Bob


Ruaha Catholic University
Department of Computer Science
Faculty of Information and Communication
Technology
JAVA
METHODS
Reusable code
blocks performing
specific tasks
Methods
 A method is a block of code which only runs when it is
called.
 You can pass data, known as parameters, into a method.
 Methods are used to perform certain actions, and they are
also known as functions.
 Why use methods? To reuse code: define the code once, and
use it many times.
 All methods in Java must belong to a class. Methods are
similar to functions and expose the behavior of objects.
Syntax of a Method
<access_modifier> <return_type>
<method_name>( list_of_parameters)
{
Key components of Method defi nition

Access Modifier: It specifies the method’s access


level (e.g., public, private, protected, or default).
Public: You can access it from any class
Private: You can access it within the class where it is
defined
Protected: Accessible only in the same package or other
subclasses in another package
Default: It is the default access specifier used by the Java
compiler if we don’t mention any other specifiers. It is
accessible only from the package where it is declared
Key components of Method defi nition

 Return Type: The type of value returned (boolean, int,


double, String etc) , or void if no value is returned.
 Method Name: It follows Java naming conventions; it
should start with a lowercase verb and use camelsCase for
multiple words.
 Parameters: A list of input values (optional). Empty
parentheses are used if no parameters are needed.
 Method Body: It contains the logic to be executed
(optional in the case of abstract methods).
 Note: A method is executed by calling its name.
Key components of Method defi nition
Kinds/Types of Methods in Java

The primary way to categorize methods in Java is


into two main kinds:
i. Built-in (or Predefined) Methods:
• These are methods that are already available in
the Java Class Library
ii.User-Defined Methods:
• These are methods that are created by the
programmer to perform specific tasks according
to the requirements of their program.
ii. User-defi ned methods
i. Built-in/Pre-defi ned methods

Predefined methods are the method that are already


defined in the Java class libraries.
It is also known as the standard library method or
built-in method.
Example:
Math.random() // returns random value
 Math.PI() // return pi value
Math.sqrt(double a): Returns the square root of a
toLowerCase(): Returns a new String with all
characters converted to lowercase.
ii. User-defi ned methods

The written by the user or programmer is known as


a user-defined method. These methods are modified
according to the requirement.
When naming the user-defined methods the camelCase
convention for naming methods in Java should be
followed.

 Example:
sayHello() // user define method created above in the article
myGreeting()
setName()
Different ways to create User-defi ned methods

a. Static Method:
 They can be executed even if there are no objects
created.
 They cannot operate on (reference to) instance variables.
 This is because instance variables may not be created.
 Hence, there is no need to create an object to call it, and
that’s the most significant advantage of static methods.
 Declared inside class with static keyword.
 Example: // Static Method
public static void method_name() {
// static method body
}
User-defi ned methods- Static method(Cont..)

 Example
 Create a method inside Main:
public class Main {
public static void myMethod() {
// code to be executed
}
}
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 hence no
need to create objects.
void means that this method does not have a return
Calling Methods (Cont..)
 To call a method in Java, write the method's name followed
by two parentheses () and a semicolon inside the main
method;
 In the following example, myMethod() is used to print a text
(the action), when it is called:
 Example Inside main, call the myMethod() method:
public class Main {
public static void main(String[] args) {
myMethod();
}
static void myMethod() {
System.out.println("I just got executed!");
}

}
Methods (Cont..)
 A static method with void return type

public class MyClass {

public static void main(String[] args) {


// Calling the static method printRucu() directly using
the class name
printRucu();
}
public static void printRucu() {
System.out.println("Hello Rucu");
}
Methods (Cont..)
 A static method with a non-void return type

public class Calculator {


public static void main(String[] args) {
// Calling the static method addNumbers() and storing the returned value
in the variable result
int result = Calculator.addNumbers();
System.out.println("The sum is: " + result); // Output: The sum
is: 10
}
public static int addNumbers() {
int num1 = 3;
int num2 = 7;
int sum = num1 + num2;
return sum;
b. Instance Methods
 Access the instance data using the object name.
Declared inside a class.
 They are executed only in relation to particular objects.
 They can not execute if no objects have been created.

Example:
// Instance Method
public void method_name() {
// instance method body
}
Creating Objects
 In Java, an object is created from a class. For
instance, if you create the class named Main, you
can use this class to create objects.
 To create an object of Main, specify the class name,
followed by the object name, and use the
keyword new:
Syntax
ClassName objectName = new ClassName();
 Thus, the object from the class Main will be :
Main myObj = new Main();
 You can create multiple objects of one class
Calling Instance methods using Objects

 Create an Object (Instance):


 Use the new keyword and the class
constructor.
Example: ClassName objectName = new
ClassName();
 Use the Object to Call the Method:
 Use the dot operator (.) to access the method.
Syntax: objectName.methodName();
b. Instance Methods (Cont..)
public class Multiplier {

public static void main(String[] args) {

// Create an object (instance) of the Multiplier class

Multiplier multiplierObject = new Multiplier();

// Call the instance method multiplyNumbers() using the object

multiplierObject.multiplyNumbers(); // Output: The product is: 10

public void multiplyNumbers() {

int num1 = 5;

int num2 = 2; An instance


int product = num1 * num2; method with
System.out.println("The product is: " + product);
a void
return-type
}
b. Instance Methods (Cont..)

public class MyClass {


public int myMethod () {

A method called
A class called MyClass

myMethod
int x; p e An instance
ty
p e x = 10; u r n method with
ty le e t r n t
t
a a
a b r
return x; t u en a non-void
D a ri r e te m
v } t a return-type
A s
public static void main(String args[]) {
MyClass obj = new MyClass ();

The main
method
b je c t System.out.println(obj.
An o
myMethod());
}
}
b. Instance Methods (Cont..)
public class Subtractor {
public static void main(String[] args) {
// Create an object (instance) of the Subtractor class
Subtractor subtractorObject = new Subtractor();

// Call the instance method subtractNumbers() using the object


double result = subtractorObject.subtractNumbers();
System.out.println("The difference is: " + result); // Output: The
difference is: 12.5
}
public double subtractNumbers() {
double num1 = 15.7; An instance
double num2 = 3.2; method with
double difference = num1 - num2;
a non-void
return difference;
}
return-type
Note on void and non-void return types
 void Return Type: When a method has a void return
type, it means the method performs an action but does
not send any specific value back to the caller. If you
want to display the result of an operation within a void
method, you will typically use System.out.println()
inside the method's body to print the output directly.
 Non-void Return Type (e.g., int, double, String):
When a method has a return type other than void, it
means the method calculates or retrieves a value and
sends that value back to the code that called it using
the return keyword. To see this returned value, you
typically need to:
i. Store the returned value in a variable in the calling
Parameters & Arguments
Information can be passed to methods as a parameter.
Parameters act as variables inside the method.
Parameters are specified after the method name,
inside the parentheses. You can add as many
parameters as you want, just separate them with a
comma.
Variables that receive arguments inside a method are
called Parameters.
Values passed to a method are called arguments.
For a method to have a value passed, you must first
declare a data type and variable name.
Parameters
Parameters & Arguments
Arguments must match the parameters in terms of
order, number and data type.
This is called parameter order association.

If the parameter order association is not observed:A


syntax (compile time) error will be generated.
A logical error will be generated, i.e. an incorrect
result will be produced.
Parameters & Arguments
Example:
public int getSum(int a, int b, int c){
// The rest of the method
}
The return value is of type int.
int a, int b, int c are the parameters.
This method must be supplied with 3 values of type int
for the three variables when calling it.
An attempt to call this method without supplying the
values will generate a compile error.
Parameters & Arguments
 It is not allowed to declare parameters of the same type this
way:
int getSum(int a, b, c){
// The rest of the method
}
 It is also possible to declare parameters of different data types
such as:
int getSum(int a, double b, float c){
// The rest of the method
}

➡️When calling this method, arguments for variables a, b and c


must be of appropriate data types and provided in the same
order as specified in the method declaration.
Parameters & Arguments(Example)

// Example 1: Printing a simple text using a parameter


public class WelcomePrinter {

public static void printWelcomeMessage(String message) {


System.out.println(message);
}

public static void main(String[] args) {


// Calling the method and passing “Welcome to Rucu" as the argument
printWelcomeMessage(“Welcome to Rucu");
}
}
Parameters & Arguments(Example)
// Example 2: Adding two numbers using parameters and returning
the result
public class Adder {

public static int addTwoNumbers(int num1, int num2) {


int sum = num1 + num2;
return sum; // Returning the calculated sum
}

public static void main(String[] args) {


int number1 = 2;
int number2 = 4;
int result = addTwoNumbers(number1, number2); // Calling the
method with arguments
System.out.println("The sum of " + number1 + " and " + number2 + "
is: " + result);
}
Parameters & Arguments(Example)
Example 3: a method with two parameters of different data types (float and
double)
public class CalculationExample {

public static double calculateResult(float value1, double value2) {


// Perform a calculation with the two values
double result = (value1 * 2) + value2;
return result;
}
public static void main(String[] args) {
float floatValue = 10.5f; // Note the 'f' suffix for float literals
double doubleValue = 20.75;

// Call the method with the float and double values


double finalResult = calculateResult(floatValue, doubleValue);

// Print the result


System.out.println("The result of the calculation is: " + finalResult);
}
END OF LECTURE FIVE
NEXT ON LECTURE SIX

CONSTRUCTORS
THANK YOU!

You might also like