Automation QA Testing Course Content

Java Methods/Functions

Method:

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

if a method prototype line contains a static keyword then that method is called a static method.

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 - 

  1. The static methods of a particular class can only access the static variables and can change them.
  2. A static method can only call other static methods.
  3. Static methods can’t refer to non-static variables or methods.
  4. 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;
}

Example:

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();

   }

}

StaticMethods_1

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();

   }

}

StaticMethods_2=================================================

Scenario 1)how to call static members in the Same class: 
Q)How can you call static void method under main method/anystaticmethod in the same class?
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
================================================
Scenario - 1: calling static members in the same class:
package methodprograms;

public class StaticMembersDemo {
//accessmodifier static datatype variablename=value;
private static char c='A';
static int i=25;
protected static long l=50L;
public static String s="selenium";
/**
* This method does the division between numbers
*/
//accessmodifier sattic void methodname(){logic}
public static void division() {
System.out.println("started executing the division()...");
//fetch the remainder using %
long rm=(i+c)%l;
System.out.println("remainder value is:"+rm);
//fetch quotient value using /
float qt=(i+l)/c;
System.out.println("quotient value is:"+qt);
System.out.println("*********************************");
}
/**
* Swapping two integer numbers
* @param a
* @param b
*/
//accessmodifier static void methodname(datatype p1,datatype p2){logic}
public static void swapWithoutThirdVariable(int a,int b) {
System.out.println("before swaping a value is:"+a+" b value is:"+b);
a=a+b;
b=a-b;
a=a-b;
System.out.println("After swaping a value is:"+a+" b value is:"+b);
}
/**
* This method generates random double value from 0 to 1
* @return
*/
//accessmodifer static datatype methodname(){logic;return value;}
public static double getDoubleRandomNumber() {
System.out.println("Generating random number from 0 to 1");
//Generate random numbers using Math.random()
double randNumb=Math.random();
return randNumb;
}
/**
* Converting celcius degrees temp to farenheit temp
* @param ct
* @return
*/
//accessmodifier static datatype methodname(datatype p1){logic;return value;}
//  protected static float convertCelciusToFarenheitTemp(float ct) {
  public static float convertCelciusToFarenheitTemp(float ct) {
  System.out.println("started executing the convertCelciusToFarenheitTemp(float ct)");
float ft = (float) (ct*1.8 + 32);
return ft;
  }
public static void main(String[] args) {
/*
* Q)How can you call static void method under main method/anystaticmethod in the same class?
Ans)staticmethodname();
*/
division();
/*
* Q)how can you call static void parameterised method under main() in same class?
Ans)staticmethodname(p1value,p2value,p3value..);
*/
swapWithoutThirdVariable(35, 75);
/*
* Q)how can you call return type static method() under main() in the same class?
datatypeofthemethod varaiblename=returntypestaticmethod();
*/
double randNumber=getDoubleRandomNumber();
System.out.println("random number value from 0 to 1 is:"+randNumber);
/*
* how to call returntype static method in printstatement?
Ans)System.out.println("value is"+returntypestaticmethod());
*/
System.out.println("Farenheit temp is:"+convertCelciusToFarenheitTemp(50.5F));
/*
 * Q)how can you access static variable in same class under any static/nostatic/main method?
Ans)directly call static variable
 */
System.out.println("static string variable s value is:"+s);
}

}

========================
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());
=======================================
Scenario -2 calling one class static members in another class same  package program
package methodprograms;

public class CallStaticMembInAnotherClassSamePkg {

public static void main(String[] args) {
/*
* Q)How can you access one class static variable in another class?
Ans)classname.staticvariable;
*/
long sum=StaticMembersDemo.i+StaticMembersDemo.l;

System.out.println("sum value is:"+sum);
/*
 * Q)how can you call one class static void method in another class?
Ans)classname.staticmethod();
 */
StaticMembersDemo.division();

/*
 * Q)how can you call static void parameterised method under any method/main() in another class?
Ans)classname.staticmethodname(p1value,p2value,p3value..);
 */
StaticMembersDemo.swapWithoutThirdVariable(10, 20);
/*
 * Q)how can you call return type static method() under any method/main() in another class?
datatypeofthemethod varaiblename=classname.returntypestaticmethod();
 */

float ft=StaticMembersDemo.convertCelciusToFarenheitTemp(30.34F);
System.out.println("farenheit temp value is:"+ft);
/*
 * how to call returntype static method in printstatement?
Ans)System.out.println("value is"+classname.returntypestaticmethod());
 */
System.out.println("random value is:"+StaticMembersDemo.getDoubleRandomNumber());

}

}

