Why am I getting two different values ​​from system.out.println () and system.exit ()?

System.out.println(Integer.parseInt(e.getMessage())); System.out.println(e.getMessage()); System.exit(Integer.parseInt(e.getMessage())); 

when I run the code in unix system.exit(Integer.parseInt(e.getMessage())) gives 254

output:

 -2 -2 254 
+6
source share
3 answers

The operating system exit codes are unsigned 8-bit integers, so the only valid exit codes are 0..255.

The reason you get 254 is because the lower 8 bits of int -2 are treated as an unsigned number.

 $ for q in -2 -1 0 1 2 253 254 255 256 257 ; do perl -e'exit $ARGV[0]' -- $q printf '%3d => %3d\n' $q $? done -2 => 254 -1 => 255 0 => 0 1 => 1 2 => 2 253 => 253 254 => 254 255 => 255 256 => 0 257 => 1 
+2
source

Since System.exit () should take a positive value from 0 to 255, -2 will become 256 - 2 = 254 .

+2
source

The exit status code on Linux and Unix is ​​8 bits and unsigned (0-255) .

Binary level conversion comes from int to byte here (254 is the least significant byte of an integer).

Note that this does not happen in java (the native Shutdown.halt0 method gets int), as this may be different on another platform.

+1
source

All Articles