Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Core Java notes · Topic 2 of 20 · 6 min read

Java variables, data types and operators

Java notes with examples: variables, the 8 primitive data types, String, type casting, arithmetic, relational, logical and assignment operators, and precedence.

Variables

A variable is a named box that holds a value. In Java every variable has a type, fixed when you declare it:

int age = 16;
double price = 49.50;
char grade = 'A';
boolean passed = true;
String name = "Asha";

The pattern is type name = value;. You can declare first and assign later:

int marks;
marks = 87;

Naming rules

  • Letters, digits, _ and $ only; it cannot start with a digit.
  • Java keywords such as class, int or public cannot be names.
  • Names are case-sensitive: total and Total are different variables.
  • Convention: camelCase for variables (totalMarks), UPPER_CASE for constants.

Constants with final

final double GST_RATE = 0.18;
// GST_RATE = 0.12;   // error: cannot assign a value to final variable

var (Java 10+)

Inside a method, var lets the compiler work out the type from the value:

var count = 10;        // int
var city = "Ranchi";   // String

The type is still fixed; var only saves typing.

The 8 primitive data types

TypeSizeRange or useExample
byte1 byte-128 to 127byte b = 100;
short2 bytes-32,768 to 32,767short s = 3000;
int4 bytesabout ±2.1 billion (default whole number)int n = 25;
long8 bytesvery large whole numberslong pop = 1_400_000_000L;
float4 bytesdecimals, about 7 digitsfloat f = 3.5f;
double8 bytesdecimals, about 15 digits (default decimal)double d = 3.14159;
char2 bytesone Unicode characterchar c = 'J';
boolean-true or falseboolean ok = false;

Note the suffixes: L for long and f for float. Underscores in numbers such as 1_000_000 are only for readability.

String: a class, not a primitive

String holds text in double quotes. It starts with a capital S because it is a class.

String first = "Ravi";
String full = first + " Kumar";      // joining with +
System.out.println(full.length());   // 10

Single quotes are for one char: 'A'. Double quotes are for a String: "A".

Type casting

Widening (small type to big type) happens automatically:

int n = 50;
double d = n;          // 50.0

Narrowing (big to small) needs an explicit cast and may lose data:

double price = 99.99;
int rupees = (int) price;   // 99: the decimal part is cut off, not rounded

Operators

Arithmetic

OperatorMeaningExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23 (int division)
%remainder7 % 21

Integer division: when both sides are int, / drops the decimal part. Write 7 / 2.0 or (double) 7 / 2 to get 3.5.

Relational (comparison)

==, !=, >, <, >=, <= all give a boolean.

Logical

  • && (AND): true only when both sides are true.
  • || (OR): true when at least one side is true.
  • ! (NOT): flips true and false.

&& and || are short-circuit: if the left side already decides the answer, the right side is not checked.

Assignment and increment

int x = 10;
x += 5;    // x = x + 5  -> 15
x *= 2;    // 30
x++;       // 31
x--;       // 30

x++ (post-increment) uses the value, then adds 1. ++x (pre-increment) adds 1 first:

int a = 5;
int b = a++;   // b = 5, a = 6
int c = ++a;   // a = 7, c = 7

Ternary operator

int marks = 72;
String result = marks >= 40 ? "Pass" : "Fail";

Precedence

Highest to lowest (simplified): () then ++ -- ! then * / % then + - then comparisons then && then || then ? : then assignment. When unsure, add brackets.

Example: simple interest

public class Interest {
    public static void main(String[] args) {
        double principal = 20000;
        double rate = 7.5;
        int years = 3;
        double si = principal * rate * years / 100;
        System.out.println("Simple interest: " + si);
    }
}
Simple interest: 4500.0

Common mistakes

  • float f = 3.5; fails: 3.5 is a double. Write 3.5f.
  • Expecting 5 / 2 to be 2.5. With two ints it is 2.
  • Using = (assign) where you meant == (compare).
  • Comparing strings with ==. Use a.equals(b) (see the Strings topic).
  • Using a local variable before giving it a value: the compiler reports "might not have been initialized".

Key points

  • Every Java variable has a fixed type; final makes it a constant.
  • Eight primitives: byte, short, int, long, float, double, char, boolean.
  • String is a class; text goes in double quotes.
  • Widening casts are automatic; narrowing needs (type) and can lose data.
  • int / int is integer division; % gives the remainder.

Practice questions

1. What is printed: System.out.println(17 / 5 + " " + 17 % 5);

3 2. 17 divided by 5 is 3 with remainder 2.

2. Which line has an error and why? long a = 5; int b = a;

int b = a; fails: converting long to int is narrowing and needs a cast, int b = (int) a;.

3. What are the values of a and b after int a = 3; int b = a++ + ++a;?

a++ gives 3 (then a is 4), ++a makes a 5 and gives 5. So b = 3 + 5 = 8 and a = 5.

4. Write a program that converts 98.6 degrees Fahrenheit to Celsius.
public class Temp {
    public static void main(String[] args) {
        double f = 98.6;
        double c = (f - 32) * 5 / 9;
        System.out.println(c);   // 37.0 (approximately)
    }
}
5. Use the ternary operator to store "Even" or "Odd" for int n = 14.
String type = n % 2 == 0 ? "Even" : "Odd";