Progress3 of 14 topics

21% complete

Java Variables and Data Types

In this tutorial, you'll learn about variables and data types in Java - the building blocks of any Java program. We'll cover how to declare variables, the different types of data Java can handle, and best practices for using them effectively.

Understanding Variables in Java

A variable is a container that holds a value during the execution of a Java program. Think of variables as labeled boxes where you can store different types of data.

Variable Declaration and Initialization

In Java, you must declare a variable before using it, specifying its data type and name:

java
1// Variable declaration
2int age;
3
4// Variable initialization
5age = 25;
6
7// Declaration and initialization in one line
8int score = 95;

Variable Naming Rules

Java Variable Naming Rules

  • Variable names are case-sensitive (age, Age, and AGE are different variables)
  • Names must start with a letter, dollar sign ($), or underscore (_)
  • After the first character, names can also include numbers
  • Cannot use Java reserved keywords as variable names
  • Cannot include spaces or special characters like %, #, @, etc.

Java Naming Conventions

While not required by the compiler, following these conventions makes your code more readable:

TypeConventionExamples
VariablescamelCasefirstName, totalScore, isVisible
ConstantsUPPER_SNAKE_CASEMAX_VALUE, PI, DATABASE_URL
ClassesPascalCaseStudent, BankAccount, MainActivity
MethodscamelCasecalculateTotal(), getUserName()
Packagesall lowercasecom.example.myapp, java.util

Java Data Types

Java is a statically-typed language, which means you must declare the data type of a variable when you create it. Java has two categories of data types:

Primitive Data Types

Basic data types built into the language that store simple values. Java has 8 primitive data types.

Reference Data Types

Complex data types that refer to objects. These include classes, interfaces, arrays, and enumeration types.

Primitive Data Types

Data TypeSizeRangeExample
byte8 bits-128 to 127byte b = 100;
short16 bits-32,768 to 32,767short s = 1000;
int32 bits-231 to 231-1int i = 100000;
long64 bits-263 to 263-1long l = 100000L;
float32 bits±3.4e−038 to ±3.4e+038float f = 3.14f;
double64 bits±1.7e−308 to ±1.7e+308double d = 3.14159;
char16 bits0 to 65,535 (Unicode characters)char c = 'A';
boolean1 bittrue or falseboolean isActive = true;

Integer Types (byte, short, int, long)

These types store whole numbers (without decimal points). The difference between them is their size, which affects the range of values they can store:

java
1// Integer types examples
2byte smallNumber = 127; // Max value for byte
3short mediumNumber = 32000; // Fits within short range
4int regularNumber = 2000000; // Regular integer value
5long bigNumber = 9223372036854775807L; // Note the 'L' suffix for long literals
Note:

For long literals, you must append the letter 'L' (uppercase 'L' is recommended to avoid confusion with the digit '1').

Floating-Point Types (float, double)

These types store numbers with decimal points:

java
1// Floating-point types examples
2float price = 19.99f; // Note the 'f' suffix for float literals
3double preciseValue = 19.99; // double is the default for decimal literals
4double scientificNotation = 1.23e4; // 12300.0 (scientific notation)
Note:

For float literals, you must append the letter 'f' or 'F'. Without it, Java treats decimal literals as double by default.

Character Type (char)

The char type stores a single Unicode character:

java
1// Character type examples
2char letter = 'A'; // Single quotes for char literals
3char digit = '9'; // A digit character, not the number 9
4char unicode = '©'; // Unicode representation (© symbol)
5char escape = '\'; // Escape sequence for backslash

Boolean Type

The boolean type can only store true or false:

java
1// Boolean type examples
2boolean isJavaFun = true;
3boolean isBoring = false;
4
5// Often used in conditional statements
6if (isJavaFun) {
7 System.out.println("Enjoying the learning process!");
8}

Reference Data Types

Reference types don't store the actual data but store a reference (memory address) to where the data is located. The main reference types are:

String

Although not a primitive type, String is so commonly used that it feels like a built-in type. It represents a sequence of characters:

java
1// String examples
2String name = "John Doe"; // Double quotes for String literals
3String empty = ""; // Empty string
4String multiline = """
5 This is a
6 multi-line
7 text block
8 """; // Text block (Java 15+)

Arrays

Arrays store multiple values of the same type:

java
1// Array examples
2int[] numbers = {1, 2, 3, 4, 5}; // Array initialization with values
3String[] names = new String[3]; // Array initialization with size
4names[0] = "Alice"; // Assigning values to array elements
5names[1] = "Bob";
6names[2] = "Charlie";
7
8// Accessing array elements
9System.out.println(numbers[0]); // Outputs: 1
10System.out.println(names[1]); // Outputs: Bob

Classes and Objects

User-defined reference types are created using classes:

java
1// Class definition
2class Student {
3 String name;
4 int age;
5
6 void study() {
7 System.out.println(name + " is studying.");
8 }
9}
10
11// Creating objects from a class
12Student student1 = new Student();
13student1.name = "Alice";
14student1.age = 20;
15student1.study(); // Outputs: Alice is studying.

Constants in Java

Constants are variables whose values cannot be changed once assigned. In Java, constants are declared using the final keyword:

java
1// Constants examples
2final double PI = 3.14159;
3final int MAX_USERS = 100;
4
5// This will cause a compilation error:
6// PI = 3.14; // Cannot assign a value to final variable 'PI'

By convention, constants are named in UPPERCASE_WITH_UNDERSCORES to distinguish them from regular variables.

Type Casting in Java

Type casting is the process of converting a value from one data type to another. There are two types of casting in Java:

Implicit Casting (Widening)

Happens automatically when converting from a smaller type to a larger type:

