- Get link
- X
- Other Apps
Method
Method are truly heart and soul of java program.A method is a self contained block of code that performs a specific task. They provide a way of defining the behavior of an object either the purpose of object.
They are same as functions in C language. Method is chunk of code which is reusable, manageable and can calculate complex problem within some limited lines of code. A method follows the approach of write once and use anywhere. You can create a method in a class and can call this method from other class using objects or you can use static methods.
Note: The void is just a datatype to define method which returns no value. As you can see in examples given below, the methods are returning nothing so they are defined using void return type.No void method can be treated as main even if these method are static too.
Method Declaration and Definition
In the method definition, we define method so it can be later used in program.If you want to define method in main class remember, Method can be defined inside a class but outside the main method. As a method can not contain the definition of other method.
Definition of method is written in following format:
Method Header
In the method header we write following things:
1)Access Modifiers: These are used to control the scope of method. There are following modifiers: default, public, private and protected. We will discuss about these modifiers in Encapsulation.We can use public modifier when we want our method to be accessed from anywhere.
2) Return type: It is the datatype of method. Lets suppose your method outputs an integer value after calculation then you can give int as the return type. If your method is not returning any value then use void as return type. The void type is used for returning no value or null value.
3)Method Name: Give a name to method. Make sure the method name is relatable to its logic.For example, if your method is calculating sum of numbers, give it name as sumOfNumbers. In java , we use camel case to name methods and variable. In camel case, the first word is in small letters but the second word always starts with the capital letter. Like, myClass, myMethod, sumOfNumbers etc.
4)Parameters or Arguments: Parameters or arguments are the inputs that a method takes to perform operations and give result.These are optional.A method may or may not has parameters. Remember, you can omit parameters but () these brackets are mandatory in method definition syntax.
The opening and closing curly brackets are must to write the method body.
Method Body
Method body can contain declarations of variables, constants.Statements can also be written here. Logic means to write the statements which calculates something.
for example:
public int sum(int a, int b)
{
int c=a+b;
return c;
}
Here, public is an access modifier. You can omit writing modifier. When you omit modifier, java uses its default access modifier,
Types of methods
There are two types of methods, as follows:
1) Static methods
Static methods are accessible from anywhere. They can be accessed from any other class or package.Methods can defined as static by using static keyword like in main method. These methods do no require objects to access them.
Syntax:
acessModifire static returnType methodName(parameters)
{
//statements and declarations
}
for example:
public static int sum(int a, int b)
{
int c= a+b;
return c;
}
Here, static will allow the method to be called easily from anywhere without using object and the dot operator.
Example: This will illustrate the static method and its use.
Write a program to print following pyramid pattern on screen using static method.
1
3 3
5 5 5
7 7 7 7
In the above example,
- First we created a class and named it "PatternsUsingStaticMethod".
- In the main method, we defined a variable named "number", this variable is getting an input from user using the Scanner input method. This variable is used to get the number of lines of pyramid to be printed on screen. As you can see in output Console, 5 lines to be printed as user gave 5 as input.
- In line 11 of program, we are invoking the static method, it is written in italic because static methods are special methods, they are powerful and can be accessed from anywhere without using any object of class. So, we are just calling it by using its name and passing one parameter "number" as this method require a number in input.
- In line 15 , we are defining a static method named "pyramidPattern", this method takes an input as argument or parameter named "num". When method is called from main method, it will assign the value of "number " variable to its "num" variable.
- The definition , code or statements of method is written in the body of method.This body starts an ends within curly braces.
- We have defined a variable "count" to hold the numbers to be printed in the pattern. It is initialized with 1.
- We used nested for loops. Outer for loop has control variable "i" which will control the rows or lines to be printed. Inner loop has variable "j" which controls the numbers to be printed in columns or we can say it will control how many a numbers are printed in a single line.
- Outer loop runs till "i" is less than or equal to "num". Inner loop runs until j is less than or equal to "i" of outer loop.It keeps increasing the value of "i" by 1 using i++ in each iteration.
- Inner loop prints the value of count each time it runs.When condition becomes false and j is greater than i, then the next statements written in line number 26 & 27 executes.
- Line 27 increase the value of count by 2 ,it is in outer loop so each time when control moves to next line, the next odd number will get printed as initially count is 1 , so count=count+2; is 1+2=3, and so on.
- Line 28, make the control jumps to next line.It is print statement to print in next line used like new line character "\n". We can also use "\n" , we will use that in next example.
- Now, put the value of number as 5 and try to analyse the output.
Tip: For better understanding of loops and their working. Solve the loops in a notebook first. Outer loop is closed after inner loop.
2) Non-static method
These are methods which have limited scope. To invoke these methods you need object of the class which contain the method definition and have to call method using object and dot(.) operator.
Syntax:
accessModifire returnType methodName(parameters)
{
//statements and declarations
}
for example,
public int sum(int a, int b)
{
int c= a+b;
return c;
}
Write a program to print following pyramid pattern on screen using non-static method.
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
In the above example,
- First we created a class and named it "PatternsUsingNonStaticMethod".
- In the main method, we defined a variable named "number", this variable is getting an input from user using the Scanner input method. This variable is used to get the number of lines of pyramid to be printed on screen. As you can see in output Console, 5 lines to be printed as user gave 5 as input.
- In line 15 of program, we created an object "obj" of class using new keyword. Then in line 16 , we used this "obj" object to call method "reversePyramidPattern" using a dot(.) operator. This method requires an input of "number" variable, so we passed "number" here.
- In line 21 , we are defining a non-static method named "reversePyramidPattern", this method takes an input as argument or parameter named "num". When method is called from main method, it will assign the value of "number" variable to its "num" variable.
- The definition , code or statements of method is written in the body of method.This body starts an ends within curly braces.
- We used nested for loops. Outer for loop has control variable "i" which will control the rows or lines to be printed. Inner loop has variable "j" which controls the numbers to be printed in columns or we can say it will control how many numbers are printed in a single line.
- We have to print reverse pyramid. That is why "i" is initialized with num's value. Outer loops runs until "i" is greater than 0.It keeps decreasing the value of "i" by 1 using i-- in each iteration.
- Inner loop prints the value of variable "j"each time it runs.When condition becomes false and j is greater than i, line 31 executes and print the next values in new line.
- Now, put the value of number as 5 and try to analyse the output.
Note: Non-static methods are normal methods and they are used frequently.You should use static methods whenever,
- The code in the method is not dependent on instance creation and is not using any instance variable.
- A particular piece of code is to be shared by all the instance methods.
- The definition of the method should not be changed or overridden.
- you are writing utility classes which should not be changed.
Difference between static and non-static methods
Static Methods
- A static method is a method that belongs to a class, but not to an instance of that class and this method can be called without the instance or object of that class.
- In static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables
- Static method uses compile time or early binding.
- Static method cannot be overridden because of early binding.
- In static method, less memory is use for execution because memory allocation happens only once, because the static keyword fixed a particular memory for that method in RAM.
Non-static Methods
- Every method in java is a non-static method, but these method must not have static keyword before method name. Non-static methods can access any static method and static variable without using the object of the class.
- In non-static method, the method can access static data members and static methods as well as non-static members and method of another class or same class.
- Non-static method uses runtime or dynamic binding.
- Non-static method can be overridden because of runtime binding.
- In non-static method, much memory is used for execution because here memory allocation happens when the method is invoked and the memory is allocated every time when the method is called.
Experiment: Practice creating more static and non static methods by writing your own programs.
Keep learning! Happy Coding!
- Get link
- X
- Other Apps
Comments
Post a Comment
If you have any doubt, ask here