Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

unix

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

when I am runnig the code in unix system.exit(Integer.parseInt(e.getMessage())) is giving 254

output:

-2  
-2  
254
like image 393
akash Avatar asked Feb 24 '14 14:02

akash


3 Answers

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

The reason you are getting 254 is because it's the lower 8 bits of int -2 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
like image 102
ikegami Avatar answered Oct 09 '22 13:10

ikegami


Since System.exit() needs to take a positive value between 0-255 the -2 will become 256 - 2 = 254.

like image 29
Mihai238 Avatar answered Oct 09 '22 12:10

Mihai238


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

A binary level conversion occurs from int to byte here (254 is the low level byte of the -2 integer).

Note that this doesn't happen in java (the native Shutdown.halt0 method receives an int) as this could be different on a different platform.

like image 1
Denys Séguret Avatar answered Oct 09 '22 12:10

Denys Séguret