Is it necessary to always initialise the result variable in the function
For example
Public class Calculator
result=addition(a,b);
Public static int addition(int a, int b)
int result;
result =a+b;
return result;
You don't need to have a result variable at all. You need to make sure that every possible way that execution can reach the end of your function (without just throwing an exception) means you get to a return statement, and every return statement has an appropriate express to evaluate, but that doesn't mean you need a separate variable. Your example could be written as:
public static int addition(int a, int b) {
return a + b;
}
If you do use a variable, you'll need to make sure it's definitely assigned before you can read from it, including in a return statement. For example, this won't work because result hasn't been definitely assigned:
public static int addition(int a, int b) {
int result;
if (a < b) {
result = a + b;
}
return result; // Invalid! result may not have a value
}
Where possible, it's generally a good idea to initialize a variable at the point of declaration. So if I were writing this code and wanted a result variable, I'd have:
public static int addition(int a, int b) {
int result = a + b;
return result;
}
Now, looking at your sample code again, you've got another variable used when you call the method:
result=addition(a,b);
It's not clear where that variable would be declared (which is one reason to avoid just posting pseudo-code in questions) but it's completely separate from the result variable in addition, which is local to the addition method. The two variables happen to have the same name, but they're otherwise unrelated. For example, you could easily have:
int sum = addition(a, b);
or call another method with the result instead of assigning it to a variable:
System.out.println(addition(a, b));
Or you could just ignore it entirely:
addtion(a, b); // Valid, but pointless unless there are side-effects
Related
Lets say I have helper (util) methods and caller
Helper methods:
public int getSomeIntermediateResult(String someString){
// Some operations with someString.
int x = ... ; //Not a constant, but assume it gets created with some computation in method.
return x;
}
public int overallHelperFunction(String someString){
int intermediateResult = getSomeIntermediateResult(someString);
return getFinalOverallResult(someString, intermediateResult);
}
// THIS FUNCTION MUST only be called with the {someString}
// AND the intermediateResult created by getSomeIntermediateResult(someString) only, otherwise it makes no sense.
public int getFinalOverallResult(String someString, int intermediateResult){
// .. donSome Other Stuff and return
}
Here is he trouble I am having, I have two callers
public int callerOne(String someString){
return overallHelperFunction(someString);
}
This one is fine, I can directly call overallHelperFunction which takes care of everything.
The second one is the issue.
public int callerTwo(String someString){
int intermediate = getIntermediateResult(someString);
int finalResult = getFinallOverallResult(someString, intermediate);
return intermediate + finalResult; // I have to REUSE intermediate here.
}
Now this is the main issue.
The thing is the function getFinallOverallResult doesn't make sense if its called with two disjoint someString and intermediateResult so make it a public interface is risky if it gets in the hands of a wrong caller, but at the same time, I need it exposed for callerTwo. What should I do in this case? I did document getFinallOverallResult, but there is no actual restriction of it being called with random params.
Thanks!
Is there a way in Java to create a method that would return the list of parameters of another method such that I am able to call
anotherMethod(method())
where anotherMethod has arbitrary arguments like
public void anotherMethod(int a, int b, String c)
And what is if the types stay the same, like with
public int add(int a, int b, int c)
If there is no such way, how could I model the list of parameters such that it would work? Is it a List or an array or something else?
If the number of parameters is fixed at the call site, you could use varargs
int add(int... numbers)
otherwise you'd use an array or collection
int add(int[] numbers)
You can then of course have another method provide the value of these parameters:
add(someOtherMethod())
Varargs
Java has a built-in feature to denote a variable length of arguments. It is called varargs (documentation) (variable arguments) and it only works if the type stays the same. The syntax for a method is like this:
public int add(int... values)
Note the int... values which denotes varargs. A caller can now call the method like
add(null) // Passing null
add(values) // Passing an int[]
add() // No arguments
add(a) // One int
add(a, b) // Two ints
add(a, b, c) // Three ints
add(a, b, c, d) // Four ints
...
Note the three special cases null, int[] and empty.
What Java does is it will convert the arguments into an array. So inside the method values will be a regular int[]. You could thus implement the method like
public int add(int... values) {
int sum = 0;
for (int value : values) {
sum += value;
}
return sum;
}
If you, as a caller, want to pass the return value of a function you just need to make sure that it returns an array like int[]. So the following would work:
public int[] valueProvider() {
int[] values = ...
return values;
}
and then call it like
int sum = add(valueProvider());
Collection, Iterable and Stream
Besides that, if you don't want to use varargs or arrays, you can use Collections (documentation). A collection may be a List or a Set and so on. For example you could declare
public int add(Collection<Integer> values)
and feed it like
Collection<Integer> values = new ArrayList<>();
values.add(1);
values.add(2);
int sum = add(values);
An Iterable<Integer>, in contrast to Collection<Integer> would even be more flexible.
Using a Stream (documentation) would also work like a charm and is probably one of the most flexible variants since the source of a stream could be anything and nearly anything of the standard library supports a stream representation.
Changing type
Now note that what you searched for in the beginning, a method that is able to feed arbitrary arguments, is not possible in Java.
The main problem is that the types may change, so you may have a method like
public void doSomething(int first, String second, File third)
and you won't be able to feed the method with varargs, Collections or any of the presented methods.
In that case you will need a wrapper class like
public class DoSomethingArguments {
private int mFirst;
private String mSecond;
private File mThird;
public DoSomethingArguments(int first; String second, File third) {
this.mFirst = first;
this.mSecond = second;
this.mThird = third;
}
// Some getters
}
(or a generic tuple class, a triple in this case)
But then you would need to change the method to
public void doSomething(DoSomethingArguments arguments)
what is probably not what you wanted since you probably intended to not change the signature of doSomething.
But unfortunately there is no way to feed a method like this in such a way.
There is nothing that works the way you wish for at compile time. As the other answers are pointing out, there are varargs. But that is just syntactical sugar. That is just the compiler implicitly creating an array of a certain type for you.
But beyond that, there is reflection. Reflection allows you to dynamically inspect classes and methods at *runtime.
In other words: you can do something like
Object whatever = ...
Class<?> someClass = whatever.getClass();
And now you can ask someClass about the methods it has. And which parameters they need.
But as said: all of that is runtime only. And it the reflection APIs are very easy to get wrong. And you only find out at runtime, when some exception is thrown.
There is not direct way to pass multiple values in the way you want. But you can use a indirect way to pass a group of values of different type. I can think of two ways but their can be more.
Firs - Use a map, just insert the values you want to pass in the collection and pass the collection to the second method.
Second - Create a bean (Java POJO) to pass as parameter to the consuming method.
A small sample code.
class Sample{
private int a;
private String b;
private int c;
Sample(int a,String b,int c){
this.a = a;
this.b = b;
this.c = c;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public int getC() {
return c;
}
public void setC(int c) {
this.c = c;
}
}
public class PassingExample {
public void consumerofInputs (Map<Integer, Object> input)/*(int a, String b, int c)*/{
System.out.println("I use three different inputs : int, string and int");
for (Map.Entry<Integer, Object> entry : input.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
public Map producingInput() {
Map<Integer, Object> input = new HashMap<Integer, Object>();
input.put(1, 10);
input.put(2, "input");
input.put(3, 89);
return input;
}
public Sample createClassAsInput(){
Sample input = new Sample(10,"class-input",30);
return input;
}
public void useSampleAsInput(Sample input){
System.out.println("\nUsing Class as input \nInt::"+input.getA()+"\nString::"+input.getB()+"\nInt::"+input.getC());
}
public static void main(String[] args) {
PassingExample example = new PassingExample();
example.consumerofInputs(example.producingInput());
example.useSampleAsInput(example.createClassAsInput());
}
}
The following code:
public static void main(String[] args) {
int first = 1;
int second = 2;
sum(first,second);
System.out.println(sum);
}
public static int sum(int a, int b){
int sum = a+b;
return sum;
}}
will return error and I need to write
int x = sum(first,second);
System.out.println(sum);
and define that method as integer x and print x.
But for array,
public static ArrayList<String> removeLast(ArrayList<String> list) {
//code
return list;
}
public static void main(String[] args) {
//code
removeLast(persons);
System.out.println(persons);
}
will print the returned value of array without defining as another array as the was with the previous one.
I am sorry if the question has already been asked as I couldn't find it. And I am just learning Java.
Arrays are passed by (value of) reference, therefore, any change that happens to the array inside the method, will actually change the array passed in to it. On the other hand ints are passed by value. Change an int inside a method, and it won't change the int passed into the method.
For this reason, the return statement in your array method is completely unnecessary. Your code will still change the array, even if you omit the return statement.
But there's another misconception that needs to be pointed out: when you sum two ints, you are creating a new value in memory, which exists as long as the method is executed. When the sum method is done, the sum int doesn't exist anymore. To retain its value, you need to return it from within the method, and assign it to a variable where you call the code.
Because Java is pass by value, but the value of reference types (including arrays) is a reference to the Object (in this case, a List). You might use a variadic function and (in Java 8+) an IntStream to implement it like
public static int sum(int... arr) {
return IntStream.of(arr).sum();
}
Then you can call sum with as many (or few) int arguments as you like.
Will print the returned value of array without defining as another
array as the was with the previous one ?
Whatever #yeedle mentioned above is correct, but one point to add as below:
ArrayList class (actual type of persons object) has overridden the toString() method such that it
could print the array details when you invoke
System.out.println(persons);.
You need to know that for your objects (created for your custom
classes like Product, Employee, etc..), you need to override
toString() method (inherited from java.lang.Object) to print the
values like how you wanted, otherwise simply using
System.out.println(object); will print the hashcode of the
object (like #HA5431 etc..).
You can look here and here
I have very silly doubt that why we use return statement in method . Without using return statement in method we can also get required value
as example
package testing;
public class ReturnMethod {
static int a = 10;
static int b = 5;
static int c;
static int d;
public static void add() {
c = a + b;
}
public static int returnAddValue() {
d = a + b;
return d;
}
public static void main(String[] args) {
add();
System.out.println("c: " + c);
int value = returnAddValue();
System.out.println("value: " + value);
}
}
In above example in both the cases i am getting output
c: 15
value: 15
So i am having doubt when to use return statement and why is neccessary
With return statement, the return value is not necessary to be saved in any global, external or member variable.
However, without return statement you have to prepare kind of outer variable value to track that.
If you assign the result of a method to a static variable (and, indeed, pass in the "parameters" of the method by setting static variables), you have problems when that method is called by two threads concurrently, since the variables are shared for all invocations of the method:
Thread t1 = new Thread(() -> {a = 1; b = 2; add(); }); t1.start();
Thread t2 = new Thread(() -> {a = 3; b = 4; add(); }); t2.start();
t1.join(); t2.join();
You don't know which of these threads run first, or even if they run at the same time; so you don't know what the value of a or b is when you call add(), and nor do you know whether the value in c afterwards is the result of the invocation in the first or second thread (or a mixture of the two).
The value stored in c afterwards could be any of 3, 5 or 7 (or any other value, if there is another thread which is also invoking add() concurrently outside this code.
This problem of thread interference just completely goes away if you keep values localized to the stack, by passing a and b as method parameters, and receiving the result as a return value.
Even if your code is single-threaded, it's simply ugly to have to write:
a = 1;
b = 2;
add();
int result = c;
rather than
int result = add(1, 2);
You should use a return statement, when you need the method to return a value.
In your case, both methods work.
But you can, and should use returning methods, when you don't want a field of your class to be changed by another class.
For example, you want money to be only seen, and not changed, when you are making a bank-account related software. So, you make money private, and make a method which returns the money. In this way, other classes can only see money, but not change it.
First, your functions are different, as you see
public static **void** add()
public static **int** returnAddValue()
First one does not return anything, because it has void as return type and the second one has int as return type.
First one works, because c is a global variable.
You typically would use return when you don't store the result in a (static) variable of your class.
public class ReturnMethod {
static int a = 10;
static int b = 5;
public static void add() {
int c = a + b;
}
public static int returnAddValue() {
int d = a + b;
return d;
}
public static void main(String[] args) {
add();
//not possible to access c here
//System.out.println("c: " + c);
int value = returnAddValue();
System.out.println("value: " + value);
}
}
In that modified example, there would be no way for you to access the result of the add() method.
You should probably read about Scopes in Java.
You have a class variable c & d. These variables are associated with the class and stored in heap. If you assign a value back to it and you can access it without a explicit return statement. But if you have declared d inside the method then return statement is required to give the value back to the caller.
The reason that you are able to access the value of class variable c is that it has been initialized as static. Had this not been the case the information in the c variable would be lost as soon as the add method ends. The reason methods have return value is that they user can get the updated value , if there are any manipulation in the object data. In this case there is a very small, what if there is series of manipulation with the data. In that case the final value has to be returned to the calling object which without return statement is not possible.
Its totally depends upon our requirement whether to return a value from our method or update instance variable. Some time we just want to process a value and get back the result in and result will be used in different manner, in this case we need to return value from method.
For example
java.lang.Math.sqrt(double a) method return a value and we use returned value as per our need OR requirement. Can you think if this method does not returned any value then what it should update, I think this method useless if it does not returned any value.
The variable C in your code snippet is accessed in the class throughout, and will stay until the object of the class exists. So you can print the value of Variable C outside the method.
However, if you had declared a local variable in the method add(), then print statement System.out.println("c: " + c); will print the default value for variable c. That is zero in this case.
In the following code the method array1 won't return the avarage because its return type is void.
I know what void means but can someone explain to me what is a void result type and how to make this method return the avarage:
public class JavaApplication4 {
public static void main(String[] args) {
int[] a = {1,2,3,4};
double result = array1 (a);
}
public static array1 (int[] b) {
double avarage;
int total = 0;
for (int x:b) {
total += x;
}
avarage = total / b.length;
return avarage;
}
The "result type" or "return type" is set in the function declaration. It just means what type of data is going to be returned after the function is called. Your function should look like:
public static double array1(int[] b) {
double average;
int total=0;
for(int x:b){
total +=x;
}
average = (double) total/b.length;
return average;
}
This will return the value of average after the function is done. So result will hold the same thing as the final value of average after the function completes.
You need to declare array1 as returning double. Change its declaration to:
public static double array1(int [] b ) {
A void function -- void array1(...) -- does not return a value.
Note that there's another error in your code:
avarage = total / b.length;
The above uses integer division, meaning that the result is truncated to integer, and only then converted to double. To fix, change the line to:
avarage = total / (double)b.length;
A return type of void means that a method doesn't return anything. This is useful when you want to preform an operation on an array, but there isn't any value associated with the operation. For example, say that you wanted to swap the first and last element in an array, you could write some method like this (ignore the necessary error checking)
public void swapArrayLocs(int[] swapping){
int temp = swapping[0];
swapping[0] = swapping[swapping.length - 1];
swapping[swapping.length - 1] = temp;
}
When you call this method, you're not expecting any sort of result from it, you're expecting your program to just take care of business and continue executing.
In this case, you actually want your array1(int[]) method to make its available to the rest of the program. You do this by specifying the return type of the function, which tells the rest of the program what type of information you expect that function to return. In your case, you'd do this by changing your method declaration to.
public static double array1(int[] b){
//the same method body
}
Note how in this case the word double is inserted after static. This tells the calling function that when it executes array1, the method will give back a value of type double. Contrast this with what you had before which said that the method would not give back any type of information.