Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Java equivalent to C#'s 'checked' keyword?

Tags:

java

c#

casting

Yes, it's a trivial piece of code to write, but I still wonder if there's a built-in replacement.

Here's the code:

/**
 * Cast x to int, throw an exception if there's loss of information
 */
public static int safeLongToInt(long x)
{
  int result = (int) x;
  if (result != x)
    throw new RuntimeException("long doesn't fit in an int: " + x);

  return result;
}

The code in C# would be:

int foo;
long bar = ...;
checked
{
  foo = bar;
}
like image 994
ripper234 Avatar asked Nov 03 '09 18:11

ripper234


2 Answers

No there's no equivalent, check out this keyword chart.

like image 93
Joseph Avatar answered Nov 11 '22 13:11

Joseph


The (pre-release) open-source Guava library has the method you seek:

Ints.checkedCast(long)

like image 26
Kevin Bourrillion Avatar answered Nov 11 '22 13:11

Kevin Bourrillion