Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Computer Programming 2 Lec

Topic : Methods

What is a Method ?
 Methods are truly the heart and soul of Java programs.
 They serve the same purpose in Java that functions do in C, C++, and Pascal-only the
terminology is different.
 All execution that takes place in an application takes place within a method. It is only by
combining multiple dynamic methods that large-scale Java applications are written.

Declaring a Method

The general form for declaring a method is :

Access_specifier modifiers return_value nameOfMethod ( parameters ) throws ExceptionList {


method’s body }
Example:
public static void printText( String txt ) {
System.out.println(txt); }

Parts of a Method
a. Method Signature. Specifies a method’s name, its return type, its modifiers and access
modifiers, the list of parameters it requires and the type of exceptions it can throw.
b. Body. The method’s body is where the work of a method is performed. This body is defined by
a block of statements enclosed within curly braces {}.

Access Specifiers. Specifies the access level of the method from other methods or classes. Keywords
are: private, public, or protected. If access specifier is omitted then the default access restrictions are
imposed. The default access type is sometimes referred to as “friendly” or “package” access Methods
declared this way are only accessible to other classes within the same package.

Modifiers. Keyword that specifies whether a method is a static, a final, or an abstract method.
 Static methods are methods that belong to a class and not to an instance of a class. Static
methods are often referred to as class methods, as opposed to instance methods.
 Abstract method is a method that is declared but not implemented in the current class. The
responsibility for defining the body is passed on the subclasses of the current class.
 Final method is a method that cannot be overridden by subclasses of the current class.

Returning Information. When a method completes its execution, it can return a primitive value, an
object reference, or nothing at all to the method that called it. The return type in the method signature
defines what is returned. Methods that do not return anything must be declared with a return type of
void.

Parameters. The parameter list in a method signature is the list of information that will be passed to
the method, whenever it is called. A parameter list takes the following form and can consist of as many
parameters as you want: ( DataType variableName, DataType variableName, . )

Example:
public class SumOfNos {
public static int calcSum( int n1, int n2, int n3 ) {
int sum; sum = n1 + n2 + n3;
return sum;
}
public static void main( String [] args ) {
System.out.print(“Sum is “ + calcSum(1,2,3); }
}
Catching and Throwing Exceptions
An exception is a special type of object that is created when something goes wrong in a method. The
rest of the program is notified about a problem when a method performs an action called throwing an
exception. When an exception is thrown, it up for the program to catch the exception and handle it.

Types of Exceptions
1. Checked Exception is an exception that must be handled or declared in the throws
clause of a method where a method call can produce it. These exceptions represent
problems that might occur in a perfect program. Because these errors are usually
beyond programmer’s control, the Java compiler requires developers to provide
ways to handle them if they do occur.

Common Java Checked Exceptions:


• AWTException
• ClassNotFoundException
• FileNotFoundException
• IOException
• ParseException
• SQLExceptio

2. Unchecked Exceptions are exceptions that should not occur in a correct program
and developers are not required to handle or declare them in the method’s throws
clause.

Common Java Unchecked Exceptions:


• ArithmeticException
• ArrayIndexOutOfBoundsException
• ArrayStoreException
• NullPointerException
• NumberFormatException
• SecurityException
• StringIndexOutOfBoundsExceptions
Implementing Methods in a Java Program

Problem:
Create a program that will accept three integers. The same program must be able to display the
following output once the three integer values had been entered.
- Sum of three numbers
- Highest value among the three numbers

// Import Section
import java.util.Scanner;
// Class declaration
public class UsingMethods {
// Methods
static float calcSum( float v1, float v2, float v3) {
float sum = 0;
sum = v1 + v2 + v3;
return sum;
}
static float findHighest( float v1, float v2, float v3) {
float highest = 0;
if ( v1 > v2 ) highest = v1;
else highest = v2;
if ( v3 > highest ) highest = v3;
return highest;
}

// Main Method
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
float n1, n2, n3, sum, highest;
char ans;
do {
// Accept all numbers
System.out.println("Enter three Numbers: ");
System.out.print("\t1st Number: "); n1 = input.nextFloat();
System.out.print("\t2nd Number: "); n2 = input.nextFloat();
System.out.print("\t3rd Number: "); n3 = input.nextFloat();
// Get Sum of three numbers
sum = calcSum( n1, n2, n3 );
highest = findHighest( n1, n2, n3 );
// Display the results
System.out.println("Results: ");
System.out.println("\tHighest Number: " + highest);
System.out.println("\tSum : " + sum);
// Display message and accept response
System.out.print("\n\nType Y to Try again, or N to exit: ");
ans = input.next().charAt(0);
} while (ans == 'Y');
}
}

You might also like