Page 107 - CTS - CSA TP - Volume 2
P. 107
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 95 : Pass data and Objects to Methods
Objectives
At the end of this exercise you shall be able to
• know about how to pass data and objects to methods in JAVA
• develop Java programs using data and object passing to methods.
Requirements
Tools/Materials
• PC/Laptop with Windows OS
• JDK Software
• Text Editor (Visual Studio/Sublime/Notepad)
Procedure
In Java, you can pass data and objects to methods in various ways, such as passing primitive data types, passing
objects, and passing arrays. Below are examples of Java programs demonstrating these concepts:
1 Passing Primitive Data Types to Methods
TASK 1: Finding sum of two numbers
public class PrimitiveDemo {
public static void main(String[] args) {
int x = 10;
i nt y = 20;
// Passing primitive data types to a method
int sum = add(x, y);
System.ouwt.println(“Sum: “ + sum);
}
// Method to add two integers
public static int add(int a, int b) {
return a + b;
}
}
92