=================================================
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());
=================================================
Scenario 3 Calling one package class static members in another package class:
package sampleprograms;

import methodprograms.StaticMembersDemo;

public class AcessAnotherPkgStaticMembers {

public static void main(String[] args) {
/*
* Q)How can you access one class static variable in another package class?
Ans)classname.staticvariable;
*/
System.out.println("StaticMembersDemo static variable s value is:"+StaticMembersDemo.s);

/*
 * Q)how can you call one class static void method in another package class?
Ans)classname.staticmethod();
 */
StaticMembersDemo.division();
/*
 * Q)how can you call static void parameterised method under main() in another package class?
Ans)classname.staticmethodname(p1value,p2value,p3value..);
 */
StaticMembersDemo.swapWithoutThirdVariable(55, 80);
/*
 * Q)how can you call return type static method() under main() in another package class?
datatypeofthemethod varaiblename=classname.returntypestaticmethod();
 */
double randNumb=StaticMembersDemo.getDoubleRandomNumber();
System.out.println("random value is:"+randNumb);
/*
 * how to call returntype static method in printstatement?
Ans)System.out.println("value is"+classname.returntypestaticmethod());
 */
System.out.println("farenheit temp is:"+StaticMembersDemo.convertCelciusToFarenheitTemp(60.78F));

}

}

======================================
(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();

===============================================
Static Import program:
package sampleprograms;
//import static methodprograms.StaticMembersDemo.s;
//import static methodprograms.StaticMembersDemo.division;
import static methodprograms.StaticMembersDemo.*;
public class StaticImportDemo {

public static void main(String[] args) {
division();
swapWithoutThirdVariable(45, 90);
//returntype mtheods
double randVal=getDoubleRandomNumber();
System.out.println("random value is:"+randVal);
System.out.println("static variable s value is:"+s);
}

}
QUIZ on Static Methods:
1)Guess the output
package methods;

public class Test {

public static double get() {
return 10;
}
public static void main(String[] args) {
// TODO Auto-generated method stub

}
i)Compilation fails
ii)Runtime Exception
iii)No error & no output
============================================
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();
Did you know that in Java, you can create multiple instances of a class to store different data?
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);
============================================
Scenario -1 -creating & calling nonstatic members in same class
package methodprograms;

