Saturday, April 7, 2018

Methods in java


Methods are one of the most important part of coding , this article is all about methods in java
before  more further let see previous articles in series.



  1. Making Games With Java- Introduction
  2. Getting Everything you need for Java
  3. Introduction to Java Programming
  4. Basic data types and Variables in java
  5. Basic Data types and Variables in java - Continued...
  6. User Input using Scanner class in java
  7. Conditional Logic in java
  8. Loops in java
  9. Arrays in java
  10. Wrapper classes in java
What are methods in Java?
A method in Java can be defines as a bunch of code that is written to form a particular operation or function. There are quite a lot of methods that are in-built into the java programming language, an example being the System.out.println() method. Though it seems like just one simple line of code, it actually executes several statements in the background in order to do what it does.

To view these background programmes, type out a print statement, select it and right-click. Under the Navigate option, click Go to Source.



In this lesson, you will see how to create your own methods and invoke your methods into your code. This will help you to keep your code concise, organised and more readable.

Defining a Method
An average method consists of a method header and a method body. The method header is the statement that determines the values that the method returns and how easily it can be accessed in and out of a class.

The method header usually consists of the following:

  • Access Modifier: This determines how easily the method can be accesses. It is not necessary to add, but is usually advisable.
  • Return Type: The type of value the method can return. It’s possible for the method to return no value.
  • Method Name
  • Parameters: The type, order, and number of parameters a method requires to return a value. A method can have no parameters

The method body is defined by the pair of opened and closed curly brackets immediately after our method header and consists mainly of the code we want the method to run and the return keyword.

Now, let’s look at the method below:

public int add(int firstNumb , int secondNumb){
      int result =0;
      result = firstNumb+ secondNumb;
      return result;
}

If we’re to break it down into the components listed above:

  • public : access modifier
  • int: return type
  • methodName: the method name
  • int firstNumb, int secondNumb: parameters
  • result = firstNumb + secondNumb: code
  • return result: return statement

The above method, named add(), takes two integer parameters firstNumb and secondNumb, and returns their sum, which will be saved in the integer variable result.

Calling your Method

When your code is run, it will only read the code written within the main method. In order to implement our methods in the program, the method will have to be invoked or called into the main method.

The process of doing this is quite simple. When a method is called in our main method, control is transferred from the main method to the called method. The code the executes the code in the curly bracket and returns the set value.

For example, let us call the above mentioned method ‘add’ into our main method:

public class CalculationDemo {

	public static void main(String[] args) {
		CalculationDemo demo = new CalculationDemo();

		System.out.println("Will Add two number 10 , and 20");
		int r =demo.add(10, 20);
		System.out.println(r);
	}

	public int add(int firstNumb , int secondNumb) {
		int result =0;
		result = firstNumb+ secondNumb;
		return result;

	}

}
Result

Result:-
Will Add two number 10 , and 20
30

Void Method

So far, we can see that the type of data you set to the method is the type of data that it returns. If you create an integer method, it returns an integer. A string method will therefore return a string, a float method returns a float, a double method a double, and so on.
But there are times you don’t want your code to return any value. You just want it to perform a function and be done with it. This method is called a void method.

Also read : Basic and tricky java Interview Questions

Let’s recreate our last method, but make it void. Outside our last method, create this new method and call it addWithoutReturn:

	public void addWithoutReturn(int first , int second) {
		int result =first +second;
		System.out.println(result);
		 
	}

You can notice that it’s basically the same as our original method. The only difference is the absence of the return statement. This is replaced with a print statement, which causes it to automatically print out our variable when the method is called; so we don’t have to call a print statement in the main method.

Access Modifiers

Access Modifiers are keywords that determine how easily a method can be accessed or whether you can access a method within the class, the subclass or the java package. The three major access modifiers are:
  • Public
  • Private
  • default
  • Protected
If you choose not to give a modifier to a method or variable, it will only be visible in its class and the package.
Giving a public modifier will make your method or variable visible everywhere; even outside the java package. It is good practice not to do this, though, so that your variable will not be affected by an external user. It is more advisable to give your method a private or protected modifier.

A private modifier added before a method name will make it accessible to your class only. You won’t be able to access it anywhere outside your class; not even in the package. A protected modifier, on the other hand, will still allow your method to be seen everywhere, except outside the package. This is used mostly during inheritance and other related practices.

It is usually best to make your method or variable private, so that your method will not be manipulated by an external user. You can allow indirect access to your method or variable through the use of a getter and setter function. To access this; right-click your java file, click Insert Code, then click getter and setter. Choose the variable or method you need a getter and setter for, and click OK.

Access Modifiers grouped based on their Access Levels


Modifier
Class
Package
Sub-Class
World
Public
Access
Access
Access
Access
Protected
Access
Access
Access
No Access
No Modifier(default)
Access
Access
No Access
No Access
Private
Access
No Access
No Access
No Access


If we give a public modifier before any variable, it is visible everywhere in your project. It is good practice not to do this, though, so that it will not be affected by any other user. It is usually more advisable to declare your variable private or protected.
When your variable or method is declared private, it is only made available in the class. You cannot access it in any other class except its own. If you try to do so, it will give you an err because that class that cannot be accessed.
Protected is the least used among all these access modifiers, and so we won’t discuss it here because it is mostly used in Java Inheritance; so we will discuss that when we start on inheritance.


Next week, we’ll go a step further by talking about how to create classes.

Thanks for reading
Noeik

0 comments:

Post a Comment