- Returning a Value from a Method
- Returning a Class or Interface
- Can we return this keyword from a method in java?
- Returning “this”
- Example
- Output
- Java what does this method return
- What does this method return?
- Java method return this; [duplicate]
- Java When outputting String and method return, why does method return output first?
- What «return this» means in Java
Returning a Value from a Method
You declare a method’s return type in its method declaration. Within the body of the method, you use the return statement to return the value.
Any method declared void doesn’t return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:
If you try to return a value from a method that is declared void , you will get a compiler error.
Any method that is not declared void must contain a return statement with a corresponding return value, like this:
The data type of the return value must match the method’s declared return type; you can’t return an integer value from a method declared to return a boolean.
The getArea() method in the Rectangle Rectangle class that was discussed in the sections on objects returns an integer:
// a method for computing the area of the rectangle public int getArea()
This method returns the integer that the expression width*height evaluates to.
The getArea method returns a primitive type. A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we might have a method like this:
public Bicycle seeWhosFastest(Bicycle myBike, Bicycle yourBike, Environment env) < Bicycle fastest; // code to calculate which bike is // faster, given each bike's gear // and cadence and given the // environment (terrain and wind) return fastest; >
Returning a Class or Interface
If this section confuses you, skip it and return to it after you have finished the lesson on interfaces and inheritance.
When a method uses a class name as its return type, such as whosFastest does, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type. Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.lang.Number , which is in turn a subclass of Object , as illustrated in the following figure .
The class hierarchy for ImaginaryNumber
Now suppose that you have a method declared to return a Number :
public Number returnANumber()
The returnANumber method can return an ImaginaryNumber but not an Object . ImaginaryNumber is a Number because it’s a subclass of Number . However, an Object is not necessarily a Number it could be a String or another type.
You can override a method and define it to return a subclass of the original method, like this:
public ImaginaryNumber returnANumber()
This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.
Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.
Can we return this keyword from a method in java?
The «this» keyword in Java is used as a reference to the current object, within an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables, and methods.
Returning “this”
Yes, you can return this in Java i.e. The following statement is valid.
When you return «this» from a method the current object will be returned.
Example
In the following Java example, the class Student has two private variables name and age. From a method setValues() we are reading values from user and assigning them to these (instance) variables and returning the current object.
public class Student < private String name; private int age; public Student SetValues()< Scanner sc = new Scanner(System.in); System.out.println("Enter the name of the student: "); String name = sc.nextLine(); System.out.println("Enter the age of the student: "); int age = sc.nextInt(); this.name = name; this.age = age; return this; >public void display() < System.out.println("name: "+name); System.out.println("age: "+age); >public static void main(String args[]) < Student obj = new Student(); obj = obj.SettingValues(); obj.display(); >>
Output
Enter the name of the student: Krishna Kasyap Enter the age of the student: 21 name: Krishna Kasyap age: 21
Java what does this method return
Solution 4: You have blank array — default zeros as it is int array — Therefore, in the following method invocation expression you are invoking the since is a variable of type .
What does this method return?
I have just started learning to program. I was wondering what this method returns:
public int doSomething(int size) < int[] b = new int [size]; int c = 0; for (int d : b) < c = c + d; >return c; >
There is nothing adding in the array and the c value is still zero .
You might confused with the line
That is java for each loop .
- int[] b = new int [size]; will initialise every element in the array to zero.
- for (int d : b) notation iterates over every element in the array.
So the computation is summing the elements of the array with answer zero.
(Note that in C and C++ arrays elements are not initialised to zero and the behaviour of a similar construct in those languages would be undefined).
The cycle accumulates the sum of the values in the array b into the variable c . As an integer is set to 0 by default and you never change the values of the elements in b , the sum of size zeros is still zero and thus c is 0 when it is returned.
You have blank array — default zeros as it is int array — So currently it is returning zero. Add some numbers in array you will get their addition in returned c.
public int doSomething(int size) < int[] b = new int [size]; b[0]=5; // add integers like this to get non zero return b[1]=8; . . b[size-1]=3; int c = 0; for (int d : b) < c = c + d; >return c; >
How to call a method that returns some other method in, A method is a collection of statements that perform some specific task and return the result to the caller. A method can also perform some specific task without returning anything. In this article, we will understand how to call a method that returns some other method in Java. In Java, there are two types of …
Java method return this; [duplicate]
What does return this statement do in this line? I’ve Googled a lot but found no relevant answers regarding this 🙁 There is a mistake in the setA method but that is intentional.
Here is the full code, it is working fine.
public class E < int a; public int getA() < return a; >public void setA(int a) < a = a; >E show() < return this; //What is the role of this line? >public static void main(String[] args) < E obj = new E(); obj.setA(10); System.out.println(obj.getA()); E obj2 = obj.show(); System.out.println(obj2.getA()); >>
ob.show() will return the same instance of the object to which obj is having a reference to. Now obj and obj2 will be having a reference to the same object. You can modify your object using any reference varible and the changes will be reflected both sides .
How to Return an Array in Java?, Keypoint 1: Method returning the array must have the return type as an array of the same data type as that of the array being returned. The return type may be the usual Integer, Double, Character, String, or user-defined class objects as well. // Method returning an integer array. int [] methodName () <> // Method returning …
Java When outputting String and method return, why does method return output first?
In the code below, if the string «Mult» comes before the test1(4) method call, why does the method output before the string? And why does it bounce form outputting the first part of the method, then leaves the method to output the string, then returns to the method to output the method’s return value?
public class Scratch < public static void main(String[] args)< System.out.println("Mult:" + test1(4)); >public static int test1(int n) < System.out.println("N:" + n); return n*2; >>
The first thing to note is when you use the + with two operands where one of the two operands is a String , the result of the expression is a String .
Therefore, in the following method invocation expression
System.out.println("Mult:" + test1(4));
you are invoking the PrintStream#println(String) since out is a variable of type PrintStream . Note how the method accepts a single String argument. Therefore, the String has to be resolved from the String concatenation of
For that to happen, the test1(4) method has to be executed.
public static int test1(int n)
This method again uses PrintStream#println(String) but with the argument
This is another String concatenation that produces the String value
for this particular invocation. The produced String value is then used as an argument to the println(..) method which outputs it to your program’s standard output.
The method then returns the value 8 , since 4 * 2 = 8 .
That return value is the value of invoking the test1(4) method. So
System.out.println("Mult:" + test1(4));
Then String concatenation occurs, transforming
That String is then used as the single argument to the println(..) method which outputs it to your program’s standard output.
In the code below, if the string «Mult» comes before the test1(4) method call, why does the method output before the string?
Because you’re calling the method before you’re calling System.out.println with the «Mult:» part.
Basically, your code is equivalent to:
public static void main(String[] args) < int tmp = test1(4); // This prints N:4 System.out.println("Mult:" + tmp); >
If you think about it, the test1 method has to be completed before the string concatenation can occur (otherwise we can’t know what the right hand side of the concatenation operator is), and the string concatenation has to occur before the System.out.println call can occur (otherwise we can’t know what we’re going to print). Make sense/
System.out.println("Mult:" + test1(4));
is run, test1(4) must be evaluated before it can be System.out.println’d. So, the JVM will run the following:
evalate result of test1(4) < print ("N:" + 4); return 2*4; >evalate result of "Mult:" + returnedValue
The JVM cannot print something before it knows its value. In this case, test1(4) get evaluated first so the JVM knows what to print out (the return value).
You could also complete the task this way>>
int result = test1(4); //This prints out 4 and evaluates to 8 System.out.println("Mult: " + result); //This concats "Mult: " and 8 after converting it to of type String
The above line is an expression whose value is the concatenation of «Mult:» , and of the result of test1(4) . So, to be able to know the result of this concatenation, test1(4) is executed. This execution prints «N:4» , and then multiplies n by 2, returning 8. 8 is then concatenated with «Mult:» , and the result is printed.
When and how to Use «return this» in Java, 2 Answers. returns the instance itself from the method. Returning the instance is usually (but not always) used when implementing a fluent interface, which allows code to look like this: This in turn is very commonly used (but not required) when implementing the builder pattern. return this simply means …
What «return this» means in Java
posted 9 years ago
In crawljax open-source code, I seen this method,
I got, it should return «Options». But, «return this» ? I dint get the meaning of this. Because in the above code, they called method addOption(Params. ); they are not catching anything from that method then how can they return «return this» ? Please explain me what «return this» means.
Thanks All:
Ramakrishna K.C
posted 9 years ago
«return this» means return the current object instance. In your example it will return the Options object as shown by the addOption() method. For more information on the this keyword you can read the Java language specification.
posted 9 years ago
It’ll return the instance of . This is nothing but,
posted 9 years ago
The addOption() method from your first example must be part of a class right? For example this class might be look like as simple as this:
So, the return this simply means return me the current object instance, which is the instance of the class Options. The keyword this is a reference to the current object.
posted 9 years ago
The addOption() method from your first example must be part of a class right?
Obviously yes. But, they called addOption() method and catching nothing. I mean,
see the above code. The above code from another class. Creating instance of Options and then calling options.addOption(Params. ); they called and that method is returning something like «return this». But, they are not capturing «this» instance. Then, why they are returning «this»?
Sheriff
posted 9 years ago
- 1
Returning this allows several calls on the same object to be «chained». Most often I see this used with a StringBuilder:
This is functionally identical to the following code:but requires less typing and, at least for some people, is more readable (this is obviously subjective).
Note that the append() methods in the second example returns this as well, but the caller just doesn’t use it. You aren’t required to «use» the value returned by a method in Java, but returning «this» allows to chain the methods as outlined in the first example.
Returning this is also used by so called Fluent interfaces. However, the concept of fluent interfaces is broader than just returning this — fluent interfaces always return the instance that is best suited for the particular context of the operation that was performed. (Uh, I hope the Wikipedia article makes better job of explaining it than I did here.)