Skip to content
On this page

Variables and Data Types

Declaring Variables:

In Java, you declare variables with a specific data type before using them.

java
// Declaring variables
int age = 30;
double height = 5.9;
char gender = 'M';
boolean isStudent = true;

Primitive Data Types: int, double, char, boolean

Java supports several primitive data types:

  • int: Integer type, e.g., 5, -10.
  • double: Floating-point type, e.g., 3.14, -0.5.
  • char: Character type, e.g., 'A', '$'.
  • boolean: Boolean type, e.g., true, false.
java
// Primitive data types
int num1 = 10;
double num2 = 3.14;
char grade = 'A';
boolean isPassed = true;

Non-Primitive Data Types: String

Java provides a String class for working with textual data.

java
// Non-primitive data types (String)
String name = "John Doe";
String message = "Hello, World!";

Type Conversion:

Java allows type conversion between compatible data types using casting.

java
// Type conversion
String numStr = "25";
int numInt = Integer.parseInt(numStr);         // Convert String to int
double numDouble = Double.parseDouble(numStr); // Convert String to double

String result = String.valueOf(numInt);        // Convert int to String