Posts Tagged arguments
Java Tutorial 7 – passing arguments and returning values
Passing arguments between methods is very easy.
lets use class1 and class2 that we created before.
and change class1 to :
public class class1 {
public static void main(String[] args) {
Class2 c2object= new Class2();
c2object.boy(“Yash”);
c2object.girl(“sweety”);
}
}
and Class2 :
public class Class2 {
public void girl(String name){
System.out.println(name + ” is present”);
}
public void boy(String name){
System.out.println(name + ” is present”);
}
}
Here we have changed
public void boy()
to
public void boy(String name)
so now every time we call boy method it takes a string, see we have passed a string in boy(“Yash”) in class 1.
- boy(“yash”) passes a string to boy function.
- this string is cached into the String name in class 2.
- then we used name to print a line.
You can also pass int, double etc. but when you pass an int you must define other int in definition of method to catch that int.
for example:
public static void main(String[] args){
add(12,13);
public static void add(int x, int y){
System.out.println(x+y);
}
}
we have passed two arguments and cached it in int x and y and used it to display sum.
Returning values:
to return value just add one line at bottom of method called “return (variable)”
in above example we can return the sum like this way:
public static void main(String[] args){
int ans;
ans = add( 12, 13 );
System.out.println(ans);
public static int add(int x, int y){
return (x+y);
}
}
what we have done here is , we simply get 2 int in method and returned the addition of them.
now notice that we have changed public static void add(int x, int y) to public static int add(int x, int y)
it is because now our method returns an int.
same way if your method returns double or String method would be public static double add(int x, int y)
and in class 1 we written ans = add( 12, 13 ) here ans is the variable which will store the returned value.
same way if you returns a String you must have String variable to store it instead of int ans.
In next tutorial we will learn how to pass Objects between methods.