public class InstanceMemberDemo {
//accessmodifier datatype variablename=value;
private char c='a'; //ascii code of a=97 b=98
float f=3.75F;
protected double d=25.45;
public int i=50;
/**
* this method explains about type casting and char conversion
*/
//accessmodifier void methodname(){logic}
public void charDemo() {
System.out.println("started executing the charDemo()...");
//datatype variablename=value/expression;
char c1=(char)(c+1);
System.out.println("c1 value is:"+c1);
char c2=(char) (c1+d);
System.out.println("c2 value is:"+c2);
long sum=(long) (c1+c2+c+i+d+f);
System.out.println("sum of c1,c2,c,i,d,f variables output is:"+sum);
}
//accessmodifier void methodname(datatype p1,datatype p2){logic}
public void swapWithThirdVariable(int x, int y) {
System.out.println("Before swapping x value is:"+x+" y value is:"+y);
int temp=x;
x=y;
y=temp;
System.out.println("After swapping x value is:"+x+" y value is:"+y);
}
//accessmodifier datatype methodname(){logic;return value;}
public int getIntRandomNumber() {
System.out.println("Started executing the integer random number fom 1 to 100");
int randNumb=(int) (Math.random()*100);
return randNumb;
}
//accessmodifier datatype methodname(datatype p1,datatype p2){logic;return value;}
protected float getMaxFloatValue(float f1,float f2) {
System.out.println("started executing the getMaxFloatValue(float f1,float f2) ...in "+f1+" "+f2);
float maxVal=Math.max(f1, f2);
return maxVal;
}
public static void main(String[] args) {
//create object for the class - InstanceMemberDemo
//classname refobj=new classname();
InstanceMemberDemo insObj=new InstanceMemberDemo();
System.out.println("insObj memory address is:"+insObj.hashCode());
InstanceMemberDemo imdObj=new InstanceMemberDemo();
System.out.println("imdObj memory address is:"+imdObj.hashCode());
//how can you compare two objects using Object class -obj1,.equals(obj2)--returns boolean
boolean bn=insObj.equals(imdObj);
System.out.println("comparing insObj with equals(imdObj):"+bn);
//can i call static members with this object reference? Ans: No
/*
* Q)How can you call nonstatic void method under main method in the same class?
Ans)objreference.nonstaticmethod();
*/
insObj.charDemo();
/*
* Q)how can you call nonstatic void parameterised method under main() in same class?
Ans)objreference.nonstaticmethodname(p1value,p2value,p3value..);
*/
insObj.swapWithThirdVariable(35, 67);
/*
* Q)how can you call return type nonstatic method() under main() in the same class?
datatypeofthemethod varaiblename=objreference.returntypenonstaticmethod();
*/
int randVal=insObj.getIntRandomNumber();
System.out.println("random number is:"+randVal);
/*
* ow to call returntype nonstatic method in printstatement?
Ans)System.out.println("value is"+objreference.returntypenonstaticmethod());
*/
System.out.println("maximum float value is:"+insObj.getMaxFloatValue(55.45F, 23.456F));
/*
* Q)how can you access nonstatic variable in same class under main method?
Ans)datatype output=objectreference.nonstatic variable1+objectreference.nonstatic variable2;
*/
double result=insObj.c+insObj.d+insObj.f;
System.out.println("result value is:"+result);
System.out.println("nonstatic variable under main():"+imdObj.i);
}

}

=================================================
Scenrio:2  how to call nonstatic members in another class of same package
create object for the class
classname objreference
=new classname();
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());
=================================================
Scenrio:2  how to call nonstatic members in another class of same package Program:
package methodprograms;

public class CallNonStaticMembInAnotherClassSamePkg {

public static void main(String[] args) {
//create Object for the class - InstanceMemberDemo
//classname refobj = new classname();
InstanceMemberDemo indObj=new InstanceMemberDemo();
/*
* Q)How can you access one class nonstatic variable in another class?
Ans)objectreference.nonstatic variable;
*/
System.out.println("calling InstanceMemberDemo instance variable i value:"+indObj.i);
/*
* Q)how can you call one class nonstatic void method in another class?
Ans)objectreference.nonstaticmethod();
*/
indObj.charDemo();
/*
* Q)how can you call nonstatic void parameterised method under main() in another class?
Ans)objectreference.nonstaticmethodname(p1value,p2value,p3value..);
*/
indObj.swapWithThirdVariable(10, 15);
/*
* Q)how can you call return type nonstatic method() under main() in another class?
datatypeofthemethod varaiblename=objectreference.returntypenonstaticmethod();
*/
float maxVal=indObj.getMaxFloatValue(20.34F, 12.234F);
System.out.println("max float value is:"+maxVal);
/*
* how to call returntype nonstatic method in printstatement?
Ans)System.out.println("value is"+objectreference.returntypenonstaticmethod());
*/
System.out.println("get random int value is:"+indObj.getIntRandomNumber());
}

}
=====================================================
Scenario 3 program: calling one package class nonstatic members in another package class:
package sampleprograms;

import methodprograms.InstanceMemberDemo;

public class CallInstanceMembInAnotherPkgClass {

public static void main(String[] args) {
// create object for the class - InstanceMemberDemo
//classnamre refvar= new classname();
InstanceMemberDemo inObj=new InstanceMemberDemo();
//how can you call InstanceMemberDemo -instance variable
System.out.println("InstanceMemberDemo instance variable i value is:"+inObj.i);
//calling void without paramters method
inObj.charDemo();
//calling voif paramterised method
inObj.swapWithThirdVariable(80, 400);
//caling returntype mtehods
//datatype variablename=objref.returntypenonstatimethod();
int randVal=inObj.getIntRandomNumber();
System.out.println("random value is:"+randVal);
//call in the print statement --returntype method
//System.out.println("get max float value:"+inObj.get);
}

}
=========================================

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.

