Lecture 2
Lecture 2
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);
}
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){ }
Method Body
Body of a method starts from opening curly braces { and
ends at closing curly braces }.
All statements of methods goes within the pair of curly
braces.
Execution of method stops on either return statement or
closing curly braces }.
e.g.
public int go(int x, int y)
{
Int sum = x + y;
Return sum;
}
But how to call a method???????
Local Variable
1. Local variable are those
variables which are declared
within a method.
2. These are known as Local
variable because they formed
within method and dies at the
end of the method
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);
//It will generate the number from 0 to 3
IF statement:
This is a decision making statement, which will execute its codes if and only if
the condition is true.
If(condition)
statement; // codes
If-else statement:
In this the else codes will be execute if and only if the condition is false.
If(condition)
statement; //codes
else
statement; // codes
If-else-if :
This is combination of if-else statements.
If(condition)
Statements;
Else if (condition)
Statements
Else if (condition)
Statements;
Else
Statements;
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();
}
}