Create a new class,
name third.
Copy in to class.
public static void main(String args[]) {
}
public static void show()
{
System.out.println("This is example text");
}
Run to see blank
Console screen.
Type show(); in to
main command, run.
Now we see text we
want to show.
Copy to above last bracket.
public static void multiply(int a, int b) {
int c=a*b;
System.out.println("Result is: "+c);
}
Add to main:
int so=10;
int so2=12;
multiply(so,so2);
Run to see result 120.
The code lines in
show(), multiply() call method or function.
The line public static
void show() declare a method, in main, we use method.
Why need method ? When
coding, some code need to use many times, so we put them in a method, when use,
we simple call it.
Compare
show() and multiply() we see show() has nothing in it’s bracket, we say it not
receive parameters, multiply receive to integer numbers a, b.
Copy to
below multiply()
public static int multiply2(int a, int b) {
int c=a*b;
return c;
}
Add to main:
int so3=15;
int so4=2;
int kq=multiply2(so3,so4);
System.out.println("Reuslt second method is:
"+kq);
Run to see result.
Compare multiply () and multiply
2(), we see void
and int
at method declaration.
Void mean that method return nothing, int return
an integer. If method return value, it must has return at end of method.
Method can return a
string, copy to below multiply2.
public static String add(int a, int b) {
int c=a+b;
return "Result is: "+c;
}
Add to main.
String
kq2=add(so3,so4);
System.out.println(kq2);
Run to see result.
Method can return
array, copy to above last close bracket.
public static int [] calculate(int a, int b) {
int []ar=new int[3];
int c=a+b;
int d=a-b;
int e=a*b;
ar[0]=c;
ar[1]=d;
ar[2]=e;
return ar;
}
Add to main.
int []kq3=new int[3];
kq3=calculate(so3,so4);
System.out.println("Elements in array is: "+kq3[0]+" "+kq3[1]+" "+kq3[2]);
Run to see result.
Method calculate()
return 3 numbers result after calculate.
No comments:
Post a Comment