Java:Java Variables and Primitive Data Types with Examples
Java•Variables

Java Variables and Primitive Data Types with Examples

Java is strongly and statically typed. Every variable must have a defined type, with local type inference available via var.

Syntax

int count = 10; String title = "Java"; var inferred = 3.14;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
int, long, short, byteInteger TypesSigned two's complement integers.
double, floatFloating PointIEEE 754 decimal numbers.
StringObject ClassImmutable sequence of characters.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

public class Main {
    public static void main(String[] args) {
        String serviceName = "Compilra Runner";
        int memoryLimitMB = 2048;
        double cpuCores = 4.5;
        boolean isProduction = true;

        System.out.println("Service:  " + serviceName);
        System.out.println("Memory:   " + memoryLimitMB + " MB");
        System.out.println("CPUs:     " + cpuCores + " cores");
        System.out.println("Status:   " + (isProduction ? "LIVE" : "STAGING"));
    }
}
Expected Output:
Service:  Compilra Runner
Memory:   2048 MB
CPUs:     4.5 cores
Status:   LIVE

How It Works: Step-by-Step

  • Lines 3-6: Declares strongly-typed primitive variables and String object.
  • Lines 8-11: Outputs values to standard out using System.out.println.

Key Concepts

  • Java requires all code to reside inside class declarations.
  • Primitives (int, double, boolean) store values directly; Objects (String) store references.
  • System.out.println prints a message followed by a newline.

Common Mistake: Comparing Java Strings with == instead of .equals()

In Java, == compares memory references, not string contents. Always use .equals().

❌ Incorrect
String a = new String("test");
if (a == "test") { /* Evaluates to false! */ }
✅ Correct
String a = new String("test");
if (a.equals("test")) { /* Compares content correctly */ }

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler