Professional Documents
Culture Documents
Lesson 5 Methods
Lesson 5 Methods
Lesson 5 Methods
Methods/ Functions()
Today’s Agenda
• Topics:
• Introduction
• Static Methods
• Method Declarations
• Method Calls
• Scope of Declarations
• Method Overloading
• Random numbers
• Reading:
• Java how to program Late objects version (D & D)
• Chapter 5
• The Java Tutorial
• https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Introduction
• A method is a block of code that performs a specific task.
• The method in Java or Methods of Java is a collection of statements that
perform some specific task and return the result to the caller.
Advantage of Method
• Code Reusability
• Easy modification
• Code readability
• Code Optimization
Method Declaration
• The method declaration provides information about method attributes, such as
visibility, return-type, name, and arguments.
• It has six components that are known as method header, as we have shown in
the following figure.
Types of Method
• There are two types of methods in Java:
• Predefined Method
• User-defined Method
Predefined Method
• The method that is already defined in the Java class libraries is known as
predefined methods/standard library method/built-in method.
• We can directly use these methods just by calling them in the program at any
point.
• Some pre-defined methods are length(), compareTo(), main(), print(), max(),
sqrt(), etc.
• When we call any of the predefined methods in our program, a series of codes
related to the corresponding method runs in the background that is already
stored in the library.
• Each and every predefined method is defined inside a class.
• Such as print() method is defined in the java.io.PrintStream class. It prints the
statement that we write inside the method. E.g., print("Java"), it prints Java on
the console.
Predefined Method
• Example 1: Java Standard Library Method
• public class Main {
• public static void main(String[] args) {
• // using the sqrt() method
• System.out.print("Square root of 4 is: " + Math.sqrt(4));
• }
•}
User-defined Method
• The method written by the user or programmer is known as a user-defined method.
• These methods are modified according to the requirement.
• We have defined a method named add() that sum up the two numbers.
• Therefore, the method adds the value of a and b and store it in the variable s
and returns the sum.
Predefined Method
• Example 3: Java Standard Library Method using a for loop for code reusability.
• public class Main {
• // method defined
• private static int getSquare(int x){
• return x * x;
• }
• // method call
• int result = getSquare(i);
• System.out.println("Square of " + i + " is: " + result);
• }
• }
• }
Static Method
• A method that has static keyword is known as static method.
• In other words, a method that belongs to a class rather than an instance of a
class is known as a static method.
• We can also create a static method by using the keyword static before the
method name.
• The main advantage of a static method
• we can call it without creating an object.
• It can access static data members and also change the value of it.
• It is used to create an instance method.
• It is invoked by using the class name.
• The best example of a static method is the main() method.
Static Method Con’t
• Example of static method
• As mentioned earlier, a method can also have any number of parameters. For
example;
• // method with two parameters
• // code
•}
• int addNumbers(){
• // code
•}
Method Parameters Con’t
• If a method is created with parameters, we need to pass the corresponding
values while calling the method.
• For example;
• // calling the method with two parameters
• addNumbers(25, 15);
• addNumbers()
Method Parameters Con’t
• Example 1: Method Parameters • public static void main(String[] args) {
• class Main { • // create an object of Main
• // method with no parameter
• Main obj = new Main();
• public void display1() {
• // calling method with no parameter
• System.out.println("Method without
• obj.display1();
parameter");
• System.out.println("Method with a • }
single parameter: " + a); •}
• }
Method Parameters Con’t - Explanation
• The parameter of the method is int. Hence, if we pass any other data type
instead of int, the compiler will throw an error. It is because Java is a strongly
typed language.
• The argument 24 passed to the display2() method during the method call is
called the actual argument.
• The type of actual arguments and formal arguments should always match.
Advantages of using methods in Java:
• Reusability: Methods allow you to write code once and use it many times, making your
code more modular and easier to maintain.
• Abstraction: Methods allow you to abstract away complex logic and provide a simple
interface for others to use. This makes your code more readable and easier to
understand.
• Improved readability: By breaking up your code into smaller, well-named methods,
you can make your code more readable and easier to understand.
• Encapsulation: Methods allow you to encapsulate complex logic and data, making it
easier to manage and maintain.
• Separation of concerns: By using methods, you can separate different parts of your
code and assign different responsibilities to different methods, improving the structure
and organization of your code.
• Improved modularity: Methods allow you to break up your code into smaller, more
manageable units, improving the modularity of your code.
• Improved testability: By breaking up your code into smaller, more manageable units,
you can make it easier to test and debug your code.
• Improved performance: By organizing your code into well-structured methods, you
can improve performance by reducing the amount of code that needs to be executed
and by making it easier to cache and optimize your code.
1.Introduction
• Best way to develop and maintain a large program is to
construct it from small, simple pieces.
• It is called divide and conquer
• Normally, methods are called on specific objects
• Example: toUpperCase() method from a string object.
• declare, construct, and initialize a String object
• Note: (We will cover the details on creating objects later)
String s1 = new String("abc");
String s2 = s1.toUpperCase();
1.Introduction
Instance Methods String s2 = s1.toUpperCase();
• Instance Methods:
• Operations we can apply to objects to examine/change their state
• We use a variable name to specify which object to call a method on
(the object it refers to)
• we write the name of the variable, followed by a period (a separator), followed
by the name of the method, all followed by a pair of open/close parentheses
(separators/delimiters).
• Example: the toUpperCase method is called in the form
object-reference.toUpperCase()
• returns as a result a reference to a new String object whose state is the upper-case
version of the state of the object to which object-reference refers.
1.Introduction String str = new String("abcd");
String Methods
• Some popular methods in the String class:
returnVar = methodName(parameters);
• Using an object’s variable name followed by a dot (.) and the method name to call a
non-static method of the object
returnVar = an_object.methodName(parameters);
• Using the class name and a dot (.) to call a static method of a class
String s2 = s1.toUpperCase();
returnVar = className.methodName(parameters);
System.out.println(Math.min(20, 1));
2.Static Methods
The Math class
2.Static Methods
The Math class
• Class Math declares two constants
• Math.PI (3.141592653589793) is the ratio of a circle’s circumference to its diameter
• Math.E (2.718281828459045) is the base value for natural logarithms (calculated with
static Math method log)
• These constants are declared in class Math with the modifiers public, static
and final.
• public allows you to use these fields in any other classes
• static allows them to be accessed via the class name Math and a dot (.) separator
• final indicates that they are constants—value cannot change after they are initialized.
• A class’s variables are sometimes called fields.
2.Static Methods
The Main method
• Why Is the method main declared static?
• When you execute the Java Virtual Machine (JVM) with the java
command, the JVM attempts to invoke the main method of the class
you specify.
• i.e. This is the line at which the program will start executing.
• All Java applications begin execution by calling main.
• Declaring main as static allows the JVM to invoke main without
creating an object of the class.
• If we omit static keyword before main, Java program will successfully
compile but it won't execute.
3.Method Declarations (static methods)
Method Header
• Method header: Modifiers, return type, method name and parameters
For now, we begin every method declaration
• A public method is “available to the public” with the keywords public and static
• It can be called from methods of other classes
• static methods: can be called without creating an object of class.
• Method name : Style convention :
• Class names, method names and variable names are all use the same camel case naming
scheme (e.g. toUpperCase)
• return type : Specifies the type of data a method returns
• void : perform a task but will not return any information
public static void methodName1(int parameter) { ... }
public static int methodName2(int parameter) { ... }
Example
• Example: determines and returns the largest of two double values
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter 2 numbers separated by
spaces: ");
double num1 = input.nextDouble();
double num2 = input.nextDouble();
double result = max_of_2(num1, num2);
System.out.println("Maximum is: " + result);
}
26 Celsius is 78 Fahrenheit
Exercise 1
• Consider the following code fragment in Main:
int f = 98, c = 26;
System.out.printf("%d Fahrenheit is %d Celsius%n%n", f, celsius(f));
System.out.printf("%d Celsius is %d Fahrenheit%n%n",c, fahrenheit(c));
parameter
public static void method(int n) {
int n =0;
int x = 5;
} Local variable
field
public class L05Code02 {
public static int x = 1; //a field
public static void main(String[] args) {
int x = 5; //method's local variable x shadows field x
System.out.printf("local x=%d%n", x);
method();
} Local variable
System.out.println(Math.max(10, 12));
System.out.println(Math.max(10.5, 12.5));
12
12.5
6.Method Overloading L05Code02.java
Rules
• Compiler distinguishes overloaded methods by their signatures
• A combination of the method’s name and the number, types and order of its
parameters, but not its return type.
• The return type of the method is NOT part of the signature
• The compiler must be able to determine which version of the method is being
invoked by analysing the parameters
Argument Promotion
• Argument promotion—converting an argument’s value, if possible, to the
type that the method expects to receive in its corresponding parameter
• promotion rules: int -> double, float -> double etc
sum(20, 20);
public static void sum(int a, double b){
System.out.println(a+b);
System.out.println("Two args");
}
public static void sum(int a,int b,int c){
System.out.println(a+b+c);
System.out.println("Three args"); 40.0
} Two args
• Note:
• Literal integer values are treated as type int
• Literal floating-point values are treated as type double
Exercise 2 - Overloading
• Valid or invalid?
• Case 1: int mymethod(int a, int b, float c)
int mymethod(int var1, int var2, float var3)
2 4 3 5 1 2 0 0 3 0 3 5 0 2 5 1 2 1 2 0 3
L05Code03.java
7.Random Numbers
Scaling and Shifting
• Generalized scaling and shifting of random numbers:
SecureRandom randomNumbers = new SecureRandom();
number = shiftingValue + randomNumbers.nextInt(scalingFactor);
• where shiftingValue specifies the first number in the desired range of consecutive
integers and scalingFactor specifies how many numbers are in the range
• Example: Simulating dice
• Valid values: 1, 2, 3, 4, 5, 6
randomNumbers.nextInt(6)
0 1 2 3 4 5
1 + randomNumbers.nextInt(6)
1 2 3 4 5 6
Exercise 3
• Complete the code to allow a user to guess a number (from 0 to 10) that will
be randomly generated by computer.
__________________