mandar262 mandar262 - 2 months ago 5
Java Question

what is the use of passing parameters to methods in java?

I am new to Java. I would like an in-depth explination of passing parameters to methods in Java?


  1. Why use it?

  2. How to use it?

  3. What is the benefit of using it?



what i mean to say is we can also do this was also

With example.......

following is type, not example just ref

type a)

public class DataArtist {
int a,b;
char abc,xyz
...
public void draw(String s) {

int a,b;
char abc,xyz ...
}
public void draw(int i) {
...
}
public void draw(double f) {
...
}
public void draw(int i, double f) {
...
}
}


type b)

public class DataArtist {
int a,b;
char abc,xyz
...
public void draw() {

int a,b;
char abc,xyz ...
}
public void draw() {
...
}
public void draw() {
...
}
public void draw( ) {
...
}
}


what is difference betwween type a and b and advantages
and why there is need to pass parameters to method
but normaly we declare data in the class and method so why there is need

Answer

Parametrized methods promote reusable code. This is general to most (99%) of programming languages.

e.g.

 void Greet(String name) {
    System.out.println("Hi, " + name);
}

Greet("John");
Greet("Adam");
Greet("Jill");
Greet("Tim");
...

Instead of

 System.out.println("Hi, John");
System.out.println("Hi, Adam");
System.out.println("Hi, Jill");
System.out.println("Hi, Tim");
...

This example is very basic and demonstrates the point, but does not begin justifying why we have parametrized methods.