Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Operators and Type Conversion Fundamentals

Tech 1

Type Conversion

Java supports automatic and explicit type conversion between compatible data types.

Implicit Type Conversion

Asigning a value from a narrower type to a wider type happens automatically:

double value = 100;
System.out.println(value); // 100.0

Type widening order:

byte → short → char → int → long → float → double

Critical rules to remember:

  1. Integer literals default to int type. When byte, short, or char values participate in operations, they automatically promote to int.
byte b1 = 15;
byte b2 = 25;
int result = b1 + b2; // Correct: sum is int type
// byte result = b1 + b2; // Compilation error: int cannot be assigned to byte
byte result = (byte) (b1 + b2); // Valid: explicit casting
  1. The boolean type cannot be converted to or from any other primitive type.

Explicit Type Conversion

Converting from a wider type to a narrower type requires casting:

targetType variableName = (targetType) value;
double source = 7.8;
int target = (int) source;
System.out.println(target); // 7, decimal truncated

Constant Optimization

The compiler evaluates constant expressions at compile time:

byte x = 5;
byte y = 6;
byte z = x + y;     // Compilation error
byte w = 5 + 6;     // Compiles successfully: result 11 fits in byte range

During compilation, constant arithmetic is computed directly, and the result is verified against the target type's range. If within range, compilation succeeds; otherwise, it fails.


Operators

Arithmetic Operators

Operators and Expressions

An operator performs operations on operands. An expression combines operands with operators according to Java syntax.

int a = 15;
int b = 40;
int c = a + b; // '+' is the operator, 'a + b' is an arithmetic expression

Arithmetic Operator Reference

Symbol Operation Example
+ Addition 5 + 3 → 8
- Subtraction 10 - 4 → 6
* Multiplication 6 * 7 → 42
/ Division 20 / 4 → 5
% Modulus 17 % 5 → 2

Key behaviors:

  • / returns the quotient, % returns the remainder
  • Integer division discards the decimal portion
int dividend = 25;
int divisor = 4;
System.out.println(dividend / divisor); // 6
System.out.println(dividend % divisor); // 1

Character Arithmetic

Characters convert to their Unicode numeric values for calculations:

'a' → 97   (consecutive: 'b'=98, 'c'=99, ...)
'A' → 65   (consecutive: 'B'=66, 'C'=67, ...)
'0' → 48   (consecutive: '1'=49, '2'=50, ...)
char letter1 = 'x';
System.out.println(letter1 + 1); // 121

char letter2 = 'M';
System.out.println(letter2 - 1); // 76

char digit = '7';
System.out.println(digit); // 7 (character, not number)
System.out.println(digit + 1); // 49 + 1 = 50

Type Promotion Rules:

When operands have different types in an expression:

  1. byte, short, and char always promote to int first
  2. The result type matches the highest-ranked operand
byte p = 8;
byte q = 12;
// byte r = p + q; // Error: result is int
int r = p + q; // Correct

int num1 = 50;
double num2 = 30.5;
double num3 = num1 + num2; // num1 promotes to double

String Concatenation

The + operator becomes string concatenation when any operand is a String:

System.out.println("Total: " + 100); // Total: 100

Evaluation proceeds left-to-right:

System.out.println(5 + 10 + " Units");     // 15 Units
System.out.println("Result: " + 5 + 10);   // Result: 510
System.out.println("Sum: " + (5 + 10));     // Sum: 15

Digit Extraction Example

Extract individual digits from a three-digit number:

import java.util.Scanner;

public class DigitExtractor {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a three-digit number: ");
        int number = scanner.nextInt();
        
        int ones = number % 10;
        int tens = (number / 10) % 10;
        int hundreds = number / 100;
        
        System.out.println("Digit breakdown of " + number + ":");
        System.out.println("Hundreds: " + hundreds);
        System.out.println("Tens: " + tens);
        System.out.println("Ones: " + ones);
    }
}

Increment and Decrement Operators

Symbol Effect
++ Increase value by 1
-- Decrease value by 1

Usage patterns:

Position Behavior
Operand suffix (x++) Use current value, then increment
Operand prefix (++x) Increment first, then use new value
int count = 10;
count++;        // 11
++count;        // 12