java
1// Implicit casting examples
2byte smallByte = 10;
3int largerInt = smallByte; // byte to int (automatic)
4long evenLarger = largerInt; // int to long (automatic)
5float decimalFloat = evenLarger; // long to float (automatic)
6double largestDecimal = decimalFloat; // float to double (automatic)
Widening Conversion Path:

byte → short → int → long → float → double

Explicit Casting (Narrowing)

Required when converting from a larger type to a smaller type. You must use cast operators:

java
1// Explicit casting examples
2double largeDouble = 123.456;
3float smallerFloat = (float) largeDouble; // double to float (manual)
4long largeLong = (long) largeDouble; // double to long (manual)
5int smallerInt = (int) largeLong; // long to int (manual)
6byte smallestByte = (byte) smallerInt; // int to byte (manual)
7
8// Be careful with narrowing conversions - you may lose data
9int x = 128;
10byte y = (byte) x; // Results in -128 (overflow, as byte max is 127)

Warning:

Explicit casting can lead to data loss or unexpected results if the value being cast is outside the range of the target type. Always be cautious when performing narrowing conversions.

Variable Scope in Java

The scope of a variable determines where in your code the variable can be accessed:

java
1public class ScopeExample {
2 // Class level variable (instance variable)
3 private int instanceVariable = 10;
4
5 // Static variable (class variable)
6 private static int classVariable = 20;
7
8 public void methodOne() {
9 // Method level variable (local variable)
10 int localVariable = 30;
11
12 // Block scope
13 if (true) {
14 // Block level variable
15 int blockVariable = 40;
16 System.out.println(blockVariable); // Accessible
17 System.out.println(localVariable); // Accessible
18 System.out.println(instanceVariable); // Accessible
19 }
20
21 System.out.println(localVariable); // Accessible
22 // System.out.println(blockVariable); // ERROR: Not accessible outside block
23 }
24
25 public void methodTwo() {
26 System.out.println(instanceVariable); // Accessible
27 // System.out.println(localVariable); // ERROR: Not accessible from other methods
28 }
29}

Practical Examples

Let's look at some practical examples of using variables and data types in Java:

Example 1: Calculator

java
1public class Calculator {
2 public static void main(String[] args) {
3 // Declare and initialize variables
4 int num1 = 10;
5 int num2 = 5;
6
7 // Perform calculations
8 int sum = num1 + num2;
9 int difference = num1 - num2;
10 int product = num1 * num2;
11 int quotient = num1 / num2;
12 int remainder = num1 % num2;
13
14 // Display results
15 System.out.println("Number 1: " + num1);
16 System.out.println("Number 2: " + num2);
17 System.out.println("Sum: " + sum);
18 System.out.println("Difference: " + difference);
19 System.out.println("Product: " + product);
20 System.out.println("Quotient: " + quotient);
21 System.out.println("Remainder: " + remainder);
22
23 // Using floating-point numbers
24 double decimal1 = 10.5;
25 double decimal2 = 2.5;
26 double decimalQuotient = decimal1 / decimal2;
27
28 System.out.println("Decimal Quotient: " + decimalQuotient);
29 }
30}

Example 2: Student Record

java
1public class StudentRecord {
2 public static void main(String[] args) {
3 // Student information
4 String name = "Alice Johnson";
5 int age = 20;
6 char grade = 'A';
7 double gpa = 3.85;
8 boolean isFullTime = true;
9
10 // Array of course scores
11 int[] scores = {95, 87, 92, 78, 90};
12
13 // Display student information
14 System.out.println("Student Name: " + name);
15 System.out.println("Age: " + age);
16 System.out.println("Grade: " + grade);
17 System.out.println("GPA: " + gpa);
18 System.out.println("Full-time: " + isFullTime);
19
20 // Calculate and display average score
21 int sum = 0;
22 for (int score : scores) {
23 sum += score;
24 }
25 double average = (double) sum / scores.length;
26
27 System.out.println("Average Score: " + average);
28 }
29}

Best Practices

Choose Appropriate Data Types

Use the most appropriate data type for your needs. For example, use int for most whole numbers,double for decimal values, and boolean for true/false conditions.

Use Meaningful Variable Names

Choose descriptive names that indicate the purpose of the variable. For example, use numberOfStudentsinstead of n or x.

Declare Variables Close to Use

Declare variables as close as possible to where they are first used to improve code readability and reduce the scope of variables.

Use Constants for Fixed Values

Use final variables for values that don't change, like PI or maximum allowed values, to make your code more maintainable.

Practice Exercises

  1. Create a program that calculates the area and perimeter of a rectangle using appropriate variable types.
  2. Write a program that converts temperature from Fahrenheit to Celsius using the formula: C = (F - 32) * 5/9.
  3. Create a program that calculates the average of 5 test scores stored in an array.
  4. Write a program that demonstrates type casting between different numeric data types.
  5. Create a simple banking application that tracks account balance and performs deposits and withdrawals.

Summary

In this tutorial, you've learned:

  • How to declare and initialize variables in Java
  • The rules and conventions for naming variables
  • Java's primitive data types: byte, short, int, long, float, double, char, and boolean
  • Reference data types like String, arrays, and objects
  • How to use constants with the final keyword
  • Type casting between different data types
  • Variable scope and best practices for using variables effectively

Understanding variables and data types is fundamental to programming in Java. These concepts form the foundation for storing and manipulating data in your programs. In the next tutorial, we'll explore control flow in Java, which allows you to make decisions and repeat actions in your code.

Related Tutorials

Learn the basics of Java programming language.

Learn more

Learn about decision making and loops in Java.

Learn more

Understand the fundamentals of OOP in Java.

Learn more