Free Ebook cover Java for Beginners: A Complete Introduction to Programming with Java

Java for Beginners: A Complete Introduction to Programming with Java

New course

10 pages

Variables and Data Types in Java

Capítulo 2

Estimated reading time: 5 minutes

+ Exercise

What a Variable Is (and Why You Need It)

A variable is a named storage location in memory that holds a value your program can use and change. When you want to remember information (like an age, a price, or a name), you store it in variables. In Java, every variable has a type, which tells Java what kind of value it can hold and what operations are allowed.

Declaring and Assigning Variables

Declaration: creating a variable

To declare a variable, you write its type followed by its name. Declaration reserves space and sets the rules for what can be stored.

int age;        // declares an int variable named age (no value yet)

Assignment: giving it a value

To assign a value, use the equals sign (=). This is not “equals in math”; it means “store the value on the right into the variable on the left”.

age = 20;       // assigns 20 to age

Declaration + assignment in one line

int age = 20;

Updating a variable

Variables can change during the program. Updating means assigning a new value to the same variable.

age = 21;       // age is now 21

Naming Rules and Readable Naming Conventions

Java naming rules (what is allowed)

  • Names can contain letters, digits, underscore (_), and dollar sign ($).
  • Names cannot start with a digit.
  • Names cannot be Java keywords (like int, class, public).
  • Names are case-sensitive: age and Age are different.

Readable naming conventions (what you should do)

  • Use camelCase for variables: firstName, isMember, totalPrice.
  • Choose descriptive names: prefer price over p.
  • Booleans often read like a yes/no question: isMember, hasDiscount, canVote.
  • Avoid confusing single-letter names except for short loops (covered elsewhere).

Core Data Types You’ll Use Often

Primitive types

Primitive types store simple values directly.

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

  • int: whole numbers, e.g., -3, 0, 42.
  • double: decimal (floating-point) numbers, e.g., 3.14, 19.99.
  • boolean: true or false.
  • char: a single character in single quotes, e.g., 'A', '7', '?'.

String (a commonly used reference type)

String stores text like names and sentences. Unlike primitives, String is a reference type (an object). You write string values in double quotes.

String name = "Mina";

Even though it’s not a primitive, you will use String constantly in beginner programs.

Exercise: Store User-Like Data in Variables

In this exercise, you will create variables that represent typical user information: age, price, membership status, an initial, and a name. Then you will print them and update them.

Step 1: Declare and assign the variables

int age = 28;                 // whole number age in years
double price = 19.99;         // decimal price
boolean isMember = true;      // membership status
char initial = 'M';           // first letter
String name = "Mina";        // full name

Step 2: Print the values

Use System.out.println to display values. You can combine text and variables using + (string concatenation).

System.out.println("Name: " + name);
System.out.println("Initial: " + initial);
System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Is member? " + isMember);

Step 3: Update variables (simulate changes)

Now pretend time passes or the user changes something: the user has a birthday, the price changes, and membership is canceled.

age = age + 1;                // or: age++
price = 17.49;                // new price
isMember = false;             // membership changed

Print again to confirm the updates:

System.out.println("--- Updated values ---");
System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Is member? " + isMember);

Step 4: Try it yourself (small tasks)

  • Change name to another value and print it.
  • Set initial to match the new name.
  • Increase price by 2.00 using the current value (not by typing a new number).
price = price + 2.00;
System.out.println("New price: " + price);

Focused Comparison: int vs double

What they represent

  • int is for whole numbers only. It cannot store decimals.
  • double is for numbers with decimals (and can also store whole numbers like 5.0).

Common beginner mistake: losing decimals

If you divide two int values, Java performs integer division and drops the decimal part.

int a = 5;
int b = 2;
int resultInt = a / b;        // 2 (not 2.5)
System.out.println(resultInt);

Using double keeps the decimal part:

double resultDouble = 5.0 / 2; // 2.5
System.out.println(resultDouble);

Even if only one side is a double, Java will do decimal division:

double resultDouble2 = a / 2.0; // 2.5
System.out.println(resultDouble2);

Which should you choose?

  • Use int for counts: age in years, number of items, number of students.
  • Use double for measurements and prices where decimals matter.

Simple Type Conversion (Beginner Cases)

Type conversion happens when you move a value from one type to another. Some conversions are automatic (safe), and some require an explicit cast (because information might be lost).

Case 1: int to double (automatic)

Java can safely convert an int to a double because a double can represent whole numbers.

int items = 3;
double itemsAsDouble = items;   // 3.0
System.out.println(itemsAsDouble);

Case 2: double to int (requires a cast)

Converting a double to an int can lose the decimal part. Java requires you to explicitly cast to show you understand that.

double rating = 4.8;
int ratingInt = (int) rating;   // 4 (decimal part is removed)
System.out.println(ratingInt);

This does not round; it truncates (cuts off) the decimal part.

Case 3: Avoiding integer division by converting

If you have two int values but want a decimal result, convert at least one to double.

int total = 7;
int people = 2;
double average = (double) total / people; // 3.5
System.out.println(average);

Case 4: char and String basics

A char is one character; a String is text of any length. You can combine them in printing:

char initial = 'M';
String name = "Mina";
System.out.println("Initial: " + initial);
System.out.println("Name: " + name);

Remember: 'M' is a char, but "M" is a String.

Now answer the exercise about the content:

You want the result of dividing 5 by 2 to be 2.5 instead of 2. Which change ensures Java performs decimal division?

You are right! Congratulations, now go to the next page

You missed! Try again.

Dividing two int values uses integer division and drops the decimal part. If at least one operand is a double, Java performs decimal division and keeps the fractional result.

Next chapter

Operators and Expressions for Java Calculations

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.