Methods, Variables, If
Methods, Variables, If
com
1. Access/NonAccess Modifier
2. returnType
3. MethodName ( Parameter List)
4. {
5. //method body or statement block
6. }
-------------------------------------------------------------------
public void go(int x)
{
System.out.println(x);
}
Way2Automation.com
Method Return Type
• It May be possible that a method returns a value
or doesn’t returns any value.
Return type of a method is nothing but the data
type of the value returned by the method.
e.g.
If method returns an integer value then it’s return
type will be ‘int’, for float ‘float’, for character
‘char’, for boolean ‘boolean’ and so on.
If a method doesn’t returns any value then it’s
return type will be “void”.
• If a method returns a value then the last
statement should be a “return statement”
• Any code after return statement is not reachable
Way2Automation.com
Parameter List
• Method Parameters are the variables which
are declared in the declaration of method.
e.g.
public int go(int x) {}
• The method parameters can be nothing, one
or more than one. For multiple parameters
they are separated by comma.
e.g.
Public int go (int x, float y, String s, char c){ }
Way2Automation.com
Method Body
Predefined Methods
• Predefined methods are those methods which are
already defined in java and ready to use.
• We can call these methods and can use in our code
directly.
e.g.
Math.random();
• Math.random() is a method defined in Math class
which is used to generate a random number between
o.o to .9 in double type
• Calling Math.random() :
Int x = (int) (Math.random() * 4);
• import java.util.*;
• public class Test2 {
• public static void main(String[] args)
• {
• Test2 t = new Test2();
• Scanner scan = new Scanner(System.in); //ignore
• System.out.println("enter a value");
• int input = scan.nextInt(); //ignore
• scan.close(); //ignore
• int randomNum = (int)(Math.random()* 10);
• if(input == randomNum)
• System.out.println("well done smarty");
• else
• t.looser();
• }
• }
Way2Automation.com