Java Methods Making Subprograms
Learning Objectives Be able to read a program that uses methods. Be able to write a write a program that uses methods.
Program with static method public class FreshPrince { public static void main(String[] args) rap(); System.out.println(); } public static void rap() System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); Output: Now this is the story all about how My life got flipped turned upside-down
public: It can be called from outside the class public: It can be called from outside the class. For now we will make them all public. private: Can only be called from within the class. (Later) Default (No modifier) Can be accessed within the class and the package (folder). static You do not need to make an instance of the object to use it. For now our methods will be static which makes them Class Methods. If not defined as static, then it is not static. Everything is a value parameter! (type var, type var, type var) <modifier>[static] <return-type><subroutine-name>( parameter-list ) { <statements> return something } Start with a lowercase letter, and describes what the method is doing. return: Jumps out of the method and returns the answer. A method can have more than one return statement void: Nothing. Like a procedure int, double, char, String, int [], String [],Class name (Later): Defines the thing being returned. Method Syntax
Example Can be called from outside the class. import java.util.Scanner; // program uses class Scanner public class Addition { // main method begins execution of Java application public static void main( String args[] ) // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int number1, number2, sum; System.out.print( "Enter first integer: " ); // prompt number1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); // prompt number2 = input.nextInt(); // read second number from user sum = total(number1, number2); // add numbers System.out.printf( "Sum is %d\n", sum ); // display sum } // end method main public static int total(int first, int second) return first+second; } } // end class Addition Example Can be called from outside the class. Does not need to be instantiated, made into an object, to use. Returns an integer
Breaking down the method Can be called from outside the class Can be called without first making an object Returns an integer value public static int total(int first, int second) { return first+second; } Name of the method Parameters/ messages. Everything is a value parameter! Used to return a value from the method and kick out of the method
Control flow When a method is called, the program's execution... "jumps" into that method, executing its statements, then "jumps" back to the point where the method was called. public class MethodsExample { public static void main(String[] args) { message1(); message2(); System.out.println("Done with main."); } ... public static void message1() { System.out.println("This is message1."); } public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with message2."); } public static void message1() { System.out.println("This is message1."); }
Dry run public static void main(String [] args) { int x = 3, y = 5; fun(x, y); System.out.println(x + “ “ + y); } public static void fun(int a, int b) a+=b; b+=a; System.out.println(a + “ “ + b);
What are the values of a and b after the following? public static void main(String [] args) { int a = 3, b = 7; b = fun(a, b); a = fun(b, a); } public static int fun(int x, int y) y -= x; return y;
What does the following method do? Order of ops () [], x++, x--, !x, (type casting) *, /, % +, - <. <=, >= ==, != && || =, +=, -=, public static int process(double amt) { return (int) (amt * 100 + 0.5) % 100; } A) Returns the cent portion of amt. B) Returns the number of whole dollars in amt. C) Returns amt converted to the nearest cent D) Returns amt rounded to the nearest integer E) Returns amt truncated to the nearest integer
Dry run public static void main(String [] args) { int x = change(45); System.out.println(x); } public static int change(int value) if(value < 3) return value % 3; else return value % 3 + 10 * change(value/3);
Style Declare the main method as the first method. Declare other methods later.
First Method Program Song: Average Method. Write a program that has methods for chorus, first verse, second verse, … for a song of your choice. The main body will call each of the methods for the song Average Method. Write a program that has a method. In the method the user will input an unknown number of scores, then the average of the scores will be calculated and returned to the main body. The main body will then shows the average.
Dry Run
Second Method Programs F to C Sent a temperature in Fahrenheit and returns the temperature in Celsius. C = 5/9(F-32) Just the Factorials Sent a positive integer Returns its’ factorial. Hypotenuse The lengths of the sides are entered in the main body. Sent the lengths of two sides of a right triangle Returns the length of the hypotenuse
Voltage = current *Resistance Power = current *Voltage Third Method Program: For one of the following, write a class with the associated methods Electricity Class Resistance: given Voltage and Current Current: Given resistance and voltage Voltage: Given Resistance and current Power given: current and resistance Movement Class Distance: Sent the initial distance (d0), velocity (V0) , acceleration (a) and time (t) Return the distance covered Distance = d0 + Vo*t + (1/2) a t^2 Velocity: Sent Initial velocity (V0) , acceleration (a) and time (t) Calculates the velocity at the given time. Velocity = V0 + a*t Acceleration: Sent initial velocity V0, ending velocity V1 and time (t) Acceleration = (v1 – v0)/t Statistics Class Factorial Permutations Write a method that will find the number of permutations of n items taken r at a time. Permutations of n items taken r at a time= n!/(n-r)! Push add methods for the following. Combinations Write a method that will find the number of combinations of n items taken r at a time. Combinations of n items take r at a time= n!/((r!)(n-r)!) Voltage = current *Resistance Power = current *Voltage