0% found this document useful (0 votes)
44 views25 pages

Variables and Methods

This document discusses variables and methods in Java. It defines local, instance, and static variables and explains how they differ. Methods are described as reusable blocks of code that take in arguments, perform operations, and return outputs. The key parts of a method like return type, name, arguments, and body are outlined. A special main method is used to define the entry point for a Java program and must follow a specific signature. Examples of methods that perform operations like division and finding the maximum value are provided.

Uploaded by

Soll Haile
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)
44 views25 pages

Variables and Methods

This document discusses variables and methods in Java. It defines local, instance, and static variables and explains how they differ. Methods are described as reusable blocks of code that take in arguments, perform operations, and return outputs. The key parts of a method like return type, name, arguments, and body are outlined. A special main method is used to define the entry point for a Java program and must follow a specific signature. Examples of methods that perform operations like division and finding the maximum value are provided.

Uploaded by

Soll Haile
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
You are on page 1/ 25

Lecture 6

Methods

Variables and Methods


Variables
 are memory location which is used for
storing any value.
 Java has three kinds of variables
1. Local Variables
2. Instance Variables
3. Static Variables
Variables (Local Variables)
 Local variables in Java are declared in
constructor, method, or blocks.
 This variable is only visible in the blocks or
method in which they are declared they
can't be used outside the methods or
block in which they are declared.
 Local variables are created when the
method, constructor or block is entered
Variables (Instance Variables)
 Instance variables in Java are declared
outside a method, constructor or block.
 They are declared in a class and are
available for an entire class method,
constructor and blocks.
 Instance variables are created when an
object is created and destroyed when the
object is destroyed.
Variables (Static Variables)
 Static variables in Java are also declared
in the class outside the method,
constructor or any block
 A static/class variable can be defined
using the static keyword.
 These are loaded and initialized when
class is loaded.
 There exists only one copy of class
variable
The Concept of a Method
 Methods also known as functions or procedures.

 Methods are a way of capturing a sequence of


computational steps into a reusable unit.

 Methods can accept inputs in the form of


arguments, perform some operations with the
arguments, and then can return a value that is
the output, or result of their computations.

inputs outputs
method
Square Root Method
 Square root is a good example of a method.

 The square root method accepts a single number as an


argument and returns the square root of that number.

 The computation of square roots involves many


intermediate steps between input and output.

 When we use square root, we don’t care about these


steps. All we need is to get the correct output.

 Hiding the internal workings of a method from a user but


providing the correct answer is known as abstraction
Declaring Methods

 A method has 4 parts: the return type, the


name, the arguments, and the body:
type name arguments

double sqrt(double num) {


// a set of operations that compute
body
// the square root of a number
}

 The type, name and arguments together is


referred to as the signature of the method
The Return Type of a Method

 The return type of a method may be


any data type.

 The type of a method designates the


data type of the output it produces.

 Methods can also return nothing in


which case they are declared void.
Return Statements
 The return statement is used in a method to output
the result of the methods computation.

 It has the form: return expression_value;

 The type of the expression_value must be the


same as the type of the method:
double sqrt(double num){
double answer;
// Compute the square root of num and store
// the value into the variable answer
return answer;
}
Return Statements

 A method exits immediately after it


executes the return statement

 Therefore, the return statement is


usually the last statement in a method

 A method may have multiple return


statements. Can you think of an
example of such a case?
Answer

 Example:
int absoluteValue (int num){
if (num < 0)
return –num;
else
return num;
}
void Methods
 A method of type void has a return statement
without any specified value. i.e. return;

 This may seem useless, but in practice void is


used often.

 A good example is when a methods only


purpose is to print to the screen.

 If no return statement is used in a method of


type void, it automatically returns at the end
Method Arguments

 Methods can take input in the form of


arguments.

 Arguments are used as variables inside the


method body.

 Like variables, arguments, must have their


type specified.

 Arguments are specified inside the paren-


theses that follow the name of the method.
Example Method

 Here is an example of a method that


divides two doubles:

double divide(double a, double b) {


double answer;
answer = a / b;
return answer;
}
Method Arguments

 Multiple method arguments are


separated by commas:
double pow(double x, double y)

 Arguments may be of different types


int indexOf(String str, int fromIndex)
The Method Body
 The body of a method is a block
specified by curly brackets. The body
defines the actions of the method.

 The method arguments can be used


anywhere inside of the body.

 All methods must have curly brackets


to specify the body even if the body
contains only one or no statement.
Invoking Methods

 To call a method, specify the name of


the method followed by a list of comma
separated arguments in parentheses:
pow(2, 10); //Computes 210

 If the method has no arguments, you


still need to follow the method name
with empty parentheses:
size();
Static Methods
 Some methods have the keyword
static before the return type:
static double divide(double a, double b) {
return a / b;
}
main - A Special Method

 The main method is where a Java program


always starts when you run a class file with
the java command
 The main method is static has a strict
signature which must be followed:
public static void main(String[] args) {
. . .
}
main continued
class SayHi {
public static void main(String[] args) {
System.out.println("Hi, " + args[0]);
}
}
 When java Program arg1 arg2 … argN is typed on
the command line, anything after the name of the class file
is automatically entered into the args array:
java SayHi Sonia

 In this example args[0] will contain the String "Sonia",


and the output of the program will be "Hi, Sonia".
Example main method
class Greetings {
public static void main(String args[]) {
String greeting = "";
for (int i=0; i < args.length; i++) {
greeting += "Jambo " + args[i] + "! ";
}
System.out.println(greeting);
}
}

 After compiling, if you type


java Greetings Alice Bob Charlie
prints out "Jambo Alice! Jambo Bob! Jambo Charlie!"
Recursive Example
class Factorial {
public static void main (String[] args) {
int num = Integer.parseInt(args[0]));
System.out.println(fact(num));
}

static int fact(int n) {


if (n <= 1) return 1;
else return n * fact(n – 1);
}
}

 After compiling, if you type java Factorial 4


the program will print out 24
Another Example
class Max {
public static void main(String args[]) {
if (args.length == 0) return;

int max = Integer.parseInt(args[0]);


for (int i=1; i < args.length; i++) {
if (Integer.parseInt(args[i]) > max) {
max = Integer.parseInt(args[i]);
}
}
System.out.println(max);
}
}

 After compiling, if you type java Max 3 2 9 2 4


the program will print out 9
Summary
 Methods capture a piece of computation we wish to
perform repeatedly into a single abstraction

 Methods in Java have 4 parts: return type, name,


arguments, body.
 The return type and arguments may be either
primitive data types or complex data types (Objects)
 main is a special Java method
 main has a strict signature that must be followed:
public static void main(String args[])

You might also like