method result type - java

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.

Related

What is the difference between void and return even though I can get same output on both?

i made a small program for summing two numbers
if i used a void type method it will be like this
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
getSum(x,y);
}
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
} }
here if i used a method that returns a value i will get same output!
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
int r = getSum(x,y);
System.out.println("sum = " + r);
}
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}}
so i'm confused what is the benefit of returning a value if i can finish my program with a void type method?
The point is not to get the result but the way we get the result
consider
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
}
will print the output to the screen after calculation
but when we use return
as you have done it later
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}
this function will respond back the sum. that sum can be stored in a variable
can be used afterwards
like in recursion
In small programs, you won't get the difference but while writing the big programs you have to make several functions which are being called several times and you may need the output of one function into other.
In that case, you will require return so that the output of one function can be used into other.
Hope this helps!!
I think the answer is that, if you're calling getSum() method with a return type in any other class.. you would get a returned value which can be used for further processing. .
Where as in void that's not possible... Hope this helps... Reply if any doubts..
I can understand why you have this question.
First of all, you should know that in real development, we do not use console logs.
System.out.Println();
This is used only for debugging and that too in very rare cases.
The whole point of a function is to take some input and convert to something else.
So,
public static int getSum(int x, int y) {
return x+y;
}
public static void main(String[] args) {
System.out.Println(getSum(5,10));
}
This is the better solution.
Best Regards,
Rakesh
When you use the keyword void it means that method doesn't return anything at all. If you declare a return type different to void at the method statement instead, that method must return obligatorily a valid value to the declared return type using the keyword return followed by a variable/value to send back to the class that called the method.
Defining methods here you have the java documentation for a method declaration
Answering your question, in small programs that work with primitive values it doesn't really matter but in complex program when you usually need to return specifics object types, i.e an ArrayList or actually an instance of a class you created you can't simply put it into a System.out.println and send it to the console, mostly you'll want to get something from a method and that something usually can be a more complex object than an integer or a string, the way to get that something is through the return type defined by the method's statement.
A common use of return types is when your method is static and it can't interact with the non-static instance variables of the class, this type of static methods usually get values from their arguments, do a certain kind of progress and then return a result that the method's caller can use.
Returning a value enables you to use that value in whichever way you want, including printing it or assigning it to variable for further processing. If on the other hand you print the value in the method and not return anything, i.e. making the method of type void, then that's all you can do with that method.

Why should I define a method as another variable for integers but not for array in java?

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

Passing the array to method (using random numbers)

I am writing a program piece by piece. I continue to receive compile errors. Can you look at my code to determine my issue?
So here, I am saying that array can store 1000 elements of the double type. Now I want to pass the array to my main method and place 1000 random numbers into the array. So I will create a new method.
public class Practice{
public static void main(String[] args){
double[]array=new double[1000];
}
}
Here, I have created a new method named passArray. I am trying to say that for each array element at its respective index (based on the count) assign a random integer until we reach 1000.
public static void passArray(double[]x){
for(int counter=0; counter<x.length; counter++){
x[counter]=(int)(Math.random()*1000);
}
Okay, so now I want to print my results to determine if my code does what I want it to do. In my main method, I will use an enhanced for loop:
for(double k: array)
System.out.println(k);
}//End of main Method
The problem I continue to encounter is a compile error. However, the output displays 999 values as a double value at random. What in the world am I missing here?
I think you have a typo ( remove the '}' from the for loop )
and you need to pass the array to the method to make it work.
This compiles and runs :
public class Practice{
public static void main(String[] args){
double[]array=new double[1000];
// calling the method
passArray(array);
// print the array
for(double k: array)
System.out.println(k);
//End of main Method
}
public static void passArray(double[]x){
for(int counter=0; counter<x.length; counter++){
// compiles ... but why cast to int if you have double[] ?
x[counter]=(int)(Math.random()*1000);
}
}
}
Not sure about the compile error, but your int to double problem is at the start of your code.
You declared an array of type double:
double[] array = new double[1000];
You're trying to type cast your random values to type int, which the compiler should accept.
x[counter] = (int) (Math.random() * 1000);
However since this is an array of type double, then you're storing the values as doubles. i.e. the values get cast back to double immediately. All that java is really doing is, changing from a double, eg. 567.97, to an int 567, and stroing it as a double again 567.0. Notice that it has now lost all its floating point information from being cast to an int. Or in geekier terms, the mantissa has been set to all 0's.
Either you will have to declare your array as type integer. Or cast back to int every time you access a value.
eg.
int[] array = new int[1000];
public static void passArray(int[] x) {
// code
}
or
System.out.println((int)k);
Edit: Are you getting a compiler error, or warning? There's a big difference. A warning will allow it to run, which your posts suggests is happening, an error will not compile, and thus not run. You may just be getting a warning about the type cast from int to double.

return the maximum value in the array?

