Method is a sub block of a class that contains logic of that class.
logic must be placed inside a method, not directly at class level,
if we place logic at class level compiler throws an error.
So class level we are allowed to place variables and methods.
The logical statements such as method calls, calculations and printing related statements must be
placed inside method,
because these statements are considered as logic.
Syntax of method:
accessmodifier keyword(s) returntype methodname(){
write the logic //method body
}
1.Method Prototype:
The head portion of the method is called method prototype.
Ex:public static void main(String args[]) // ->method prototype.
2.Method body and logic:
The "{ }" region is called method body, and the statements placed inside method body is called logic.
3.Method parameters and arguments:
The variables declared in method parenthesis "( )" are called parameters.
We can define method with 0 to n number of parameters.
The values passing to those parameters are called arguments.
In method invocation we must pass arguments according to the parameters order and type.
syntax of parameterised method:
accessmodifier keyword(s) returntype methodname(datatype p1,datatype p2,datatype p3..){logic}
ex:
public static void add(int a, float b){ // ->method prototype. int a, int b are parameters
float sum=a+b;
}
//calling the add() method.
public static void main(String[] args){
add(5,10.5F); //calling/invocation of the parameterised method
add(15,20.2F);
4:Method signature:
The combination of method "name + parameters " is called method signature
In the above program add(int a, float b) and main(String args[]) are method signatures.
5. Method return type:
The keyword that is placed before method name is called method return type.
It tells to compiler and JVM about the type of the value is returned from this method after its execution
If nothing is return by method then we can use "void" keyword which specifies method returns nothing.
return type keywords:
void,boolean,char,byte,short,int,long,float,double,String,interface,classname,arrayname[],collectiontypes, map.
Methods are two types:
1)static method
2)nonstatic method
Static Methods in Java
It is common to often refer to static methods in Java as class methods. The reason is that the static members are associated with the classes and their objects. Similar to static variables, static methods can also be invoked using the class name. There are some important points that you need to consider when you work with static methods in Java. These are -
- The static methods of a particular class can only access the static variables and can change them.
- A static method can only call other static methods.
- Static methods can’t refer to non-static variables or methods.
- Static methods can’t refer to “super” or “this” members.
Also, often you will notice that the main method in Java is defined as static. This is so because you don’t need an object to call the main method in Java. If you have defined the main method in Java as non-static, then the Java Virtual Machine (JVM) would have first created an instance for the main class and then called the main method using that instance which would lead to unnecessary memory usage. Moreover, there are tons of static methods defined in the Wrapper Classes and Utility Classes in Java.
Any static method can call any other static method in the same file or any static method in a Java library like Math.static methods can be called inside nonstatic/instance methods also.
Syntax:
accessmodifier static void methodName(){
logic
}
The static method has two types:
1) non-parameterized static method: if a method does not contain any parameters inside the parenthesis ()then that method is called a non parameterized static method
access modifier static void methodName(){
logic
}
parameterized static method: if a method contains parameters inside the parenthesis() then that method is called a parameterized static method
syntax:
access modifier static void methodName(datatype p1,datatype p2,...){
logic
}
Note: if you don't write a void keyword in the method signature line then static method syntax?
access modifier static datatype methodname(){
logic;
return value;
}
accessmodifier static datatype methodname(datatype p1, datatype p2,.....){
logic;
return value;
}
Next, consider the below example.
class Test{
int counter;
public static void increment(){
counter++;
System.out.println("Current value of Counter is: " + counter);
}
}
class Main{
public static void main(String args[]){
Test.increment();
}
}
The above program will generate an error. This is so because it has tried to access a non-static variable called counter inside a static method called increment().
Let’s try to use the same example but this time, you will specify the counter variable as a static variable.
class Test{
static int counter;
public static void increment(){
counter++;
System.out.println("Current value of Counter is: " + counter);
}
}
class Main{
public static void main(String args[]){
Test.increment();
Test.increment();
Test.increment();
}
}
Ans)staticmethodname();
Q)how can you call static void parameterised method under main() in same class?
Ans)staticmethodname(p1value,p2value,p3value..);
Q)how can you call return type static method() under main() in the same class?
datatypeofthemethod varaiblename=returntypestaticmethod();
System.out.println("value is"+varaiblename);
(or)
how to call returntype static method in printstatement?
Ans)System.out.println("value is"+returntypestaticmethod());
Q)how can you access static variable in same class under any static/nostatic/main method?
Ans)directly call static variable
================================================
Scenrio:2 how to call one class static members in another class of same package
Q)How can you access one class static variable in another class?
Ans)classname.staticvariable;
Q)how can you call one class static void method in another class?
Ans)classname.staticmethod();
Q)how can you call static void parameterised method under any method/main() in another class?
Ans)classname.staticmethodname(p1value,p2value,p3value..);
Q)how can you call return type static method() under any method/main() in another class?
datatypeofthemethod varaiblename=classname.returntypestaticmethod();
System.out.println("value is"+varaiblename);
(or)
how to call returntype static method in printstatement?
Ans)System.out.println("value is"+classname.returntypestaticmethod());
Scenrio:3 how to call one class static members in another package class
import packagename.classname;
Q)How can you access one class static variable in another package class?
Ans)classname.staticvariable;
Q)how can you call one class static void method in another package class?
Ans)classname.staticmethod();
Q)how can you call static void parameterised method under main() in another package class?
Ans)classname.staticmethodname(p1value,p2value,p3value..);
Q)how can you call return type static method() under main() in another package class?
datatypeofthemethod varaiblename=classname.returntypestaticmethod();
System.out.println("value is"+varaiblename);
(or)
how to call returntype static method in printstatement?
Ans)System.out.println("value is"+classname.returntypestaticmethod());
=================================================
(or)
STATIC IMPORT:
Static imports allow you to call static members, i.e., methods and fields of a class directly
without specifying the class.
Using static imports greatly improves the readability of your test code, you should use it.
how to import static members in another class?
import static packagename.classname.staticmember;
import static packagename.classname.*;
no need to refer class name before static members.
staticmethodname();
staticvariable;
//calling returntypestaticmethod
datatype variablename=returntypestaticmethod();
===============================================
nonstatic/instance method():if a method doesnot contain static keyword then that method is called non static method.
Syntax:
accessmodifier returntype methodName(){
method body(logic)
}
parameterised instance method():if a method contains parameters then that method is called parameterised instance method.
Syntax:
accessmodifier void methodName(datatype p1, datatype p2, datatype p3,..){
method body(logic)
}
ex:
public void setEmpName(String name){method body}
non parameterised instance method:if a method doesnot contain any parameters then that method is called non parameterised instance method.
syntax:
accessmodifier void methodName(){
method body(logic)
}
Without void keyword instance method syntax:
accessmodifier datatype methodName(){
logic;
return variable;
}
ex:
protected String getEmpName(){
return name;
}
accessmodifier datatype methodName(datatype p1,datatype p2){
logic;
return variable;
}
How can you access/execute non static members under main method/any other static method?
Ans)by creating object for that class.
How to create object for a class?
Ans)by using new keyword
//local variable syntax:
classname refvariable=new classname();
reference variable:if a variable points to the object is called referencevaiable.
referencevaiable holds the address of the object
//calling the non static method
refvariable.nonstatic/instancedmethod();
//calling non static variable
refvariable.nonstatic variable;
Anonymous Object:create an object for a class without reference variable then that object is called anonymous object
Syntax:
new classname(); //anonymous object
//caling the non static method with anonymous object
new classname().nonstatic method1();
new classname().nonstatic method2();
In object-oriented programming, a class is a template for creating objects. You can create multiple instances of a class, each of which is called an object. Each object can have its own attribute values (data) and behavior (methods).
========================================================================
Scenario 1)In the Same class how to call nonstatic members
create object for the class
classname objreference=new classname();
Q)How can you call nonstatic void method under main method in the same class?
Ans)objreference.nonstaticmethod();
Q)how can you call nonstatic void parameterised method under main() in same class?
Ans)objreference.nonstaticmethodname(p1value,p2value,p3value..);
Q)how can you call return type nonstatic method() under main() in the same class?
datatypeofthemethod varaiblename=objreference.returntypenonstaticmethod();
System.out.println("value is"+varaiblename);
(or)
how to call returntype nonstatic method in printstatement?
Ans)System.out.println("value is"+objreference.returntypenonstaticmethod());
Q)how can you access nonstatic variable in same class under main method?
Ans)datatype output=objectreference.nonstatic variable1+objectreference.nonstatic variable2;
System.out.println("nonstatic variable value"+objectreference.nonstatic variable);
Scenrio:2 how to call nonstatic members in another class of same package
create object for the class
classname objreference
Q)How can you access one class nonstatic variable in another class?
Ans)objectreference.nonstatic variable;
Q)how can you call one class nonstatic void method in another class?
Ans)objectreference.nonstaticmethod();
Q)how can you call nonstatic void parameterised method under main() in another class?
Ans)objectreference.nonstaticmethodname(p1value,p2value,p3value..);
Q)how can you call return type nonstatic method() under main() in another class?
datatypeofthemethod varaiblename=objectreference.returntypenonstaticmethod();
System.out.println("value is"+varaiblename);
(or)
how to call returntype nonstatic method in printstatement?
Ans)System.out.println("value is"+objectreference.returntypenonstaticmethod());
=================================================
Static Methods | Non-Static Methods |
These methods support early or compile-time binding. | They support late, run-time, or dynamic binding. |
These methods can only access static variables of other classes as well as their own class. | They can access both static as well as non-static members. |
You can’t override static methods. | They can be overridden. |
Less memory consumption since they are allocated memory only once when the class is being loaded. | Memories are allocated for each object. |
Static vs Non-Static Method Example in Java:
package methodprograms;
/**
* * Simple Java class to represent a Player with position. * It has both static
* and non-static method to operate on * player objects. * @author Ramesh *
*/
class Player {
private static String game = "Super Mario Bros";
private int X;
private int Y;
public Player(int x, int y) {
this.X = x;
this.Y = y;
}
public void move() {
X++;
Y++;
}
public static void changeGame(String nextGame) {
game = nextGame;
}
@Override
public String toString() {
return String.format("Game: %s, X : %d, Y: %d ", game, X, Y);
}
}
package methodprograms;
/**
* * Java program to show difference between static and non-static method. * It
* explains how calling static method and changing static variable * affect all
* objects, instead of just calling object in case of non-static * method
* * @author Ramesh Ch *
*/
public class StaticDemo {
public static void main(String args[]) {
Player p1 = new Player(10, 10);
Player p2 = new Player(20, 20);
// calling non-static method move() on p1
p1.move();
// let's print position of p1 and p2
// only p1 should have moved, no impact on p2
System.out.println("P1 : " + p1);
System.out.println("P2 : " + p2);
// calling static method on p2
p2.changeGame("Cricket Brian Lara 1997");
// should have affected both p1 and p2
System.out.println("P1 : " + p1);
System.out.println("P2 : " + p2);
}
}
P1 : Game: Super Mario Bros, X : 11, Y: 11
P2 : Game: Super Mario Bros, X : 20, Y: 20
P1 : Game: Cricket Brian Lara 1997, X : 11, Y: 11
P2 : Game: Cricket Brian Lara 1997, X : 20, Y: 20
--------------------------------------
In this program, we have two players P1 and P2, which are instance of Player class. This class contains a class variable called "game" and two instance variable X and Y to denote coordinates of Player. We have a static method called changeGame() to set value of static variable "game" and non-static method move() to change value of instance variables X and Y.
Properties of static methods in Java
Static is not just another keyword it's one of most important programming concept and every language has some specific features related to static variables, methods, and classes. Though key difference comes from the fact that static is something which is associated with the class rather than an instance, there are many subtle details of static keyword, which you should keep in mind. Let's see some of them here.1. You cannot use this keyword inside a static method in Java. Since this is associated with the current instance, it's not allowed in static context because no instance exist that time. Trying to use this variable inside static context e.g. static block or method is compile time error in Java.
2. super keyword is not allowed inside the body of a static method or static block. Just like this, a super keyword is also used to represent current instance of the parent class and since the instance is not valid in static context, it's a compile-time error to use super keyword inside a static method in Java.
3. You cannot use any instance variable inside a static method, they will result in compile time error e.g. "non-static reference is not allowed inside static methods". Why? because instance may not exist when the static method gets called. They are not associated with any instance, you can call them even on a null variable without throwing NullPointerException in Java. In short, you cannot use non-static members inside your static methods in Java.
3. A static method cannot be overridden in Java, Why? because they are not resolved at runtime, which is the case with overriding. Like a private and final method, static methods are also resolved at compile time.
4. Static method invocation is more efficient than instance method because the compiler doesn't need to pass this reference, unlike instance methods. That's why you should make utility method as static if they are not using any instance variable.
5. Static methods are bonded during compile time, as opposed to an instance method, which is resolved during runtime; former is known as static binding while later is known as dynamic binding in Java. See the difference between static and dynamic binding for more details.
7. You can call a static method without creating any instance of that class, this is one of the biggest reason of making a method static in Java. For example, to call Double.valueOf(), you don't need to create an instance of the Double class. You can even call static methods with reference variable having a null value and to your surprise, those will not result in a null pointer, as only the classname is used to find and call static methods. For example, following code will run fine in Java.
Double d = null; d.valueOf(2);
8. A static method can be synchronized, and more importantly, they use different lock than instance synchronized method. Which means, two threads can simultaneously run a static and a non-static method in Java. This is a common multi-threading mistake in Java and you should look for that while writing Java test involving code and multiple threads. To learn more see the difference between static and non-static synchronized method in Java.
9. As the name implies, instance methods require an instance of a class. Static methods (and fields) are independent of class instances, as they are only associated with class. To use instance methods, you'll have to create an instance using new. A static method is considered to have no side effect on the state of an object because of the said reason.
When to use Static method in Java? Example
Methods which never need to access instance variables are good candidate to become static. The functions in java.lang.Math are a good example as they only need input arguments. One rule-of-thumb, if you have a class MyClass, ask yourself "does it make sense to call this method, even if no Object of MyClass has been constructed yet?" If so, it should definitely be static.1) Use static method as static factory method for data conversion e.g. Integer.valueOf(), which is used to convert any other data type to integer e.g. Integer.valueOf(String str) converts String to Integer in Java.
2) Use static method as utility methods like methods from Math class or Arrays or Collections e.g. Collections.sort() method.
3) getInstance() method of Singleton design pattern is another popular example of Static method in Java
4) Pattern.compile() is another static method, which is example of static factory method as discussed in the first example
5) Hmm, how can I forget the most popular example of a static method in Java, yes I am talking about public static void main(String[] str). The main method is one of the most known examples of static methods, in fact, why main is static in Java, is also one of the frequently asked Java question on college viva or on Java interviews.
Disadvantages of using the static method in Java
1. No Runtime Polymorphism
First and foremost, the static method reduces the flexibility of your system. Once a method is declared static, it's fixed. You cannot provide an alternate implementation of that method in a subclass, as the static method cannot be overridden, they can only be hidden. Even this method hiding can cause serious and subtle bugs.
2. Potential of Concurrency Bugs
One of the not-so-obvious thing about static synchronized method is that it uses different lock than instance synchronized method. which means, If you are sharing a resource between a static and non-static method, and thinking that you have synchronized their access, you are living on a dream. Both methods can be run in parallel at the same time and potentially cause subtle concurrency bugs.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.