For example, I want to create a function that can return any number (negative, zero, or positive).
However, based on certain exceptions, I\'d like the function to re
This may not be the best solution depending on what you want to do, but an easy way to solve the problem might be to have the function return an int or a constant outside the possible range (such as RETURNED_FALSE/TRUE) and check for that.
my teacher had a cool idea for a tryParse C# like method in java hope it helps
import java.util.Scanner;
public class Program {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter number");
String input = scanner.next();
int[] num ={0};
if(tryParse(input,num))
System.out.println(num[0] * num[0]);
}
static boolean tryParse(String inputString,int[] outputInt){
try{
outputInt[0] = Integer.parseInt(inputString);
return true;
}catch(Exception e){
return false;
}
}
}
You could technically do this:
public <T> T doWork()
{
if(codition)
{
return (T) new Integer(1);
}
else
{
return (T) Boolean.FALSE;
}
}
Then this code would compile:
int x = doWork(); // the condition evaluates to true
boolean test = doWork();
But you could most certainly encounter runtime exceptions if the method returns the wrong type. You also must return objects instead of primitives because T is erased to java.lang.Object, which means the returned type must extend Object (i.e. be an object). The above example makes use of autoboxing to achieve a primitive return type.
I certainly wouldn't recommend this approach because IMO you need to evaluate your use of exception handling. You catch exceptions in exceptional cases if you can do something with that exception (i.e. recover, persist, retry, etc.). Exceptions are an exception to the expected workflow, not a part of it.
inout parameters only work for objects that can be mutated. For String inout parameters, pass in StringBuilders instead of Strings, then replace() their values.
No, you can't do that in Java.
You could return an Object
though. And by returning an object you could technically return a derived class such as java.lang.Integer
or java.lang.Boolean
. However, I don't think it's the best idea.
No, one return reference to a customer.
You can write a response object that encapsulates a boolean and an int together and set the values according to your whim.
But if I was a user I'd think your design was confusing.