When writing Java we often times have to do repetitive tasks.
- Check that this user is logged in
- Get all the comments for a specific Post
- Create a new user
Methods help us manage these repetitive tasks
Imagine you have a huge machine. The machine has lots of things you can control. Like a lever, 3 buttons, a pulley and wheel and much more. All of this affects what happens inside the machine. It works by giving the machine some input. Now the input is transformed through the machine and in the end you get an output.
Imagine now that the machine is actually a method, the inputs in Java is called arguments, the things that control the method are called parameters, the output of the machine is called a return value. That might not make a lot of sense for now, but keep the metaphor of the machine, it will get handy later on!
Let's create a method that will double any number we give it!
public static int doubleNumber(int number) {
return number * 2;
}
Let's disect the code
public
andstatic
- these two keywords will later on become meaningful for you. But for now they are not so relevant.int
- Tells Java that the method will return an integerdoubleNumber
- This is the name of the method. It could be called anything(int number)
- Inside the paranthesis we put the parameters of the method.return number * 2;
- Inside the brackets is the code the method will run (called the body of the method).return
tells Java to return a value when the method runs. In this example number times two
A method does not have to return anything. If it does not return anything we use the keyword void
. As in the method is void(missing) of any return.
public static void sayHi() {
System.out.println("Hi!");
}
So what we have created now is a method that can double numbers. But how can i use it? How do i activate it somehow??
To activate a method is in Java called to call a method. So lets try and call doubleNumber
with a specific number!
int integerThatIsDoubled = doubleNumber(4);
System.out.println(numberThatIsDoubled); // 8
int integerThatIsDoubled
- is a variable that will capture the returned value from the methoddoubleNumber(4);
- Here we call the method by writing the name of the method followed by parenthesis. What is inside the paranthesis is called an argument (remember the machine input metaphor!)
Let's take another example!
public class main {
public static void main(String[] args) {
String fullname1 = getFullName("Sharmila", "Jensen");
System.out.println(fullname2); // Sharmila Jensen
String fullname2 = getFullName("Mads", "Hansen");
System.out.println(fullname2); // Mads Hansen
}
public static String getFullName(String firstname, String lastname) {
return firstname + " " + lastname;
}
}
Here we create a method called getFullName
that add's two string together with a space in-between. The method is called twice.
The parameters take on the value that the method is called with! Or put in another way they are substituted with the values the method is called with.
The first time the two parameters firstname
and lastname
is substituted for "Sharmila"
and "Jensen"
. The second time they are substituted for "Mads"
and "Hansen"
The returned value from calling the method is captured by fullname1
and fullname2
Method scope works in the same way as block scope. This means that a variable defined within a method is not accessible outside that method.
public static void sayHi() {
String hiString = "Hi!"
System.out.println(hiString);
}
System.out.println(hiString); // hiString is not defined within this scope!
After one hours of exercises its peer review time!
Solve this Parsons problem
The program will in larger terms
- Ask the user for a number of emojis to be printed
- With the number of emojis call a method to get the emojis to print
- Print the emojis
http://parsons.problemsolving.io/puzzle/8568731ac447431fb872b3f23d968391
Here is the output from running the program
Write a method that takes three integers as parameter, sums the integers and returns the result.
Write a method that takes a String as parameter and prints the String twice. The method does not return a value.
Implement a BMI calculator method. Identify the needed parameters and return type.
Write a method that takes a String as parameter and returns the String in full uppercase.
Write a method that takes a String as parameter and returns the amount of characters in the given String.
Lav en metode der ikke returnerer noget uden parameter kaldet throwDice
. Dvs. metoden returnerer ikke noget og modtager ingen input.
Metoden skal generere et tilfældigt tal ml. 1 - 6 og udskrive det på skærmen.
Hvis værdien er 6 skal du skrive 6, Lucky you 🎲
A customer from a flight booking website has asked for our help creating a specific part of their application:
When a user books a flight they write their firstname and surname, but when the ticket is printed a fullname should be displayed. It is our responsibility to create that.
Create a function called getFullname
that returns a fullname. It should have two parameters: firstname
and surname
.
String fullname = getFullname("Benjamin", "Hughes");
System.out.println(fullname) // "Benjamin Hughes"
firstname
and surname
should come from the user
On the flight website the user has the possibility to check a checkbox that indicates if the user wants to be adressed formally. They also specify their gender. Lets also change getFullname
to include support for formal name.
Create two extra parameters one that will contain the gender, the other that will indicate if the user wants to be adressed formally or not.
getFullname("Camilla", "Jensen", "female", true); // returns "Lady Camilla Jensen"`
getFullname("Benjamin", "Hughes", "male", false); // returns "Benjamin Hughes"
Now create a small program simulating a bit of a flight booking process using the method you just created.
Taken from https://github.com/HackYourFuture-CPH/JavaScript/blob/master/javascript1/week2/homework.md
Create a function (that you have to name) that has temperature as parameter. Based on the temperature it should return a string with what the user should wear. The temperature should come from the user
An example is:
String clothesToWear = youCreateThisFunctionName(18);
System.out.println(clothesToWear); // Prints out: "shorts and a t-shirt"
Taken from https://github.com/HackYourFuture-CPH/JavaScript/blob/master/javascript1/week2/homework.md
Another customer has contacted us. He works for a secret company that rimes with foogle. The customer works on their calendar application. They need some functionality to help with writing what weekday an event is held.
You specify how many days from today an event is being held. The function then figures out what weekday the event is being held. Here is an example:
Today is Sunday and the event is in 5 days. Therefore the event will be held on a friday.
// With todays weekday a tuesday
System.out.println(getEventWeekday(9)); // Prints "Thursday"
// With todays weekday a Friday
System.out.println(getEventWeekday(2)); // Prints "Sunday"
You should get the today's day from the system
Hint: use modulus, investigate how dates work in Java
Taken from https://github.com/HackYourFuture-CPH/JavaScript/blob/master/javascript1/week2/homework.md
Calculate the sum of digits of a number given by user.
E.g.
-
INPUT: 123. OUPUT: 6
-
INPUT: 12345. OUPUT: 15
A three digit number is called Armstrong number if sum of cube of its digit is equal to number itself.
E.g.- 153 is an Armstrong number because (13 )+(53 )+(33 ) = 153. Write all Armstrong numbers between 100 to 500.