-2

if 123/33 prints out 3 and 3 is an integer if we cast it to float ( (float)123/33 )how do we get the decimal places from the integer 3. does 3 contains floating points internally what ?

 public static void test() {
        System.out.println("==========");
        System.out.println(123/33); // prints 3 
        System.out.println((float)123/33); // prints 3.7272727 
        //so if we cast it to float we get the decimal points also (.7272727)
    }
RoHaN
  • 1,356
  • 2
  • 11
  • 21
  • 1
    Look at [operator precedence](http://introcs.cs.princeton.edu/java/11precedence/). Operators are evaluated **left to right** and cast has a **higher** precedence than divide. So you are actually doing `((float) 123) / 33`. – Boris the Spider Jun 10 '15 at 07:23
  • 1
    @AlessandroDaRugna not really a dup - that question is asked by casting the _result_ doesn't work. This question is asking about the precedence of the cast operator. – Boris the Spider Jun 10 '15 at 07:25
  • @BoristheSpider the accepted anwer of the question I linked explains also the precedence and how the cast works. IMHO this is a dup. Let's see what the rest of the community thinks, I may be wrong after all. – Alessandro Da Rugna Jun 10 '15 at 07:28

2 Answers2

2

The cast does not apply to the entire expression 123/33. You're casting the value 123 to a float, which causes any further operations to use floating-point math.

shmosel
  • 49,289
  • 6
  • 73
  • 138
1

123 will be casted(converted) to float and then the division happens, so the result will be float value.

System.out.println("==========");
System.out.println(123/33); // prints 3 
System.out.println((float)123); // prints 123.0 
System.out.println((float)123/33); // prints 3.7272727 
Naman Gala
  • 4,670
  • 1
  • 21
  • 55