EzDevInfo.com

return interview questions

Top return frequently asked interview questions

Does finally always execute in Java?

I have a try/catch block with returns inside it. Will the finally block be called?

For example:

try {  
    something();  
    return success;  
}  
catch (Exception e) {   
    return failure;  
}  
finally {  
    System.out.println("i don't know if this will get printed out.");
}

I know I can just type this in an see what happens (which is what I'm about to do, actually) but when I googled for answers nothing came up, so I figured I'd throw this up as a question.


Source: (StackOverflow)

How do you return multiple values in Python?

The canonical way to return multiple values in languages that support it is often tupling.

Option: Using a tuple

Consider this trivial example:

def f(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return (y0,y1,y2)

However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.

Option: Using a dictionary

The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a dict.

Consider the following:

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)

Now, we have a mechanism whereby we can project out a particular member of the returned object. For example,

result['y0']

Option: Using a class

However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:

class ReturnValue(object):
  def __init__(self, y0, y1, y2):
     self.y0 = y0
     self.y1 = y1
     self.y2 = y2

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return ReturnValue(y0, y1, y2)

In python the previous two are perhaps very similar in terms of plumbing- After all { y0, y1, y2 } just end up being entries in the internal __dict__ of the ReturnValue.

There is one additional feature provided by Python though for tiny objects, the __slots__ attribute. The class could be expressed as:

class ReturnValue(object):
  __slots__ = ["y0", "y1", "y2"]
  def __init__(y0, y1, y2):
     self.y0 = y0
     self.y1 = y1
     self.y2 = y2

From the Python Reference Manual:

The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.

Option: Using a list

Another suggestion which I'd overlooked comes from Bill the Lizard:

def h(x):
  result = [x + 1]
  result.append(x * 3)
  result.append(y0 ** y3)
  return result

This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are mutable, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.

Question

After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?

I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel implied interfaces should be preferred to explicit interfaces, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning.

So, how do -you- return multiple values in Python?


Source: (StackOverflow)

Advertisements

Why main does not return 0 here?

I was just reading

ISO/IEC 9899:201x Committee Draft — April 12, 2011

in which i found under 5.1.2.2.3 Program termination

..reaching the } that terminates the main function returns a value of 0. 

it means if you don't specify any return statement in main(), and if the program runs successfully, then at the closing brace } of main will return 0.

But in the following code i don't specify any return statement, yet it does not return 0

#include<stdio.h>
int sum(int a,int b)
{
return (a + b);
}

int main()
{
    int a=10;
    int b=5;
    int ans;    
    ans=sum(a,b);
    printf("sum is %d",ans);
}

compile

gcc test.c  
./a.out
sum is 15
echo $?
9          // here it should be 0 but it shows 9 why?

Source: (StackOverflow)

Returning from a finally block in Java

I was surprised recently to find that it's possible to have a return statement in a finally block in Java.

It seems like lots of people think it's a bad thing to do as described in 'Don't return in a finally clause'. Scratching a little deeper, I also found 'Java's return doesn't always' which shows some pretty horrible examples of other types of flow control in finally blocks.

So, my question is, can anyone give me an example where a return statement (or other flow control) in a finally block produces better / more readable code?


Source: (StackOverflow)

How to return multiple objects from a Java method?

I want to return two objects from a Java method and was wondering what could be a good way of doing so?

The possible ways I can think of are: return a HashMap (since the two Objects are related) or return an ArrayList of Object objects.

To be more precise, the two objects I want to return are (a) List of objects and (b) comma separated names of the same.

I want to return these two Objects from one method because I dont want to iterate through the list of objects to get the comma separated names (which I can do in the same loop in this method).

Somehow, returning a HashMap does not look a very elegant way of doing so.


Source: (StackOverflow)

Setting PayPal return URL and making it auto return?

This is a follow up question to: PHP: Easy way to start PayPal checkout?

So, my problem is that I am specifying the return url. However, after paying with PayPal, I end up at a a screen that says:

You just completed your payment. XXXX, you just completed your payment. Your transaction ID for this payment is: XXXXXXXXXXXXX.

We'll send a confirmation email to XX@XXXX.com. This transaction will appear on your statement as PAYPAL.

Go to PayPal account overview

I need it to not show this screen and go directly to the return URL. I have:

  • Set the "return" variable
  • Set the "rm" variable to: 2 (which according to the guide = "the buyer’s browser is redirected to the return URL by using the POST method, and all payment variables are included")

In fact, here's my whole form:

<form method="post" action="https://www.sandbox.paypal.com/cgi-bin/webscr">
  <input type="hidden" value="_xclick" name="cmd">
  <input type="hidden" value="onlinestore@thegreekmerchant.com" name="business">
  <!-- <input type="hidden" name="undefined_quantity" value="1" /> -->
  <input type="hidden" value="Order at The Greek Merchant:&lt;Br /&gt;Goldfish Flock BLG&lt;br /&gt;" name="item_name">
  <input type="hidden" value="NA" name="item_number">
  <input type="hidden" value="22.16" name="amount">
  <input type="hidden" value="5.17" name="shipping">
  <input type="hidden" value="0" name="discount_amount">        
  <input type="hidden" value="0" name="no_shipping">
  <input type="hidden" value="No comments" name="cn">
  <input type="hidden" value="USD" name="currency_code">
  <input type="hidden" value="http://XXX/XXX/XXX/paypal/return" name="return">
  <input type="hidden" value="2" name="rm">      
  <input type="hidden" value="11255XXX" name="invoice">
  <input type="hidden" value="US" name="lc">
  <input type="hidden" value="PP-BuyNowBF" name="bn">
  <input type="submit" value="Place Order!" name="finalizeOrder" id="finalizeOrder" class="submitButton">
