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:
| Parameter | Type | Description |
|---|---|---|
| int, long, short, byte | Integer Types | Signed two's complement integers. |
| double, float | Floating Point | IEEE 754 decimal numbers. |
| String | Object Class | Immutable sequence of characters. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Java Operators: Arithmetic, Logical, and Bitwise
Explore arithmetic (+, -, *, /, %), relational, and logical (&&, ||, !) operators in Java.
Java Input and Output: Scanner, System.out, and printf
Read inputs using java.util.Scanner and format output streams with System.out.printf.
Java Type Casting: Widening and Narrowing Conversions
Understand implicit widening conversions and explicit narrowing casts in Java.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.