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,intorpubliccannot be names. - Names are case-sensitive:
totalandTotalare 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
| Type | Size | Range or use | Example |
|---|---|---|---|
byte | 1 byte | -128 to 127 | byte b = 100; |
short | 2 bytes | -32,768 to 32,767 | short s = 3000; |
int | 4 bytes | about ±2.1 billion (default whole number) | int n = 25; |
long | 8 bytes | very large whole numbers | long pop = 1_400_000_000L; |
float | 4 bytes | decimals, about 7 digits | float f = 3.5f; |
double | 8 bytes | decimals, about 15 digits (default decimal) | double d = 3.14159; |
char | 2 bytes | one Unicode character | char c = 'J'; |
boolean | - | true or false | boolean 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
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3 (int division) |
% | remainder | 7 % 2 | 1 |
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.5is adouble. Write3.5f.- Expecting
5 / 2to be2.5. With twoints it is2. - Using
=(assign) where you meant==(compare). - Comparing strings with
==. Usea.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;
finalmakes it a constant. - Eight primitives:
byte,short,int,long,float,double,char,boolean. Stringis a class; text goes in double quotes.- Widening casts are automatic; narrowing needs
(type)and can lose data. int / intis 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";