</form>

Any idea how I can get it to automatically go back? Alternatively, how do I get the result of the payment back to my website so I can update the database? What is IPN?


Source: (StackOverflow)

How to "return an object" in C++?

I know the title sounds familiar as there are many similar questions, but I'm asking for a different aspect of the problem (I know the difference between having things on the stack and putting them on the heap).

In Java I can always return references to "local" objects

public Thing calculateThing() {
    Thing thing = new Thing();
    // do calculations and modify thing
    return thing;
}

In C++, to do something similar I have 2 options

(1) I can use references whenever I need to "return" an object

void calculateThing(Thing& thing) {
    // do calculations and modify thing
}

Then use it like this

Thing thing;
calculateThing(thing);

(2) Or I can return a pointer to a dynamically allocated object

Thing* calculateThing() {
    Thing* thing(new Thing());
    // do calculations and modify thing
    return thing;
}

Then use it like this

Thing* thing = calculateThing();
delete thing;

Using the first approach I won't have to free memory manually, but to me it makes the code difficult to read. The problem with the second approach is, I'll have to remember to delete thing;, which doesn't look quite nice. I don't want to return a copied value because it's inefficient (I think), so here come the questions

  • Is there a third solution (that doesn't require copying the value)?
  • Is there any problem if I stick to the first solution?
  • When and why should I use the second solution?

Source: (StackOverflow)

Python -- return, return None, and no return at all

Consider three functions:

def my_func1():
  print "Hello World"
  return None

def my_func2():
  print "Hello World"
  return

def my_func3():
  print "Hello World"

They all appear to return None. Are there any differences between how the returned value of these functions behave? Are there any reasons to prefer one versus the other?


Source: (StackOverflow)

Return array in a function

I have an array int arr[5] that is passed to a function fillarr(int arr[]):

int fillarr(int arr[])
{
    for(...);
    return arr;
}
  1. How can I return that array?
  2. How will I use it, say I returned a pointer how am I going to access it?

Source: (StackOverflow)

Enumerable.Empty() equivalent for IQueryable

When a method returns IEnumerable<T> and I do not have anything to return, we can use Enumerable.Empty<T>().

Is there an equivalent to the above for a method returning IQueryable<T>


Source: (StackOverflow)

If I return inside a with block is the file guaranteed to close?

Take the following code

with open(path, mode) as f:
    return [line for line in f if condition]

Will the file be closed properly, or does return somehow bypass the context manager?

(Python 2.7)


Source: (StackOverflow)

Is having a return statement just to satisfy syntax bad practice?

Consider the following code:

public Object getClone(Cloneable a) throws TotallyFooException {

    if (a == null) {
        throw new TotallyFooException();
    }
    else {
        try {
            return a.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

    //cant be reached, in for syntax
    return null;

}

The return null; is necessary since an exception may be caught, however in such a case since we already checked if it was null (and lets assume we know the class we are calling supports cloning) so we know the try statement will never fail.

Is it bad practice to put in the extra return statement at the end just to satisfy the syntax and avoid compile errors (with a comment explaining it will not be reached), or is there a better way to code something like this so that the extra return statement is unnecessary?


Source: (StackOverflow)

Multiple return statements without compiler error

This was an interview question:

public class Demo {

    public static void main(String[] args) {
        System.out.println(foo());
    }

    static String foo() {
        try {
            return "try ...";
        } catch (Exception e) {
            return "catch ...";
        } finally {
            return "finally ..."; //got as result
        }
    }
}

My question is why there are no compile time errors. When I have the return statement in my finally block, it is bound to return from finally instead of try and catch block. I tried to compile this code with -Xlint option, it gives a warning as.

warning: [finally] finally clause cannot complete normally

Source: (StackOverflow)

How can I return two values from a function in Python?

I would like to return two values from a function in two separate variables. For example:

def select_choice():
    loop = 1
    row = 0
    while loop == 1:
        print('''Choose from the following options?:
                 1. Row 1
                 2. Row 2
                 3. Row 3''')

        row = int(input("Which row would you like to move the card from?: "))
        if row == 1:
            i = 2
            card = list_a[-1]
        elif row == 2:
            i = 1
            card = list_b[-1]
        elif row == 3:
            i = 0
            card = list_c[-1]
        return i
        return card

And I want to be able to use these values separately. When I tried to use return i, card, it returns a tuple and this is not what I want.


Source: (StackOverflow)

Is it bad practice to use return inside a void method?

Imagine the following code:

void DoThis()
{
    if (!isValid) return;

    DoThat();
}

void DoThat() {
    Console.WriteLine("DoThat()");
}

Is it OK to use a return inside a void method? Does it have any performance penalty? Or it would be better to write a code like this:

void DoThis()
{
    if (isValid)
    {
        DoThat();
    }
}

Source: (StackOverflow)