How to cast int to byte in Java

4 Answers

0 votes
package javaapplication1;

public class JavaApplication1 {

    public static void main(String[] args) {

        try {

            int n = 13;
            
            byte b = (byte) n; 

            System.out.println(n);
            System.out.println(b);

        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
}

/*
              
run:
 
13
13
     
 */

 



answered Dec 3, 2016 by avibootz
0 votes
package javaapplication1;

public class JavaApplication1 {

    public static void main(String[] args) {

        try {

            int n = 127;
            
            byte b = (byte) n; 

            System.out.println(n);
            System.out.println(b);

        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
}

/*
              
run:
 
127
127
     
 */

 



answered Dec 3, 2016 by avibootz
0 votes
package javaapplication1;

public class JavaApplication1 {

    public static void main(String[] args) {

        try {

            int n = 128;
            
            byte b = (byte) n; 

            System.out.println(n);
            System.out.println(b);

        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
}

/*
              
run:
 
128
-128
     
 */

 



answered Dec 3, 2016 by avibootz
0 votes
package javaapplication1;

public class JavaApplication1 {

    public static void main(String[] args) {

        try {

            int n = -129;
            
            byte b = (byte) n; 

            System.out.println(n);
            System.out.println(b);

        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
}

/*
              
run:
 
-129
127
     
 */

 



answered Dec 3, 2016 by avibootz

Related questions

1 answer 183 views
183 views asked May 27, 2019 by avibootz
1 answer 166 views
166 views asked May 28, 2019 by avibootz
1 answer 195 views
195 views asked Jan 2, 2022 by avibootz
1 answer 183 views
183 views asked Sep 16, 2020 by avibootz
1 answer 174 views
174 views asked Sep 16, 2020 by avibootz
1 answer 146 views
146 views asked May 28, 2019 by avibootz
1 answer 170 views
170 views asked Mar 17, 2017 by avibootz
...