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 265 views
265 views asked May 27, 2019 by avibootz
1 answer 258 views
258 views asked May 28, 2019 by avibootz
1 answer 285 views
285 views asked Jan 2, 2022 by avibootz
1 answer 266 views
266 views asked Sep 16, 2020 by avibootz
1 answer 258 views
258 views asked Sep 16, 2020 by avibootz
1 answer 237 views
237 views asked May 28, 2019 by avibootz
1 answer 262 views
262 views asked Mar 17, 2017 by avibootz
...