Chapter 2: Variables, Data Types, and Operators

Now that you've written your first Java program, it's time to learn how Java stores and manipulates information. Unlike some scripting languages, Java is statically typed, which means every variable must have its type declared before it can be used. This might feel stricter at first, but it catches a huge number of bugs before your program ever runs.

1. Primitive Data Types

Java has eight built-in "primitive" types. The four you will use constantly as a beginner are:

int age = 21;
double price = 49.99;
char grade = 'A';
boolean isEnrolled = true;

2. Declaring Variables

Every variable declaration in Java follows the pattern type name = value;. Once a variable is declared with a type, it can never hold a value of a different type — trying to assign a String to an int variable will cause a compile-time error, which is exactly the kind of safety net static typing gives you.

String studentName = "Priya";
int score = 95;
score = 98; // allowed, still an int
// score = "A+"; // this line would fail to compile

3. Working with Strings

Text in Java is handled by the String class rather than a primitive type. Strings are extremely common, and Java gives you a rich set of built-in methods for working with them.

String first = "Code";
String last = "Master";
String full = first + last; // "CodeMaster"
System.out.println(full.length()); // 10
System.out.println(full.toUpperCase()); // "CODEMASTER"

4. Arithmetic and Comparison Operators

Java supports the standard arithmetic operators +, -, *, /, and % (modulus, which returns the remainder of a division). It also provides comparison operators like ==, !=, >, and <, which evaluate to a boolean and are the building blocks of decision-making logic covered in the next chapter.

int a = 10;
int b = 3;
System.out.println(a % b); // 1 (remainder)
System.out.println(a > b); // true

Common Beginner Mistakes

Try It Yourself

  1. Declare an int variable for your age and a String variable for your name.
  2. Print a sentence that combines both using string concatenation.
  3. Declare two double variables and print the result of dividing them.

Primitive vs Reference Types

Java splits data into primitive types (like int, double, and boolean), which store actual values, and reference types (like String and arrays), which store a reference to an object in memory. This distinction affects how variables behave when passed to methods or compared with ==.

int a = 5;
String name = "Java";  // reference type
System.out.println(name.length()); // 4