I had an an assignment with this question
Write a function maxArray which receives an array of double's and returns the maximum value in the array. using this function
double maxArray(double dar[], int size);
I did what he want and I had problem with the calling sentence within the main method !!
here is my code :
public class Q3 {
public static void main(String[] args) {
double dar[] = { 22.5 , 10.23 , 15.04 , 20.77 };
double max = maxArray(dar,4);
System.out.println("the largest number is : " + max);
}
double maxArray(double dar[], int size) {
double maxV = 0;
for (int i = 0; i < dar.length; i++) {
if (dar[i] > maxV ) {
maxV = dar[i];
}
}
return maxV;
}
}
The reason you can't call your method from main() is that main() is static whereas your method isn't.
Change it to:
static double maxArray(double dar[], int size)
While you're at it, remove size since it's not necessary.
It is probably also worth noting that your method would fail if the array were to contain negative numbers.
your maxArray method is a non static method. you cannot access non-static methods from static methods without an instance of the class, you should create an instance of your class and call maxArray method
double max = new Q3().maxArray(dar,4);
Or alternatively, you could always mark your maxArray method static and call it directly from main method.
Declare your maxArray as static, so you can access it as from a static method main()
or
You create an instance of your class and call it from the object.
your issue is you are trying to call maxArray, a non-static method, from your main method, which is static. That's a problem because a non-static method can only be called from an instance of the class, whereas a static method is called via the class itself.
Either make your maxArray a static method, or initialize a Q3 object in your main method, and call maxArray like that.
Your method has to be static, so you have to say
static double maxArray(double dar[], int size)
Here are some hints how you could improve your method:
since you don't use the value "size" once, you can either throw it out or replace the i < dar.length with i < size.
Also, when initializing maxV in the maxArray method, you might want to use the first value of the array (double maxV = dar[0]), because if all doubles in the array are negative, maxV with the number 0 will be the highest. (You could also use the lowest double value possible by saying double maxV = Double.MIN_NORMAL).
1) make your method static
2) Remember in java use BigDecimal class to do any decimal arithmetic.

Overloading methods in Java

class Overload{
public static void main(String args[]) {
int[] number={1,2,3,4,5,6,7,8,9,10};
int [] num={1,2,3,4,5};
int i;
int sum=0;
sum = f(number);
int sum1= f(num);
System.out.println("The sum is" +sum + ".");
System.out.println("The sum is" +sum1 + ".");
}
public static int f(int[] value) {
int i, total = 0;
for(i=0; i<10; i++) {
total = total + value[ i ];
}
return (total);
}
public static int f(int... x) {
int i, total = 0;
for(i=0; i<10; i++) {
total = total + x[ i ];
}
return (total);
}
}
While compiling the above program I'm getting the error as
C:\Program Files\Java\jdk1.7.0_09\bin>javac Overload.java
Overload.java:30: error: cannot declare both f(int...) and f(int[]) in Overload
public static int f(int... x)
public static int f(int... x)
is nothing but: -
public static int f(int[] x)
with only difference that it does not necessarily needs an argument to be passed. And when you pass individual elements, they are converted to an array internally. So, you are actually passing an array only.
Whereas the later one needs an argument. An empty array at the least.
And both the methods are eligible to be invoked, if you are passing an array as argument.
So the call:
f(new int[] {1, 2});
can be made to both the methods. So, an ambiguity is there.
However, f(5) call can only be made for the first method. Since, 5 cannot be assigned to an array type.
So, the ambiguity only occurs when you are passing an array.
your compiler thinks that the method which takes variable arguments as an argument might be the same as an method which takes an array as an argument. i.e., it thinks there are duplicate methods with the same number of arguments, which contrays overloading rules.
public void m1(int[] arr){
}
public void m1(int...i){
}
are basically same.the only difference is var-args can accept any number of int variables
Method overloading is a feature of java that allows you to more then one method having the same name but different argument list
METHOD OVERLOADING IS ALSO KNOWN AS STATIC POLYMORPHISM
Argument list must be differ
1) Numbers of Parameters "not the same parameters"
2) Data type of parameters "does not have the same datatype of parameters"
3) Sequence of Datatype of parameters "its may be possible to change the sequence the of datatype."
The method overloading have the same argument then it must be the return type is different suppose
public class Test
{
public int printVal(int i,int j)
{
System.out.println("Integer Return type")
return i*j;
}
public double printVal(int i,int j)
{
System.out.println("Double Return type")
return i*j;
}
}
In the above class we have the two method one have int return type and another have double return type so that can be possible in method overloading.
Sequence of datatype it means
public class Test
{
public void display(String surname ,String name)
{
System.out.println("Surname = "+surname);
System.out.println("Name = "+name);
}
public void display(String name,String surname)
{
System.out.println("Name = "+name);
System.out.println("Surname = "+surname);
}
}
in above example we have two method as a same datatype but its sequence is differ this case is also called method overloading..
The method signature is the same. Thus overload is impossible. Change the method signature.
There's a definition of method signature in Java from wikipedia.
In the Java programming language, a method signature is the method name and the number and type of its parameters. Return types and thrown exceptions are not considered to be a part of the method signature.
In your code you have two methods with the same signature f(int[] value). Another function uses int... as an argument, but it's equivalent to int[].

Categories