========================================
1)What is a better ordering flow of code base?
package name;
imports
class name
class level variables
Top Level Methods
Low Level Methods

2)
What will be the preferred Entity class name for a Class contain Student data?
a)StudentDetails.java
b)Student.java
c)StudentInformation.java
d)Students.java

3)Which is the correct naming convention for naming a Java file?
a)FeESpRocessor.java
b)Fees_Processor.java
c)FeesProcessor.java
d)_Fees_processor.java

4)Which import statement is preferred ?
a)import java.util.*;
b)import java.util.*;import java.util.ArrayList;
c)import java.util.*;import com.linkedin.speed.*;
d)import java.util.ArrayList;import java.util.List;

5)Guess the output
package methods.nonstatic;

public class Test {

public static void main(String[] args) {
Demo Math=new Demo();
int res=Math.min(10,20);
System.out.println(res);

}

}

class Demo{
}
i)20 ii)10 iii)Exception
---------------------------------------------------------------
6)
public class Test2 {

public static void main(String[] args) {
Demo2 Math=new Demo2();
int res=Math.max(10,20);
System.out.println(res);

}

}

class Demo2{
public static int max(int x, int y) {
return 100;
}
}
i)20
ii)100
iii)Exception
-------------------------------------------------------------------
package methods.nonstatic;

class Test3 {

public static void main(String[] args) {
new Demo3();

}

}
class Demo3{
private Demo3 demo3 = new Demo3();
}
i)Exception
ii)No Exception
----------------------------------------------------------------------------

Static vs Non-Static Method Example in Java:

1)key difference comes from the fact that static is something which is associated with the class rather than an instance.

2)key difference between static and non-static method is that static method affects all object if they are using any static variable, but non-static method only affects the object they are operating upon

-------------------------------------------

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);

}

}

---------------------------------------------------------------
Output 

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.

In the first example of our test program, we call instance method move() on p1 and you can see that only its X and Y are modified, p2's position has not changed because the instance method only affect the state of methods they were called upon. 

In the next example we call static method changeGame(), now this will affect both p1 and p2 because static variable "game" is shared between them. You can see the output after the invocation of instance method and static method to figure out difference.


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. 

By the way, this doesn't mean that you cannot declare another static method with same name and signature in the child class, you can do so and the compiler will not complain at all, but that would not be method overriding, instead that is called method hiding in Java. This new method will hide the static method from the parent class and when you call it using Child class only.  See why static method cannot be overridden for more details.

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.


6. By the way, You can overload static methods in Java, there is no restriction on that from Java language perspective. In fact, JDK API itself has lots of overloaded static method e.g. String.valueOf() is overloaded to accept an intlongfloatdouble, and boolean data type. EnumSet.of() is also overloaded to create EnumSet with one, two or multiple values.

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.

Another simple rule in Java is,  Immutable is good. So if your method does not change the state of the object and if it must not be overridden by a subclass, it should be static. 

Also, static methods are easier to inline by the JIT-Compiler. Let's see an example, supper you have a class Car and you might have a method double convertMpgToKpl(double mpg) , this is another good candidate to become static, because one might want to know what 45mpg converts to, even if nobody has ever built a Car.

But void setOdometer(double mi) (which sets the distance-travelled for one particular Car) can't be static because it's inconceivable to call the method before any Car has been constructed. 

In short, If a method inside a class is not using an instance variable, then it's a good candidate for making it static, and maybe it might not belong to that class itself. Here are a couple of common scenarios in the Java world, where use of static method is considered appropriate :

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 

There is nothing in the world which only has pros without any cons, and static methods are no different. Though they are immensely helpful from convenience perspective and critical to implement some core Java design patterns like Singleton and Factory Pattern, they also have some serious drawbacks. Here is a couple of them :

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.