0% found this document useful (0 votes)
14 views13 pages

Understanding Static and Non-Static Methods

This document discusses methods in Java. It defines four types of methods: those that return no value and receive no parameters, those that return no value but receive parameters, those that return a value but receive no parameters, and those that return a value and receive parameters. It provides examples of defining and calling each type of method. It includes tasks that involve writing code to define and call methods to perform tasks like printing messages, returning the square of a number, and displaying a person's name and age. The document provides a template for writing method definitions and calls based on whether they return a value or not and whether they receive parameters or not.

Uploaded by

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

Understanding Static and Non-Static Methods

This document discusses methods in Java. It defines four types of methods: those that return no value and receive no parameters, those that return no value but receive parameters, those that return a value but receive no parameters, and those that return a value and receive parameters. It provides examples of defining and calling each type of method. It includes tasks that involve writing code to define and call methods to perform tasks like printing messages, returning the square of a number, and displaying a person's name and age. The document provides a template for writing method definitions and calls based on whether they return a value or not and whether they receive parameters or not.

Uploaded by

Fatin Aqilah
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

3.

5 Methods

Non-static Methods

Learning Outcomes:

At the end of this lesson, students should be able to:


1. Construct non-static user defined methods
2. Construct programs that use standard and/or user-defined methods based
on given problem.

Task 1: Understanding the Concept of Methods


Methods must be defined before it is being called.

Method Definitions

Four (4) types of method defintions with examples:

Type 1. A method definition which return no value, receive no parameters


void showWelcome(){
[Link]("Welcome to Java");
}

Type 2. A method definition which return no value, receive parameters


void sayHello(String name){
[Link]("Hello "+ name);
}

Type 3. A method definition which return int value, receive no parameters


(this type of definition is rarely used)
int calcProduct(){
return 10*10;
}

Type 4. A method definition which return int value, receive parameters


int calcAdd(int x, int y){
return x+y;
}

Page 1
3.5 Methods

Calling a Method

Before a method is called, we must create the object in order to call the specific
method. Object created using the statement,

ClassName obj = new ClassName();

where, ClassName is the name of the class, and obj can be any valid identifiers
to represent instance of the class.

Four (4) types of method calls based on method definitions with examples:

1. Calling a Type 1 method, receive no value, pass no arguments:


[Link]();

2. Calling a Type 2 method, receive no value, pass arguments:


[Link](String name);

3. Calling a Type 3 method, receive value, pass no arguments (rarely used):


result = [Link]();
or
[Link]([Link]());

4. Calling a Type 4 method, receive value, pass arguments:


result = [Link](x, y);
or
[Link]([Link](x,y));

For calling Type 3 and Type 4 method, usually these types of methods call either:

 Assign to a variable then display the result using the output statement, or
 Directly use output statement to display the output.

Page 2
3.5 Methods

For example:

import [Link];
class Arithmetic{
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
Arithmetic obj = new Arithmetic();

[Link]("Enter your name and 2 numbers: ");


String name = [Link]();
int num1 = [Link]();
int num2 = [Link]();

[Link]();
[Link](name);
int result = [Link](num1, num2);
[Link]("Addition: "+ result);
}

void showWelcome(){
[Link]("Welcome to Java");
}

void sayHi(String name){


[Link]("Hello "+name);
}

int calcAdd(int x, int y){


return x+y;
}
}

Enter your name and 2 numbers: Amran 9 3


Welcome to Java
Hello Amran
Addition: 12

Page 3
3.5 Methods

Template for Method Definitions and Calls

Return No Value Return a Value (int, double, boolean, char, String)


METHOD
Method Definition Method Call Method Definition Method Call

void myMethod1(){ obj.myMethod1() int myMethod3(){ tmp=obj.myMethod3()

Receive //method-body //method-body [Link](tmp);


No
Arguments } }

Type 1 Type 3

void myMethod2(int a){ obj.myMethod2(x) int myMethod4(int a){ [Link](obj.myMethod4(x));

//method-body //method-body
Receive
} }
Arguments Please read Page 55, for calling
Type 3 and Type 4 method.

Type 2 Type 4

Page 4
3.5 Methods

Task 2: A Method Accepting No Arguments and Returning No


Value
Write a complete Java program which print out a message “I Love Computer
Science” from a method named printMessage().

