Method is also called as function in C/C++, but there are many differences between java and c++.
Method: A method is a group of statements or collection of statements are grouped to perform actions as well as operations. As you know that main method is also a method in java program that is called by the JVM.
A method can be called by two ways :
Method: A method is a group of statements or collection of statements are grouped to perform actions as well as operations. As you know that main method is also a method in java program that is called by the JVM.
A method can be called by two ways :
- The first way is to creating object of class that belongs to the method .
- The second way is , by declaring as static method .
To know about the static keyword click me..😄😄
Syntax of a method :
public static int methodname(int a )
{
// This is the body to perform action as you like
}
The syntax contains:
public static: This portion called as modifier , so the question arises what is modifier.
int: It is return type to return some value.
methodname: methodname is the name to call it by using it name.
int a : It is the parameter of method .
and the last thing is the body of that method to perform different type of actions.
you can say that :
modifier returntype methodname (parameter)
{//body}
So lets take an example of method:
class number
{
public static void main(String as[])
{
System.out.println("This is main");
show();
}
public static void show() //I used static keyword otherwise it will throw error.
{System.out.println("This is show");}
}
Output :
This is main
This is show
If you compile this program you will get an error because static member based on rules
"A non-static method cannot be referenced from static context"
So you must use static keyword other wise you will use that method by creating object of that class
like :
class number
{
public static void main(String as[])
{
System.out.println("This is main");
number m=new number();
m.show(); //calling method by creating object of that class
}
public static void show() //I used static keyword otherwise it will throw error.
{System.out.println("This is show method");}
}
The output is same as above appear , this is the second way to call method by using object of class.
What is Static Keyword..?? What is object..??
Why we use Static Keyword..?? What is class..??
Method Examples..!! What is loop..??
What is for loop..?? What is while and do-while loop..??
How many Types of loop...??
No comments:
Post a Comment