int a = 5;
int b = a++;    // b = 5, a = 6 (use before increment)

int c = 5;
int d = ++c;    // d = 6, c = 6 (increment before use)

Complex evaluation:

int x = 3;
int y = x++ + x++ + x++;
System.out.println(y); // 12

Execution trace:

  1. First x++ → 3 (x becomes 4)
  2. Second x++ → 4 (x becomes 5)
  3. Third x++ → 5 (x becomes 6)
  4. Result: 3 + 4 + 5 = 12

Assignment Operators

Symbol Description Equivalent
= Simple assignment a = b
+= Add and assign a = a + b
-= Subtract and assign a = a - b
*= Multiply and assign a = a * b
/= Divide and assign a = a / b
%= Modulus and assign a = a % b

Compound assignment operators perform implicit casting:

short s = 100;
// s = s + 10;      // Error: int result
s += 10;            // Valid: equivalent to s = (short)(s + 10)

Relational Operators

All relational operators return boolean values.

Operator Description Example Result
== Equal to true/false
!= Not equal to true/false
> Greater than true/false
>= Greater than or equal true/false
< Less than true/false
<= Less than or equal true/false
int first = 45;
int second = 78;

boolean check1 = first == second;  // false
boolean check2 = first != second;  // true
boolean check3 = first > second;   // false
boolean check4 = first <= second;  // true

Common mistake: confusing == (comparison) with = (assignment).


Logical Operators

Logical operators combine boolean expressions:

Operator Name Behavior
& AND Both true yields true
| OR Either true yields true
^ XOR Different values yield true
! NOT Inverts boolean value
int p = 15;
int q = 20;
int r = 25;

System.out.println((p > q) & (p > r)); // false & false → false
System.out.println((p < q) & (p < r)); // true & true → true
System.out.println((p > q) | (p < r)); // false | true → true
System.out.println((p > q) ^ (p < r)); // false ^ true → true
System.out.println(!(p > q));           // !false → true

Short-Circuit Operators

Operator Short-circuit behavior
&& If left operand is false, right side never evaluates
|| If left operand is true, right side never evaluates
int m = 8;
int n = 9;

// Using &, both expressions evaluate
System.out.println((m > 10) & (n++ > 5));  // false & true → false
System.out.println("n = " + n);            // n = 10

// Using &&, second expression skipped
System.out.println((m > 10) && (n++ > 5)); // false && ... → false
System.out.println("n = " + n);            // n = 10, not 11
Operator Left → false Left → true
& Evaluates right Evaluates right
| Evaluates right Evaluates right
&& Skips right Evaluates right
|| Evaluates right Skips right

Ternary Operator

Syntax:

condition ? valueIfTrue : valueIfFalse

The condition evaluates to a boolean. Returns the second expression if true, the third if false.

int num1 = 85;
int num2 = 120;
int maximum = (num1 > num2) ? num1 : num2;
System.out.println("Maximum: " + maximum); // 120

Finding the maximum among three values:

public class MaxOfThree {
    public static void main(String[] args) {
        int first = 158;
        int second = 342;
        int third = 96;
        
        int intermediate = (first > second) ? first : second;
        int maximum = (intermediate > third) ? intermediate : third;
        
        System.out.println("Maximum height: " + maximum + " cm");
    }
}

instanceof Operator

The instanceof operator checks object type at runtime:

Object obj = "Hello";
if (obj instanceof String) {
    String str = (String) obj;
    System.out.println("String length: " + str.length());
}

Operator Precedence

Priority Operators
1 ()
2 ++, --, !
3 *, /, %
4 +, -
5 <, <=, >, >=
6 ==, !=
7 &, ^, |
8 &&, ||
9 ?:
10 =, +=, -=, *=, /=, %=

When in doubt, use parentheses to clarify intent.


Type Conversion Summary

Conversion Type Direction Mechanism
Implicit (Widening) Narrow → Wide Automatic
Explicit (Narrowing) Wide → Narrow Manual cast required
// Widening (automatic)
byte narrow = 100;
long wide = narrow;

// Narrowing (manual)
double source = 45.67;
int target = (int) source;

Note: Boolean type is not convertible to or from any other type.

Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.