[Link]
class MethodCall1{

public static void main(String[] args){


1
MethodCall1 mc = new MethodCall1();

[Link]();

} 3
4

void printMethod(){

[Link]("I Love Computer Science");

I Love Computer Science

*Note: mc is object or instance of class MethodCall1.

Explanation:

No. Description

1 Create object, mc from class MethodCall1

2 Use object, mc to call method, printMethod

3 Pass no arguments, () to printMethod

4 Call method, printMethod

Page 5
3.5 Methods

Task 3: A Method Accepting No Arguments and Returning No


Value
Write a complete Java program which print out the following messages:

Message 1: I Love Computer Science


Message 2: I Like Programming
Message 3: I Learn Java

Message 1: I Love Computer Science will be printed from the main() method.
Message 2: I Like Programming will be printed from calling methodName1().
Message 3: I Learn Java will be printed from calling methodName2().

[Link]

class MethodCall2{
public static void main(String[] args){
MethodCall2 obj = new MethodCall2();

[Link]("I Love Computer Science");


obj.methodName1();
obj.methodName2();
}

void methodName1(){
[Link]("I Like Programming");
}

void methodName2(){
[Link]("I Learn Java");
}
}

I Love Computer Science


I Like Programming
I Learn Java

*Note: The statement

MethodCall2 obj = new MethodCall2();

is a syntax to create object, obj from its class name MethodCall2.

Page 6
3.5 Methods

Task 4: A Method with Arguments and Returning No Value


Write a complete Java program with method calling which display the following
output:

Hello, <yourname>

[Link]

class MethodCall3{
public static void main(String[] args){
MethodCall3 mc = new MethodCall3();

String name = "Amran";

[Link](name);
}

void printName(String a){


[Link]("Hello, "+ a);
}
}

Hello, Amran

*Note: The statement

MethodCall3 mc = new MethodCall3();

is a syntax to create object, mc from its class name MethodCall3.

**Here, we can see that the object name can be any valid identifiers.

Page 7
3.5 Methods

Task 5: A Method with Arguments and Returning No Value

Problem Statement
Write a complete Java program which accept name and age of a person, then
display the following output from the method named printNameAge():

Hello, <yourname>
Your age now is <age> years old

[Link]

import [Link];
class MethodCall4{
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
MethodCall4 tmp = new MethodCall4();

[Link]("Enter name and age: ");


String name = [Link]();
int age = [Link]();
[Link](name,age);
}

void printName(String a, int b){


[Link]("Hello, "+ a);
[Link]("Your age now is "+ b +" years old.");
}
}

Enter name: Amran


Enter age: 40
Hello, Amran
Your age now is 40 years old.

 What is the object name for the class MethodCall4? ______________________

 Is the method call, in this program passed any arguments? If yes, name the
arguments. __________ ____________ ____________

