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

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.