Switch Statements
Mastering the switch-case logic in Java with examples.
Description
In Java, data types define the type of data a variable can hold. Java is a statically-typed language, meaning each variable must be declared with a data type before it is used. Java has two main categories of data types:
- Primitive Types: These include
int
,float
,double
,boolean
,char
,byte
,short
, andlong
. - Reference/Object Types: These include classes, interfaces, arrays, and strings.
Variables are containers used to store data. Java variables are declared using a data type followed by a variable name and optionally an initial value.
Example: int age = 25;
Video Resources
Java Data Types Tutorial
Learn about primitive and reference data types in Java.
Java Variables Explained
Understand how to declare, initialize, and use variables.
Primitive Types and Memory
Dive deeper into how Java handles data types and memory.
Examples (code)
Primitive Data Types Example
public class DataTypeExample {
public static void main(String[] args) {
int age = 30;
double salary = 45890.50;
char grade = 'A';
boolean isJavaFun = true;
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Grade: " + grade);
System.out.println("Is Java fun? " + isJavaFun);
}
}
Reference Data Type Example
public class ReferenceExample {
public static void main(String[] args) {
String name = "Alice";
int[] scores = {90, 85, 78};
System.out.println("Name: " + name);
System.out.print("Scores: ");
for(int score : scores) {
System.out.print(score + " ");
}
}
}
Real-World Applications
Financial Systems
Variables store account balances, interest rates, and transaction data in banking applications.
Healthcare Apps
Patient vitals and health metrics are stored using appropriate data types like float, boolean, and int.
Game Development
Variables track scores, health levels, and game states using a mix of primitive and reference types.
Interview Questions
Q1: What are the primitive data types in Java?
The primitive types in Java include: byte
, short
, int
, long
, float
, double
, char
, and boolean
.
Q2: How do reference types differ from primitive types?
Primitive types store actual values, while reference types store memory addresses pointing to objects like arrays, classes, or strings.
Q3: Can you assign a float value to a double variable?
Yes, Java allows implicit conversion from float to double as it is a widening conversion (lower to higher precision).