4. Functions in Java

freepik.com With Functions, we can execute codes over and over again
so , we don't have to write same code again

As you know, firs we need a java file, a class and main method
There is an example class and main method
We are going to write our function in the class, but outside the main method


public class functions{
public static void main(String[] args) {

}
}


To write a function, first we need to write function's access modifier
This keyword gives function to accesibility from other classes
In this lection, We are not going to learn more about access modifiers

Then, We write "public", this means every other class can access our function
After this, we need to write second keyword, the return type
Functions executes some codes and if you want, they can return values
For example : F(x) = x+2
If we give this function to 5, it will return 7


Some Return Types

Until now, we have learned access keyword and return type keyword
We can write "public void" , But there is one more keyword
Now the last keyword we should write is name of the functions

Example function = public void print

And last, we need to put two parentheses and curly braces

Our Code Should Look Like This

public void print(){

}

We can write our codes inside this curly braces

public void print(){
int x = 5;
System.out.println(x);
}


How to call a function

To call a function, you should write it's name and put "()"
It will do it's job

Note : If you write your function in your main class it should have static keyword
"public static void print()"
Static is also a keyword, it means you can call this function in this class, without creating a object
We did not learn classes and object yet

Example function in java

function-java

Output

function-java-output

Returning value

We have just learned void type functions, that returns nothing
Now we are gonna look at functions with return type

First, we need to write a return type instead of "void"
Example function : public static int add(){}

How to return

To return a value from function, in function we need to use return keyword

After return keyword, we can write what we want to return
You can use the returned value, and assign this value

Example function with return

return-java

Output

return-java

How to enter variable to function

You can give variable to function
Function can use this variable and make it's job

As you remember, when we write a function, we add parentheses "()"
In this parentheses, we can declare a variable like "int number, String text"
And when you call a function, you must enter these variables to function

Example Function

java-function

Output

java-function
Home Page
Previous Lesson -> Printing
Photo from www.freepik.com
Burakhan Ünver