 Name the parameters that receive the arguments passed. ______ ______

Page 8
3.5 Methods

Task 6: A Method without Arguments and Returning Value


Write a complete Java program which find the square value of 10.

[Link]

class SquareMain {

public static void main(String[] args) {

SquareMain sm = new SquareMain();

int result;

result = [Link]();

[Link]("Squared value of 10 is: " + result);

int square() {

return 10 * 10;

Squared value of 10 is: 100

 Name one (1) object in this program.


__________________

 Give one (1) example of method definition and method call exists in this
program.

____________________________

____________________________

Page 9
3.5 Methods

Task 7: A Method Accepting Arguments and Returning Value


Write a complete Java program which return the square of a number 3 and 4.

[Link]

class SquareMain {
public static void main(String[] args) {
SquareMain sm = new SquareMain();

int result, n;

n = 3;
result = [Link](n);
[Link]("Square of 3 is: " + result);

n = 4;
result = [Link](n);
[Link]("Square of 4 is: " + result);
}

int square(int i) {
return i * i;
}
}

Square of 3 is: 9
Square of 4 is: 16

Which type the method square?

Page 10
3.5 Methods

Task 8: A Method Accepting Arguments and Returning Value


Write a complete Java program which return the sum and the product of two
integers.

[Link]

class ArithmeticMain{
public static void main(String[] args){
ArithmeticMain am = new ArithmeticMain();

[Link]("10 + 20 = " + [Link](10, 20));


[Link]("20 x 40 = " + [Link](20, 40));
}

int getSum(int i, int j){


return i + j;
}

int getProduct(int x, int y){


return x * y;
}
}

10 + 20 = 30
20 x 40 = 800

What is the object name for the class ArithmeticMain?

Which type the method getSum and getProduct?

Page 11
3.5 Methods

Task 9: A Method Accepting Arguments and Returning Value


Write a complete Java program which takes int as a parameter. Based on the
argument passed, the method returns the squared value of it.

[Link]

class SquareMain {
public static void main(String[] args) {
SquareMain sm = new SquareMain();

int result=0;

for (int i = 1; i <= 5; i++) {


result = [Link](i);
[Link]("Square of "+ i +" is : "+ result);
}
}

int getSquare(int x){


return x * x;
}
}

What is the output for the above program?

Page 12
3.5 Methods

Task 10: Exercise

1 Create a non-static method,

(a) Write the first line of a method named myMethod that takes three
parameters: an int and two Strings.
(b) Write a line of code that calls myMethod, passing as arguments the
value 501, the name of your favorite colour, and the name of the
state you grew up on.

2 Create a non-static method,

(a) Write a method called printAmerican that takes the day, date,
month and year as parameters and that displays them in American
format.
(b) Test your method by invoking it from main and passing
appropriate arguments. The output should look something like this
(except that the date might be different):
Saturday, July 22, 2015
(c) Once you have debugged printAmerican, write another method
called printEuropean that displays the date in European format.

3 Write a method called square that takes an integer and returns an


approximation of the square of the parameter. Test the method using
main method.

4 Write a method named isNotDivisible that takes two integers, p and


q, and that returns true if p is not divisible by q, and false otherwise.
Test the method using main method.

5 Write a method named oddSum that takes a positive odd integer n and
returns the sum of odd integers from 1 to n. Test the method using main
method.

Page 13

Common questions

Powered by AI

Methods in Java can be specialized for specific tasks, such as arithmetic operations and personalized greetings. For arithmetic operations, methods like getSum(int i, int j) and getProduct(int x, int y) return the sum and product of the numbers, respectively . For personalized greetings, methods like sayHi(String name) and printName(String a, int b) print customized messages by taking personal information as parameters .

Java methods designed to print multiple messages are typically structured with void return types and no parameters. These methods use System.out.println() to output text. Object creation (e.g., MethodCall2 obj = new MethodCall2();) facilitates method calls by associating the method with the specific instance. For example, invoking obj.methodName1() prints a message unique to that method such as "I Like Programming" . This structure allows methods to be modular and reusable within different program contexts.

Method definitions that return a value are used when the output needs to be used in further computations or operations. For instance, methods like calcAdd(int x, int y) return computed results that might be required for further processing or presentation (e.g., in a calculation chain). Methods that do not return a value, such as sayHello(String name), are used for executing actions that do not need further processing, like printing output directly to the console .

To create a Java program using a method without arguments and with a return value, define a method that does not take parameters but returns the desired outcome via the return statement. For example, a method square() calculates and returns the square of a fixed number. Upon invocation, it computes 10 * 10 and returns 100, which is then displayed using System.out.println() as "Squared value of 10 is: 100" .

The four types of method definitions in Java are characterized by their parameter and return types. Type 1 methods do not return any value and do not receive any parameters (e.g., void showWelcome()). Type 2 methods do not return any value but receive parameters (e.g., void sayHello(String name)). Type 3 methods return a value but do not receive any parameters, although this type is rarely used (e.g., int calcProduct()). Type 4 methods return a value and receive parameters (e.g., int calcAdd(int x, int y)).

Object instantiation in Java is crucial for invoking non-static methods as these methods are tied to specific class instances. The syntax involves creating an object using the new keyword followed by the class constructor (e.g., ClassName obj = new ClassName()). This object then allows access to the methods defined within the class using dot notation (e.g., obj.methodName()). This convention ensures that methods operate on the specific data encapsulated in the instance .

Java methods can be designed to accept parameters and return computed values by specifying the types of parameters they accept and the return type of the method. For instance, the method getSum(int i, int j) takes two integer parameters and returns their sum. Similarly, getProduct(int x, int y) accepts two integers, performs multiplication, and returns the result . These methods demonstrate how parameters are processed within the method body to produce and return computed values.

In Java, objects play a crucial role in method invocation as they encapsulate the methods within their classes. To call a method, an object of the class must first be instantiated (e.g., ClassName obj = new ClassName()). This object is then used to invoke methods defined in the class, which can vary in how they receive parameters or return values. For example, obj.showWelcome() calls a Type 1 method, while obj.calcAdd(x, y) calls a Type 4 method with parameters .

Non-static methods in Java are associated with instances of a class, meaning they require instantiation of an object to be accessed. This contrasts with static methods which belong to the class itself and can be invoked without creating an object. Non-static methods are used to maintain state information specific to an instance, enabling interaction with instance variables and other non-static methods (e.g., obj.sayHi(name)).

In Java, calling a method involves creating an object of the class and using the object to invoke the method. For Type 1 methods that receive no value and pass no arguments, e.g., obj.showWelcome(); For Type 2 methods that receive no value, but pass arguments, e.g., obj.sayHello(String name); For Type 3 methods that receive a value and pass no arguments, e.g., result = obj.calcProduct(); For Type 4 methods that receive a value and pass arguments, e.g., result = obj.calcAdd(x, y).

You might also like