Java Programming
Lecture 03: Data Types & Variables
Course: 4343203 - Java Programming
GTU Semester 4 | Unit 1
Learning Objectives:
- Understand primitive and reference data types
- Learn variable declaration and initialization
- Master type conversion and casting
- Explore variable scope and lifetime
- Apply constants and final variables
Understanding Data Types
Data Types specify the type of data that can be stored in variables and determine the operations that can be performed on them.
Primitive Data Types
- Built into Java language
- Stored in stack memory
- 8 primitive types in Java
- Hold actual values
Reference Data Types
- Created using defined constructors
- Stored in heap memory
- Classes, interfaces, arrays
- Hold memory addresses
Primitive Data Types
| Data Type | Size (bits) | Size (bytes) | Range | Default Value | Example |
|---|---|---|---|---|---|
| byte | 8 | 1 | -128 to 127 | 0 | byte b = 100; |
| short | 16 | 2 | -32,768 to 32,767 | 0 | short s = 1000; |
| int | 32 | 4 | -2³¹ to 2³¹-1 | 0 | int i = 100000; |
| long | 64 | 8 | -2⁶³ to 2⁶³-1 | 0L | long l = 100000L; |
| float | 32 | 4 | ±3.40282347E+38F | 0.0f | float f = 234.5f; |
| double | 64 | 8 | ±1.79769313486231570E+308 | 0.0d | double d = 123.4; |
| boolean | 1 | 1 | true or false | false | boolean flag = true; |
| char | 16 | 2 | 0 to 65,535 (Unicode) | '\u0000' | char c = 'A'; |
Variables Declaration & Initialization
Variable Declaration Syntax:
// Syntax: datatype variablename;
int age;
double salary;
boolean isStudent;
char grade;
// Multiple variables of same type
int x, y, z;
double length, width, height;Variable Initialization:
// Declaration and initialization
int age = 25;
double salary = 50000.50;
boolean isStudent = true;
char grade = 'A';
// Initialize after declaration
int marks;
marks = 95;Variable Naming Rules:
- Must start with letter, underscore, or $
- Cannot start with digit
- Case-sensitive (age ≠ Age)
- Cannot use reserved keywords
- No spaces allowed
Valid Variable Names:
- age, _name, $salary
- firstName, lastName
- student1, student2
- MAX_VALUE
Invalid Variable Names:
- 1student (starts with digit)
- first-name (contains hyphen)
- class (reserved keyword)
- first name (contains space)
Constants and Final Variables
Final Variables (Constants):
// final keyword makes variable constant
final int MAX_STUDENTS = 100;
final double PI = 3.14159;
final String COLLEGE_NAME = "GTU";
// Must be initialized when declared
final int MIN_AGE = 18;
// Cannot change value later
// MAX_STUDENTS = 200; // ❌ Compilation errorConvention: Use UPPER_CASE with underscores for constants
Static Final Variables:
public class MathConstants {
public static final double PI = 3.14159;
public static final int MAX_VALUE = 2147483647;
public static final String VERSION = "1.0";
public static void main(String[] args) {
System.out.println("PI = " + PI);
System.out.println("MAX = " + MAX_VALUE);
}
}Benefits of Constants:
- Prevents accidental changes
- Makes code more readable
- Central place for values
- Easier maintenance
Type Conversion & Casting
Implicit Type Conversion (Widening):
// Automatic conversion (smaller to larger)
byte b = 42;
short s = b; // byte to short
int i = s; // short to int
long l = i; // int to long
float f = l; // long to float
double d = f; // float to double
// Widening conversion hierarchy:
// byte → short → int → long → float → doubleAutomatic Conversions:
- No data loss occurs
- Smaller type fits in larger
- No explicit casting needed
- Compiler handles automatically
Explicit Type Casting (Narrowing):
// Manual conversion (larger to smaller)
double d = 9.78;
float f = (float) d; // double to float
long l = (long) f; // float to long
int i = (int) l; // long to int
short s = (short) i; // int to short
byte b = (byte) s; // short to byte
// Example with potential data loss
int largeNum = 130;
byte smallNum = (byte) largeNum; // Data loss!
System.out.println(smallNum); // Output: -126⚠️ Narrowing Risks:
- Possible data loss
- Truncation of decimal part
- Overflow/underflow issues
- Requires explicit casting
Variable Scope & Lifetime
Types of Variables:
public class ScopeExample {
// 1. Instance variables (class level)
private int instanceVar = 10;
static int staticVar = 20; // Class variable
public void method1() {
// 2. Local variables (method level)
int localVar = 30;
// 3. Block variables
{
int blockVar = 40;
System.out.println(blockVar); // ✅ Valid
}
// System.out.println(blockVar); // ❌ Error
for (int i = 0; i < 5; i++) { // Loop variable
System.out.println(i);
}
// System.out.println(i); // ❌ Error
}
}Variable Scope Rules:
Instance Variables:
- Declared inside class, outside methods
- Accessible throughout class
- Default values assigned automatically
- Lifetime: Until object exists
Local Variables:
- Declared inside methods or blocks
- Accessible only within method/block
- Must be initialized before use
- Lifetime: Until method execution ends
Static Variables:
- Class-level variables
- Shared among all instances
- Memory allocated once
- Lifetime: Until program ends
Introduction to Arrays
One-Dimensional Arrays:
// Array declaration and creation
int[] numbers = new int[5];
double[] prices = new double[10];
// Declaration with initialization
int[] marks = {85, 90, 78, 92, 88};
String[] names = {"John", "Alice", "Bob"};
// Accessing array elements
numbers[0] = 10; // First element
numbers[1] = 20; // Second element
int first = numbers[0];
// Array length
int size = numbers.length; // 5Array Properties:
- Fixed size: Cannot change after creation
- Same type: All elements must be same type
- Zero-indexed: First element at index 0
- Reference type: Array name holds address
- Default values: Automatically initialized
Array Default Values:
- int[], byte[], short[], long[]: 0
- float[], double[]: 0.0
- boolean[]: false
- char[]: '\u0000'
- Object arrays: null
Previous Year Exam Questions
Q1. (GTU Summer 2022) Explain different data types available in Java with their size, range and default values.
Solution:
Java has 8 primitive data types:
Integer Types:
- byte: 8-bit, range -128 to 127, default 0
- short: 16-bit, range -32,768 to 32,767, default 0
- int: 32-bit, range -2³¹ to 2³¹-1, default 0
- long: 64-bit, range -2⁶³ to 2⁶³-1, default 0L
Floating Point Types:
- float: 32-bit IEEE 754, range ±3.40282347E+38F, default 0.0f
- double: 64-bit IEEE 754, range ±1.7976931348623157E+308, default 0.0d
Other Types:
- boolean: 1-bit, values true/false, default false
- char: 16-bit Unicode, range 0 to 65,535, default '\u0000'
Q2. (GTU Winter 2021) What is type casting in Java? Explain implicit and explicit type casting with examples.
Solution:
Type Casting: Converting one data type to another data type.
1. Implicit Type Casting (Widening):
- Automatic conversion from smaller to larger data type
- No data loss occurs
- No explicit casting required
// Examples of implicit casting
byte b = 10;
int i = b; // byte to int (automatic)
long l = i; // int to long (automatic)
float f = l; // long to float (automatic)
double d = f; // float to double (automatic)
// Widening hierarchy: byte → short → int → long → float → double2. Explicit Type Casting (Narrowing):
- Manual conversion from larger to smaller data type
- Possible data loss
- Requires explicit cast operator ()
// Examples of explicit casting
double d = 123.45;
float f = (float) d; // double to float
int i = (int) f; // float to int (decimal part lost)
short s = (short) i; // int to short
byte b = (byte) s; // short to byteQ3. (GTU Summer 2020) Write a Java program to demonstrate the use of different primitive data types and perform type conversion.
Solution:
public class DataTypesDemo {
public static void main(String[] args) {
// Demonstrating different primitive data types
byte byteVal = 127;
short shortVal = 32000;
int intVal = 2000000;
long longVal = 9223372036854775807L;
float floatVal = 3.14f;
double doubleVal = 123.456789;
boolean boolVal = true;
char charVal = 'A';
// Display all values
System.out.println("byte value: " + byteVal);
System.out.println("short value: " + shortVal);
System.out.println("int value: " + intVal);
System.out.println("long value: " + longVal);
System.out.println("float value: " + floatVal);
System.out.println("double value: " + doubleVal);
System.out.println("boolean value: " + boolVal);
System.out.println("char value: " + charVal);
// Implicit type conversion (widening)
System.out.println("\n--- Implicit Type Conversion ---");
int i = byteVal; // byte to int
long l = intVal; // int to long
float f = longVal; // long to float
double d = floatVal; // float to double
System.out.println("byte to int: " + i);
System.out.println("int to long: " + l);
System.out.println("long to float: " + f);
System.out.println("float to double: " + d);
// Explicit type conversion (narrowing)
System.out.println("\n--- Explicit Type Conversion ---");
double largeDouble = 123.789;
float narrowFloat = (float) largeDouble;
int narrowInt = (int) narrowFloat;
short narrowShort = (short) narrowInt;
byte narrowByte = (byte) narrowShort;
System.out.println("Original double: " + largeDouble);
System.out.println("double to float: " + narrowFloat);
System.out.println("float to int: " + narrowInt);
System.out.println("int to short: " + narrowShort);
System.out.println("short to byte: " + narrowByte);
// Character to ASCII conversion
System.out.println("\n--- Character Conversion ---");
char ch = 'Z';
int ascii = ch; // char to int (implicit)
char fromAscii = (char) (ascii + 1); // int to char (explicit)
System.out.println("Character: " + ch);
System.out.println("ASCII value: " + ascii);
System.out.println("Next character: " + fromAscii);
}
}Practical Programming Examples
Student Grade Calculator:
public class GradeCalculator {
public static void main(String[] args) {
// Student information
String studentName = "John Doe";
int rollNumber = 101;
// Subject marks
int mathMarks = 85;
int physicsMarks = 90;
int chemistryMarks = 78;
int englishMarks = 92;
int computerMarks = 88;
// Calculate total and percentage
int totalMarks = mathMarks + physicsMarks +
chemistryMarks + englishMarks +
computerMarks;
double percentage = (double) totalMarks / 5;
// Determine grade
char grade;
if (percentage >= 90) grade = 'A';
else if (percentage >= 80) grade = 'B';
else if (percentage >= 70) grade = 'C';
else if (percentage >= 60) grade = 'D';
else grade = 'F';
// Display results
System.out.println("Student: " + studentName);
System.out.println("Roll No: " + rollNumber);
System.out.println("Total Marks: " + totalMarks);
System.out.println("Percentage: " + percentage + "%");
System.out.println("Grade: " + grade);
}
}Temperature Converter:
public class TemperatureConverter {
// Constants
public static final double CELSIUS_TO_FAHRENHEIT_RATIO = 9.0/5.0;
public static final int FAHRENHEIT_OFFSET = 32;
public static final double CELSIUS_TO_KELVIN_OFFSET = 273.15;
public static void main(String[] args) {
// Input temperature in Celsius
double celsius = 25.5;
// Convert to Fahrenheit
double fahrenheit = (celsius * CELSIUS_TO_FAHRENHEIT_RATIO) + FAHRENHEIT_OFFSET;
// Convert to Kelvin
double kelvin = celsius + CELSIUS_TO_KELVIN_OFFSET;
// Display conversions
System.out.println("Temperature Conversion:");
System.out.println("Celsius: " + celsius + "°C");
System.out.println("Fahrenheit: " + fahrenheit + "°F");
System.out.println("Kelvin: " + kelvin + "K");
// Demonstrate type casting
int celsiusInt = (int) celsius; // Explicit casting
System.out.println("\nCelsius as integer: " + celsiusInt + "°C");
// Character operations
char tempSymbol = '°';
int symbolCode = tempSymbol; // Implicit casting
System.out.println("Degree symbol ASCII: " + symbolCode);
}
}Hands-on Lab Exercises
Exercise 1: Data Type Explorer
- Create variables of each primitive data type
- Initialize them with maximum and minimum values
- Print their values and observe the output
- Try to assign values beyond their range and observe compiler behavior
// Template for Exercise 1
public class DataTypeExplorer {
public static void main(String[] args) {
// TODO: Create variables of all 8 primitive types
// TODO: Test boundary values
// TODO: Observe overflow/underflow behavior
}
}Exercise 2: Type Conversion Lab
- Create a program that demonstrates all possible type conversions
- Show both implicit and explicit conversions
- Observe data loss in narrowing conversions
- Convert characters to ASCII and vice versa
Exercise 3: Calculator Application
- Create a simple calculator that works with different data types
- Perform arithmetic operations on byte, int, float, double
- Handle type promotions in expressions
- Display results with appropriate precision
Assignment & Practice Problems
Programming Assignments:
- Employee Payroll System:
- Use appropriate data types for employee details
- Calculate salary with type conversions
- Handle tax calculations with precision
- Scientific Calculator:
- Implement basic arithmetic operations
- Use constants for mathematical values
- Handle different numeric types
- Data Type Converter:
- Convert between different number systems
- Handle character-number conversions
- Demonstrate safe casting techniques
Theory Questions:
- Compare primitive and reference data types
- Explain why char is 16-bit in Java
- Discuss memory allocation for different types
- Analyze type promotion rules in expressions
- Evaluate the need for different integer types
Preparation for Next Lecture:
- Review operator categories and precedence
- Practice arithmetic expressions with mixed types
- Study conditional and logical operators
- Understand bitwise operations basics
Lecture Summary
Key Concepts Covered:
- 8 primitive data types with ranges
- Variable declaration and initialization
- Variable naming conventions and rules
- Constants and final variables
- Type conversion (implicit and explicit)
- Variable scope and lifetime
- Introduction to arrays
Learning Outcomes Achieved:
- ✅ Master all primitive data types
- ✅ Understand memory allocation
- ✅ Apply proper variable naming
- ✅ Handle type conversions safely
- ✅ Use constants effectively
- ✅ Understand variable scope rules
- ✅ Implement practical programs
Next Lecture: Operators & Expressions
Topics: Arithmetic, relational, logical, bitwise, assignment operators, operator precedence
Thank You!
Questions & Discussion
Next: Lecture 04 - Operators & Expressions
Course: 4343203 Java Programming
Unit 1: Introduction to Java
GTU Semester 4

