Java Type Casting & Operators

Convert types and calculate.

✍️ 2 exercises in this lesson

Type casting

  • Widening (automatic): smaller → larger type, e.g. int → double.
  • Narrowing (manual): (int) 9.78 → 9.
  • From String: Integer.parseInt("42"), Double.parseDouble("3.5").

Java Operators

Arithmetic + - * / % ++ --, assignment += -=, comparison == != > <, logical && || !.

Dividing two ints gives an int: 7 / 2 is 3. Use 7 / 2.0 for 3.5.

Key Takeaways: Java Type Casting & Operators

Mastering Java Type Casting & Operators helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java Type Casting & Operators Code Example

Java
public class Main {
    public static void main(String[] args) {
        double d = 9.78;
        int i = (int) d;
        int parsed = Integer.parseInt("42");

        System.out.println(i);
        System.out.println(parsed + 8);
        System.out.println(7 / 2);
        System.out.println(7 / 2.0);
        System.out.println(17 % 5);

        int x = 10;
        x += 5;
        System.out.println(x > 12 && x < 20);
    }
}
Output
9
50
3
3.5
2
true
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Java Type Casting & Operators Practice Exercises

Check what you learned in “Java Type Casting & Operators”.

/ 2 solved
Fill in the blank

Convert a double to an int (narrowing).

int i =  9.78;
✓ Correct! Not quite. Try again.
Multiple choice

What is 7 / 2 in Java when both are int?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services