Programming in Java
Unit 2: Data Types, Variables & Wrapper Classes
From primitive bytes to wrapper magic โ master every data type, variable scope, type casting, and wrapper class method that powers real Java applications.
โฑ๏ธ 5 hrs theory + 4 hrs lab | ๐ฐ Earning Potential: โน5Kโโน15K/month | ๐ 30 MCQs (Bloom's Mapped)
๐ผ Jobs this unlocks: Jr Java Developer (โน4โ6 LPA) | Backend Intern (โน3โ5 LPA) | Freelance Java Projects
Opening Hook โ The Data Behind Every Rupee
๐ณ How Paytm Handles โน1,00,000 Crore in Digital Payments
Open your Paytm app right now. See that wallet balance โ say โน2,347.50? Internally, Paytm stores it as a double: double balance = 2347.50;. When you tap "Pay โน50 for chai," the backend calls Double.toString(balance) to display it on screen, and Integer.parseInt(inputAmount) to validate your input. When Paytm checks your phone number length? That's "9876543210".length() returning an int. When it verifies your PIN? Each digit is a char, validated as a boolean.
Every single rupee you see, send, or receive on Paytm went through Java data types. The wallet balance is a double. The transaction ID is a long. The "Payment Successful" flag is a boolean. The UPI PIN is an array of char. And when Paytm wraps these primitives into objects for network transmission? That's Wrapper Classes โ Integer, Double, Character, Boolean.
What if YOU built this? What if you understood exactly how Java stores, converts, wraps, and validates every piece of data in a โน1 lakh crore fintech system? That's exactly what this chapter teaches you.
Learning Outcomes โ Bloom's Taxonomy Mapped (12 Outcomes)
| Bloom's Level | Learning Outcome |
|---|---|
| ๐ต Remember | List all 8 primitive data types with their sizes, default values, and ranges |
| ๐ต Remember | Recall all 53 reserved keywords in Java and identify valid/invalid identifiers |
| ๐ต Understand | Explain the difference between widening (implicit) and narrowing (explicit) type conversion with examples |
| ๐ต Understand | Describe the three types of variables โ local, instance, and static โ and their scopes |
| ๐ข Apply | Write Java programs using type casting to convert between primitive types correctly |
| ๐ข Apply | Use Wrapper classes (Integer, Double, Character, Boolean) for autoboxing, unboxing, parsing, and conversion |
| ๐ข Analyze | Compare access modifiers (public, private, protected, default) and determine appropriate usage in class design |
| ๐ข Analyze | Differentiate between primitive types and their Wrapper class counterparts in terms of memory, nullability, and use in Collections |
| ๐ Evaluate | Assess when to use int vs long vs BigInteger for Indian financial calculations (Aadhaar numbers, transaction IDs) |
| ๐ Evaluate | Evaluate the 5 uses of the static keyword and justify when each is appropriate |
| ๐ Create | Design and build a multi-currency converter application using proper data types, type casting, and wrapper class methods |
| ๐ Create | Construct a type-safe Java utility class demonstrating all variable scopes, access modifiers, and static members |
Concept Explanation โ Data Types, Variables & Wrapper Classes from Scratch
1. The 8 Primitive Data Types
Java is a strongly typed language โ every variable must have a declared type before you use it. Think of data types as different-sized containers in your kitchen. You don't store rice in a teacup (too small) or water in a thali (wrong shape). Similarly, Java gives you exactly 8 primitive "containers," each designed for a specific kind of data.
๐ฆ Complete Primitive Type Reference Table
| Type | Size | Default | Range | Example | Use Case |
|---|---|---|---|---|---|
byte | 1 byte (8 bits) | 0 | -128 to 127 | byte age = 25; | Small numbers, file I/O, network data |
short | 2 bytes (16 bits) | 0 | -32,768 to 32,767 | short pincode = 11001; | Pincode prefix, port numbers |
int | 4 bytes (32 bits) | 0 | -2ยณยน to 2ยณยน-1 (~ยฑ2.1 billion) | int salary = 500000; | Most integer math, loop counters, array indices |
long | 8 bytes (64 bits) | 0L | -2โถยณ to 2โถยณ-1 | long aadhaar = 123456789012L; | Aadhaar numbers, timestamps, large IDs |
float | 4 bytes (32 bits) | 0.0f | ยฑ3.4 ร 10ยณโธ (~7 decimal digits) | float pi = 3.14f; | Graphics, game coordinates, approx. math |
double | 8 bytes (64 bits) | 0.0d | ยฑ1.7 ร 10ยณโฐโธ (~15 decimal digits) | double balance = 2347.50; | Financial calculations, scientific computing |
char | 2 bytes (16 bits) | '\u0000' | 0 to 65,535 (Unicode) | char grade = 'A'; | Single characters, Unicode symbols, โน sign |
boolean | ~1 bit (JVM-dependent) | false | true or false | boolean isPaid = true; | Flags, conditions, toggles |
long? An Aadhaar number is 12 digits (e.g., 999912345678). The max value of int is ~2.1 billion (10 digits). So int simply cannot hold an Aadhaar number! You must use long. This is a real interview question at TCS and Infosys.
Java // Real-world data types in action โ Paytm-style payment record byte paymentMode = 2; // 1=UPI, 2=Wallet, 3=Card short bankCode = 1234; // IFSC prefix number int transactionAmount = 500; // โน500 payment long txnId = 20260623143052001L; // Unique transaction ID float cashbackPercent = 2.5f; // 2.5% cashback double walletBalance = 2347.50; // Precise wallet balance char currency = 'โน'; // Indian Rupee symbol (Unicode) boolean isSuccess = true; // Payment successful?
float pi = 3.14; โ this is a compile error! In Java, decimal literals are double by default. You must suffix with f: float pi = 3.14f;. Similarly, long literals need the L suffix: long x = 999999999999L;. Forgetting these suffixes is the #1 exam mistake.
2. Type Conversion โ Widening & Narrowing
Sometimes you need to store a value of one type into a variable of another type. Java handles this in two ways:
๐ Widening Conversion (Implicit / Automatic)
Analogy: Pouring water from a small glass into a big bucket โ no spill, no risk. Java does this automatically because no data is lost.
Direction: byte โ short โ int โ long โ float โ double
Also: char โ int
Java int salary = 500000; double doubleSalary = salary; // Automatic: int โ double System.out.println(doubleSalary); // 500000.0 char ch = 'A'; int ascii = ch; // Automatic: char โ int System.out.println(ascii); // 65
๐ป Narrowing Conversion (Explicit / Manual Casting)
Analogy: Pouring water from a bucket into a glass โ it might overflow! You must do this consciously, acknowledging the risk of data loss.
Direction: double โ float โ long โ int โ short โ byte
Syntax: (targetType) value
Java double price = 999.99; int roundedPrice = (int) price; // Explicit cast: double โ int System.out.println(roundedPrice); // 999 (decimal part LOST!) int bigNumber = 130; byte small = (byte) bigNumber; // Explicit cast: int โ byte System.out.println(small); // -126 (overflow!)
(byte) 130?" Answer: byte range is -128 to 127. 130 overflows โ wraps around โ result is -126. The formula is: 130 - 256 = -126. This is called modular arithmetic.
3. All 53 Java Keywords
Keywords are reserved words that Java has claimed for its own syntax. You cannot use them as variable names, class names, or method names. Think of them as "government-reserved land" โ you can't build your house on it.
๐ Complete Java Keywords Table (53 Keywords)
| Category | Keywords |
|---|---|
| Data Types (8) | byte short int long float double char boolean |
| Flow Control (12) | if else switch case default for while do break continue return yield |
| Access Modifiers (3) | public private protected |
| Class/Object (8) | class interface extends implements new this super instanceof |
| Modifiers (7) | static final abstract synchronized volatile transient native |
| Package (2) | package import |
| Exception (6) | try catch finally throw throws assert |
| Misc (5) | void enum strictfp const* goto* |
| Literals (2) | true false null (technically literals, not keywords, but reserved) |
* const and goto are reserved but not used in Java. They exist to prevent C/C++ programmers from using them accidentally.
const and goto are trick-question favorites โ they ARE reserved keywords but have NO functionality in Java.
Identifiers & Naming Conventions
An identifier is any name you give to a class, method, variable, or label. Rules:
- Can contain letters (A-Z, a-z), digits (0-9), underscore (_), and dollar sign ($)
- Cannot start with a digit
- Cannot be a keyword
- Case-sensitive:
salaryโSalaryโSALARY
| Convention | Style | Example |
|---|---|---|
| Class names | PascalCase | PaytmWallet, StudentRecord |
| Method names | camelCase | calculateInterest(), getBalance() |
| Variable names | camelCase | walletBalance, userName |
| Constants | UPPER_SNAKE_CASE | MAX_RETRY, GST_RATE |
| Packages | all lowercase | com.paytm.payments |
4. Variables โ Local, Instance & Static
A variable is a named memory location that holds a value. Java has three types of variables, each with different scope (where it's visible) and lifetime (how long it exists).
๐ Three Types of Variables
| Type | Declared In | Scope | Default Value | Lifetime |
|---|---|---|---|---|
| Local | Inside a method/block | Only within that method/block | โ None (must initialise) | Method execution |
| Instance | Inside a class, outside methods | Entire class (per object) | โ Type default (0, false, null) | Object lifetime |
| Static (Class) | Inside a class with static | Entire class (shared by all objects) | โ Type default | Program lifetime |
Java public class PaytmAccount { // Instance variable โ each user has their own double balance = 0.0; String userName; // Static variable โ shared across ALL accounts static int totalAccounts = 0; static final double GST_RATE = 0.18; public void deposit(double amount) { // Local variable โ exists only inside this method double gst = amount * GST_RATE; double net = amount - gst; balance += net; System.out.println("Deposited โน" + net); } }
int x; System.out.println(x); โ Error! Always assign a value: int x = 0;
5. Access Modifiers โ public, private, protected, default
Access modifiers control who can see and use your classes, methods, and variables. Think of them as security levels at an office building:
๐ Access Modifier Comparison Table
| Modifier | Same Class | Same Package | Subclass (other pkg) | Other Package | Analogy |
|---|---|---|---|---|---|
public | โ | โ | โ | โ | Open gate โ anyone can enter |
protected | โ | โ | โ | โ | Family WhatsApp group โ relatives only |
| default (no keyword) | โ | โ | โ | โ | Colony gate โ neighbours only |
private | โ | โ | โ | โ | Bedroom lock โ only you |
Java public class BankAccount { public String bankName = "SBI"; // Anyone can see protected String branch = "Connaught Place"; // Same package + subclasses String ifscCode = "SBIN0001234"; // Default โ same package only private double balance = 50000.0; // Only this class public double getBalance() { // Getter โ controlled access return balance; } }
private and provide public getters/setters?" Answer: Encapsulation โ you control what values are set. A setBalance() method can validate that the amount isn't negative. Direct field access can't.
6. The static Keyword โ 5 Uses
The static keyword means "belongs to the class, not to any specific object." Think of it as a college notice board โ it belongs to the college (class), not to any individual student (object).
โก 5 Uses of static in Java
| # | Use | Syntax | Example |
|---|---|---|---|
| 1 | Static Variable | static int count; | Shared counter across all objects |
| 2 | Static Method | static void display() | Math.sqrt(), Integer.parseInt() |
| 3 | Static Block | static { ... } | Initialise static variables when class loads |
| 4 | Static Nested Class | static class Inner { } | Utility helper classes inside a parent |
| 5 | Static Import | import static java.lang.Math.*; | Use sqrt(25) instead of Math.sqrt(25) |
Java public class RazorpayTransaction { static int totalTransactions = 0; // 1. Static variable static { // 3. Static block โ runs once when class loads System.out.println("Razorpay SDK initialized"); } String orderId; double amount; RazorpayTransaction(String id, double amt) { this.orderId = id; this.amount = amt; totalTransactions++; // Shared across all objects } static int getTotalTransactions() { // 2. Static method return totalTransactions; } }
7. Wrapper Classes โ Integer, Double, Character, Boolean
The Big Bazaar Analogy: You buy a gift โ say a nice pen. The pen itself is the primitive value. But if you're giving it as a Diwali gift, you wrap it in a decorative box with a ribbon. The wrapper makes it presentable, giftable, and "object-like." That's exactly what Wrapper classes do โ they wrap primitive values into objects.
int) is the same, but the gift box (Integer object) lets you pass it around, add it to collections, and give it a null state (empty box). Without the wrapper, you can't put a primitive into an ArrayList, HashMap, or any Java Collection.
๐ Primitive โ Wrapper Mapping
| Primitive | Wrapper Class | Parse Method | valueOf Method | toString Method |
|---|---|---|---|---|
byte | Byte | Byte.parseByte("10") | Byte.valueOf((byte)10) | Byte.toString((byte)10) |
short | Short | Short.parseShort("100") | Short.valueOf((short)100) | Short.toString((short)100) |
int | Integer | Integer.parseInt("500") | Integer.valueOf(500) | Integer.toString(500) |
long | Long | Long.parseLong("99999") | Long.valueOf(99999L) | Long.toString(99999L) |
float | Float | Float.parseFloat("3.14") | Float.valueOf(3.14f) | Float.toString(3.14f) |
double | Double | Double.parseDouble("99.9") | Double.valueOf(99.9) | Double.toString(99.9) |
char | Character | โ | Character.valueOf('A') | Character.toString('A') |
boolean | Boolean | Boolean.parseBoolean("true") | Boolean.valueOf(true) | Boolean.toString(true) |
Autoboxing & Unboxing (Java 5+)
Autoboxing = Java automatically wraps a primitive into its Wrapper object.
Unboxing = Java automatically unwraps a Wrapper object back to its primitive.
Java // AUTOBOXING: primitive โ Wrapper (automatic) int amount = 500; Integer wrappedAmount = amount; // int โ Integer (autoboxing) // UNBOXING: Wrapper โ primitive (automatic) Integer price = Integer.valueOf(999); int rawPrice = price; // Integer โ int (unboxing) // PARSING: String โ primitive String userInput = "1500"; int rupees = Integer.parseInt(userInput); // String โ int // TOSTRING: primitive โ String double balance = 2347.50; String display = Double.toString(balance); // double โ String "2347.5" // Using Wrappers in Collections ArrayList<Integer> cart = new ArrayList<>(); cart.add(299); // autoboxing: int โ Integer cart.add(599); int first = cart.get(0); // unboxing: Integer โ int
Integer.parseInt("12.5") throws NumberFormatException! The parseInt method only accepts whole number strings. For decimals, use Double.parseDouble("12.5"). This is a very common runtime error in student projects.
Integer.valueOf() vs Integer.parseInt(): Both parse strings, but parseInt() returns a primitive int, while valueOf() returns an Integer object. In most cases, use parseInt() for primitives and valueOf() when you need an object (e.g., for Collections).
Important Wrapper Class Utility Methods
Java // Integer utilities System.out.println(Integer.MAX_VALUE); // 2147483647 System.out.println(Integer.MIN_VALUE); // -2147483648 System.out.println(Integer.toBinaryString(10)); // "1010" System.out.println(Integer.toHexString(255)); // "ff" System.out.println(Integer.toOctalString(8)); // "10" // Character utilities System.out.println(Character.isDigit('9')); // true System.out.println(Character.isLetter('A')); // true System.out.println(Character.toUpperCase('a')); // 'A' System.out.println(Character.isWhitespace(' ')); // true // Boolean utilities System.out.println(Boolean.parseBoolean("true")); // true System.out.println(Boolean.parseBoolean("yes")); // false (only "true" works)
Learn by Doing โ 3-Tier Lab: Currency Converter INR โ USD/EUR/GBP
๐ข Tier 1 โ GUIDED: Basic INR โ USD Converter
Step 1: Create the file CurrencyConverter.java
Java import java.util.Scanner; public class CurrencyConverter { // Static constants โ exchange rates (as of June 2026) static final double USD_RATE = 83.50; // 1 USD = โน83.50 static final double EUR_RATE = 91.20; // 1 EUR = โน91.20 static final double GBP_RATE = 106.75; // 1 GBP = โน106.75 public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("=== INR Currency Converter ==="); System.out.print("Enter amount in INR: โน"); // Parse user input using Wrapper class method String input = sc.nextLine(); double inr = Double.parseDouble(input); // Type conversion: double โ int (narrowing) int roundedINR = (int) inr; // Calculate conversions double usd = inr / USD_RATE; double eur = inr / EUR_RATE; double gbp = inr / GBP_RATE; // Display using Wrapper toString() System.out.println("\n--- Conversion Results ---"); System.out.println("โน" + Double.toString(inr) + " = $" + String.format("%.2f", usd) + " USD"); System.out.println("โน" + roundedINR + " = โฌ" + String.format("%.2f", eur) + " EUR"); System.out.println("โน" + roundedINR + " = ยฃ" + String.format("%.2f", gbp) + " GBP"); // Boolean check boolean isLargeAmount = inr > 100000; System.out.println("Large transaction: " + Boolean.toString(isLargeAmount)); sc.close(); } }
Step 2: Compile & Run
Terminal
javac CurrencyConverter.java
java CurrencyConverter
Expected Output:
๐ Congratulations! You've used all 4 Wrapper classes (Double.parseDouble, Double.toString, Boolean.toString, Integer via casting), type conversion, static constants, and local variables โ all in one real program!
๐ก Tier 2 โ SEMI-GUIDED: Two-way Converter with Menu
Your Mission:
Extend the Tier 1 converter to support both directions (INRโForeign AND ForeignโINR) with a menu system.
Requirements:
- Display a menu:
1. INR โ USD | 2. INR โ EUR | 3. INR โ GBP | 4. USD โ INR | 5. EUR โ INR | 6. GBP โ INR - Use
Integer.parseInt()to read the menu choice - Use a
switchstatement withcharcases orintcases - Add input validation: if user enters non-numeric input, catch
NumberFormatException - Display results using
String.format("%.2f") - Use
staticmethods for each conversion (e.g.,static double inrToUsd(double inr))
Hints:
Java // Hint 1: Parse menu choice int choice = Integer.parseInt(sc.nextLine()); // Hint 2: Static conversion methods static double inrToUsd(double inr) { return inr / USD_RATE; } // Hint 3: Error handling try { double amount = Double.parseDouble(input); } catch (NumberFormatException e) { System.out.println("Invalid input! Enter a number."); }
boolean continueLoop = true; and ask "Convert again? (y/n)".
๐ด Tier 3 โ OPEN CHALLENGE: Full-featured Currency Converter Widget
The Brief:
Build a production-quality currency converter application with these features:
- CurrencyRate class with instance variables for currency code (
String), rate (double), symbol (char) - Static counter tracking total conversions performed
- Support 5+ currencies: INR, USD, EUR, GBP, JPY, AED
- Type validation: Use
Character.isDigit()andInteger.parseInt()for all inputs - Wrapper class usage: Store conversion history in
ArrayList<Double> - Access modifiers: Private rates, public methods, protected utility methods
- Display conversion history at the end with total, average, min, max amounts
Deliverable: A clean, well-commented Java program demonstrating every concept from this chapter.
Problem Set โ Syntax, Programming, Industry & Interview Questions
Syntax Questions (5)
- Identify and fix the error:
float temperature = 36.6; - What is the output?
System.out.println((int) 99.99); - Identify and fix the error:
int 2ndPlace = 2; - What is the output?
char ch = 'A'; System.out.println(ch + 1); - Will this compile?
byte b = 128;โ Explain why or why not.
Programming Questions (8)
- Write a Java program to find the size of all 8 primitive data types using their Wrapper class constants (e.g.,
Integer.SIZE,Byte.SIZE). - Write a program that accepts a temperature in Fahrenheit (as a
String), converts it to Celsius usingDouble.parseDouble(), and displays the result rounded to 2 decimal places. - Create a program that demonstrates widening conversion for all paths:
byte โ short โ int โ long โ float โ double. - Write a program that takes a character input and prints whether it is a digit, letter, uppercase, lowercase, or whitespace using
Characterclass methods. - Build a simple GST Calculator: input price as
String, parse todouble, calculate 18% GST, display base price, GST amount, and total. - Write a program that demonstrates the difference between
Integer.parseInt()andInteger.valueOf()by showing their return types. - Create a program with a class
Studenthaving: private instance variables (name, rollNo), a static variable (college name), and a static method to display total students. - Write a program that converts an integer to binary, octal, and hexadecimal using
Integerwrapper methods.
Industry Questions (3)
- Paytm Scenario: Paytm stores wallet balance as
double. Why notfloat? Calculate the precision difference when storing โน99,99,999.99 in both types. - Aadhaar Scenario: UIDAI stores Aadhaar numbers. A junior developer used
int. Explain why this fails and what type should be used. What about leading zeros โ should it be aString? - Razorpay Scenario: Razorpay processes payments in paise (โน500.00 = 50000 paise) to avoid floating-point errors. Discuss why
intin paise is better thandoublein rupees for financial applications.
Interview Questions (3)
- TCS favourite: What is the difference between autoboxing and unboxing? Give an example where autoboxing can cause a
NullPointerException. - Infosys favourite: Can we call a non-static method from a static method? Why or why not? How would you solve this?
- Wipro favourite: Explain the output:
Integer a = 127; Integer b = 127; System.out.println(a == b);andInteger c = 128; Integer d = 128; System.out.println(c == d);
a == b is true (same cached object), but c == d is false (different objects on heap). Always use .equals() for Wrapper comparisons!
MCQ Assessment Bank โ 30 Questions (Bloom's Mapped)
Remember / Identify (Q1โQ5)
Which of the following is NOT a primitive data type in Java?
- int
- boolean
- String
- char
The size of int in Java is:
- 2 bytes
- 4 bytes
- 8 bytes
- Depends on platform
The default value of a boolean instance variable is:
- true
- 0
- false
- null
Which keyword is reserved in Java but not currently used?
- abstract
- goto
- static
- final
goto and const are reserved keywords in Java but have no functionality. They exist to prevent C/C++ programmers from using them accidentally.The Wrapper class for int is:
- Int
- INTEGER
- Integer
- int_wrapper
Understand / Explain (Q6โQ10)
What is widening conversion?
- Converting an object to a primitive
- Converting a smaller primitive type to a larger one automatically
- Converting a String to an integer
- Converting a larger type to a smaller one
Why does Java require an explicit cast for narrowing conversion?
- It's a syntax rule with no practical reason
- To improve program speed
- Because data loss may occur when converting from a larger to smaller type
- Because Java doesn't support narrowing
(int) 99.99 loses the decimal part). Java forces an explicit cast so the programmer acknowledges this risk.What is autoboxing in Java?
- Manually creating Wrapper objects using constructors
- Automatic conversion of a primitive to its corresponding Wrapper class object
- Converting a String to a primitive
- Using boxing gloves in a Java program
Integer x = 5; โ Java auto-converts int 5 to Integer.valueOf(5).A local variable in Java:
- Gets a default value of 0
- Must be initialised before use
- Is shared across all methods
- Can be accessed from other classes
What does the static keyword mean for a variable?
- The variable cannot be changed
- The variable belongs to the class, not to any specific object
- The variable is private
- The variable is stored on the stack
Apply / Use (Q11โQ15)
What is the output of: System.out.println((int) 3.9 + (int) 4.1);
- 8
- 7
- 8.0
- 7.0
(int) 3.9 = 3 (truncated, not rounded). (int) 4.1 = 4. So 3 + 4 = 7.What does Integer.parseInt("100") return?
- The String "100"
- An Integer object with value 100
- The primitive int value 100
- A compilation error
parseInt() returns a primitive int. Use Integer.valueOf("100") to get an Integer object.Which statement correctly declares a long variable for an Aadhaar number?
long aadhaar = 123456789012;long aadhaar = 123456789012L;int aadhaar = 123456789012;Long aadhaar = "123456789012";
L suffix. Without it, Java treats the literal as int (which overflows for 12-digit numbers). Option A causes a compile error.What is the output of: System.out.println(Character.isDigit('โน'));
- true
- false
- Compilation error
- Runtime error
Character.isDigit() returns true only for '0'โ'9' and equivalent Unicode digits.What is the output of: byte b = (byte) 130; and System.out.println(b);
- 130
- -126
- 127
- Compilation error
Analyze / Compare (Q16โQ20)
What is the key difference between private and default (no modifier) access?
- No difference โ they're the same
privateis accessible within same class only; default is accessible within same packageprivateis accessible within same package; default is class-onlydefaultmakes the member public in subclasses
private restricts access to the declaring class only. Default (package-private) allows access from any class in the same package.When should you use double instead of float?
- When you need to save memory
- When you need higher precision (more decimal digits)
- When dealing with boolean values
- When working with Unicode characters
double provides ~15 decimal digits of precision vs float's ~7 digits. For financial calculations (e.g., bank balances), double is essential to avoid rounding errors.Compare: Integer.parseInt("50") vs Integer.valueOf("50")
- Both return the same type
parseIntreturnsint;valueOfreturnsIntegerparseIntreturnsInteger;valueOfreturnsint- They cannot parse the same input
parseInt() returns a primitive int. valueOf() returns an Integer object. Use parseInt when you need a primitive, valueOf when you need an object (e.g., for Collections).What is the difference between a local variable and an instance variable?
- Local variables are global; instance variables are local
- Local variables exist within a method and have no default; instance variables belong to an object and have defaults
- Instance variables must be static
- Local variables can only be
int
Why can't primitives be stored directly in an ArrayList?
- ArrayList doesn't support numbers
- Generics in Java work only with reference types (objects), not primitives
- Primitives are too slow for ArrayLists
- You need to use arrays instead
ArrayList<int> is invalid; you must use ArrayList<Integer>. Autoboxing handles the conversion automatically.Evaluate / Justify (Q21โQ25)
A banking application stores account balances. Which approach is BEST?
float balancedouble balanceint balanceInPaise(store paise, not rupees)String balance
int avoids floating-point precision errors. โน999.99 becomes 99999 paise. This is how Razorpay and Stripe handle payments internally. double (B) is acceptable for display but not for calculations.When is using static methods appropriate?
- When the method needs to access instance variables
- When the method performs a utility operation that doesn't depend on object state
- When we want the method to be slow
- When we need to create multiple objects
Math.sqrt(), Integer.parseInt(), and Arrays.sort(). They don't need object state, so creating an instance would be wasteful.Evaluate: "We should always use Wrapper classes instead of primitives for better OOP design."
- True โ OOP requires objects everywhere
- False โ Wrappers use more memory and are slower; use primitives when objects aren't needed
- True โ primitives are deprecated
- False โ Wrappers don't exist in modern Java
int. In performance-critical code (loops, arrays), primitives are 2โ3x faster. Use Wrappers only when needed (Collections, nullability, API requirements).A developer writes protected methods in a utility class. Is this a good practice?
- Yes โ protected is always the safest choice
- No โ utility classes should use
public staticmethods and aprivateconstructor to prevent instantiation - Yes โ it ensures backward compatibility
- No โ utility classes should use
defaultaccess
Math, Arrays, Collections) follow the pattern: public static methods + private constructor. protected is designed for inheritance hierarchies, not utility classes.Why does Integer a = 127; Integer b = 127; (a == b) return true, but Integer c = 128; Integer d = 128; (c == d) return false?
- Java is buggy for numbers above 127
- Java caches Integer objects from -128 to 127; values outside this range create new objects on the heap
- == always compares values for Wrapper types
- 128 is not a valid Integer value
IntegerCache) for Integer values -128 to 127. Values within this range return the same cached object (so == compares the same reference). Values outside create new heap objects. Always use .equals() for Wrapper comparisons.Create / Design (Q26โQ30)
You're designing a Student class. Which declaration is most appropriate for a student's phone number?
int phone = 9876543210;long phone = 9876543210L;String phone = "9876543210";double phone = 9876543210.0;
int overflows for 10-digit Indian numbers. long (B) works technically but loses leading zeros. String is the industry standard.Design a Product class for an e-commerce app. Which fields should be static?
- productName, price
- gstRate, totalProductsCreated
- productId, category
- description, imageUrl
gstRate (18% GST applies to all products equally) and totalProductsCreated (a class-level counter) are shared across all instances. Per-product fields like name, price, and ID should be instance variables.You need to store 1 million integers for a data processing task. Which approach is best?
ArrayList<Integer>int[] array = new int[1000000];long[] array = new long[1000000];ArrayList<String>with parsed values
int[] uses ~4 MB (4 bytes ร 1M). An ArrayList<Integer> uses ~20 MB (each Integer object has ~16 bytes overhead + 4 bytes pointer). For large datasets, primitive arrays are 5x more memory-efficient.You're building a configuration class. How should you declare a constant for maximum login attempts?
int maxAttempts = 3;public static final int MAX_LOGIN_ATTEMPTS = 3;private static int MAX_ATTEMPTS = 3;final int attempts = 3;
public (accessible), static (class-level, not per-object), and final (unchangeable). Naming convention: UPPER_SNAKE_CASE.Design a method signature for a currency converter that takes INR amount (as String from user input) and returns USD value. What is the best signature?
public void convert(int amount)public static double convertInrToUsd(String inrInput) throws NumberFormatExceptionprivate String convert(double amount)protected static int convertCurrency(float amount)
public (accessible), static (utility method, no object state needed), double return (precise USD value), String input (raw user input needs parsing), throws NumberFormatException (handles invalid input). This is clean, production-quality API design.Short Answer Questions (8 Questions)
SA-1: List all 8 primitive data types in Java with their sizes.
Answer: Java's 8 primitives are: byte (1 byte), short (2 bytes), int (4 bytes), long (8 bytes), float (4 bytes), double (8 bytes), char (2 bytes), boolean (~1 bit, JVM-dependent). These are not objects โ they are stored directly on the stack (for local variables) or within the object on the heap (for instance variables).
SA-2: What is the difference between widening and narrowing type conversion?
Answer: Widening (Implicit) converts a smaller type to a larger type automatically without data loss: int x = 5; double d = x; (int โ double). Narrowing (Explicit) converts a larger type to a smaller type manually, risking data loss: double d = 9.99; int x = (int) d; (double โ int, decimal lost). Narrowing requires an explicit cast operator (type).
SA-3: What is autoboxing and unboxing? Give one example of each.
Answer: Autoboxing = automatic conversion of primitive โ Wrapper: Integer obj = 42; (Java converts int 42 to Integer.valueOf(42)). Unboxing = automatic conversion of Wrapper โ primitive: int x = obj; (Java converts Integer back to int). These features were introduced in Java 5 to reduce boilerplate code when working with Collections.
SA-4: Explain the scope difference between local, instance, and static variables.
Answer: Local โ declared inside a method, exists only during method execution, must be initialised manually. Instance โ declared in class but outside methods, unique to each object, gets default values, exists as long as the object exists. Static โ declared with static, shared across all objects of the class, exists for the entire program lifetime, belongs to the class not objects.
SA-5: Compare public, private, protected, and default access modifiers.
Answer: public โ accessible everywhere (any class, any package). protected โ accessible in same package + subclasses in other packages. default (no keyword) โ accessible only within the same package. private โ accessible only within the declaring class. Order of increasing restriction: public โ protected โ default โ private.
SA-6: What are the 5 uses of the static keyword in Java?
Answer: (1) Static variable โ shared class-level variable. (2) Static method โ can be called without creating an object (e.g., Math.sqrt()). (3) Static block โ runs once when class is loaded, used for initialisation. (4) Static nested class โ inner class that doesn't need outer class instance. (5) Static import โ import static members directly (e.g., import static java.lang.Math.*;).
SA-7: What is the difference between Integer.parseInt() and Integer.valueOf()?
Answer: parseInt("100") returns a primitive int value 100. valueOf("100") returns an Integer object with value 100. Additionally, valueOf() uses the Integer cache (-128 to 127), making it more memory-efficient for small values. Use parseInt() when you need a primitive; use valueOf() when you need an object.
SA-8: Why can't you write ArrayList<int> in Java? How do you solve this?
Answer: Java generics use type erasure at compile time, which works only with reference types (objects), not primitives. int is a primitive, not an object. The solution is to use the Wrapper class: ArrayList<Integer>. Java's autoboxing automatically converts int values to Integer objects when adding to the list.
Long Answer Questions (3 Questions)
LA-1: Explain all 8 primitive data types in Java with a comprehensive comparison table. Include size, range, default values, and real-world use cases for each.
Answer:
Java provides exactly 8 primitive data types divided into 4 categories:
1. Integer Types: byte (8-bit, -128 to 127 โ used for file I/O and network data), short (16-bit, -32768 to 32767 โ rarely used, sometimes for legacy systems), int (32-bit, ~ยฑ2.1 billion โ the default integer type for most calculations), long (64-bit, ~ยฑ9.2 quintillion โ for large IDs like Aadhaar numbers and timestamps).
2. Floating-Point Types: float (32-bit, ~7 decimal digits โ for graphics and approximate calculations, must use f suffix), double (64-bit, ~15 decimal digits โ default decimal type, used for financial calculations and scientific computing).
3. Character Type: char (16-bit Unicode, 0 to 65535 โ stores single characters including Unicode like 'โน'. Uses single quotes).
4. Boolean Type: boolean (~1 bit โ only true or false, used for conditions and flags).
Key points: All sizes are fixed (platform-independent). Instance/static variables get defaults (0, 0.0, '\u0000', false). Local variables must be manually initialised. Literals: long needs L suffix, float needs f suffix.
LA-2: Explain Wrapper Classes in Java. Discuss autoboxing, unboxing, and important methods of Integer, Double, Character, and Boolean classes with code examples.
Answer:
Wrapper classes provide an object representation for each primitive type: intโInteger, doubleโDouble, charโCharacter, booleanโBoolean, etc. They exist because Java Collections (ArrayList, HashMap) require objects, not primitives.
Autoboxing (Java 5+): Automatic primitive โ Wrapper conversion.
Java Integer x = 42; // compiler converts to Integer.valueOf(42) ArrayList<Double> prices = new ArrayList<>(); prices.add(99.99); // double autoboxed to Double
Unboxing: Automatic Wrapper โ primitive conversion.
Java Integer obj = Integer.valueOf(100); int val = obj; // Integer unboxed to int
Key Methods: parseInt(String) โ String to int. valueOf(int) โ int to Integer. toString(int) โ int to String. toBinaryString(int) โ int to binary representation. Character.isDigit(char), Character.isLetter(char), Character.toUpperCase(char). Boolean.parseBoolean(String) โ only returns true for the exact string "true".
Important Caveat: Integer caching (-128 to 127) means == works for small values but fails for larger values. Always use .equals() for Wrapper comparisons.
LA-3: Explain the static keyword in Java with all 5 uses. Illustrate with a real-world class design example.
Answer:
The static keyword means "belongs to the class, not to any specific object." It has 5 uses:
1. Static Variable: Shared across all instances. Example: static int totalAccounts = 0; in a BankAccount class โ incremented in constructor, tracks total accounts created.
2. Static Method: Can be called without creating an object. Cannot access instance variables or use this. Example: static double calculateGST(double amount) โ utility method that doesn't need object state.
3. Static Block: Executes once when the class is first loaded (before any constructor). Used for complex static variable initialisation. Example: Loading database configuration from a file.
4. Static Nested Class: An inner class that doesn't hold a reference to the outer class instance. Used for helper/utility classes. Example: Map.Entry is a static nested class inside Map.
5. Static Import: import static java.lang.Math.*; lets you use sqrt(25) instead of Math.sqrt(25). Improves readability for frequently used utilities.
Java public class BankAccount { static int totalAccounts = 0; // 1. Static variable static { System.out.println("Bank system initialized"); } // 3. Static block private String holder; private double balance; BankAccount(String name) { holder = name; totalAccounts++; } static int getTotalAccounts() { return totalAccounts; } // 2. Static method }
Lab Programs โ Additional Practice
The primary lab for this unit is the Currency Converter covered in Section D (3-Tier Labs). Additional practice programs are included in the Problem Set (Section E). Focus on completing all three tiers of the currency converter lab before moving to the next unit.
Industry Spotlight โ A Day in the Life
๐ฉโ๐ป Priya Nair, 27 โ Backend Java Developer at Razorpay, Bangalore
Background: B.Tech (IT) from NIT Calicut. Learned Java in 2nd year. Built a UPI payment simulator as a college project. Got placed at Razorpay through off-campus drive after showcasing her GitHub projects.
A Typical Day:
9:30 AM โ Morning standup with the Payments team. Discuss a bug where certain transaction amounts are showing โน0.01 discrepancy due to floating-point precision errors.
10:00 AM โ Fix the bug: refactor payment amount storage from double (rupees) to long (paise). โน999.99 โ stored as 99999L paise. Uses Integer.parseInt() to validate merchant input.
11:30 AM โ Write unit tests. Tests use Boolean.parseBoolean() for config flags and Double.parseDouble() for expected amounts in test assertions.
1:00 PM โ Lunch at Razorpay's cafeteria in Koramangala. Discusses with teammate why they use static final constants for payment gateway codes.
2:00 PM โ Code review. Catches a junior developer using == to compare Integer objects instead of .equals(). Explains the Integer cache issue (-128 to 127).
4:00 PM โ Design a new PaymentConfig class. Uses private fields, public getters, static factory methods, and final constants. Pure data types and wrapper classes in action.
5:30 PM โ Attends internal tech talk on "Why Razorpay migrated from BigDecimal to long (paise) for payment processing."
| Detail | Info |
|---|---|
| Tools Used Daily | Java 17, Spring Boot, IntelliJ IDEA, Git, MySQL, Redis, JUnit |
| Entry Salary (2026) | โน4โ6 LPA + benefits |
| Mid-Level (3โ5 yrs) | โน12โ20 LPA |
| Senior (7+ yrs) | โน25โ45 LPA |
| Companies Hiring Java Devs | Razorpay, Flipkart, PhonePe, Paytm, Zerodha, TCS, Infosys, Wipro, HCL, Amazon India, Google India |
Earn With It โ Currency Converter Widgets & Freelance Income
๐ฐ Your Earning Path After This Chapter
Portfolio Piece: "Multi-Currency Converter with Type-Safe Validation" โ a clean Java program demonstrating all data types, wrapper classes, and proper OOP design.
Beginner Gig Ideas:
โข Currency converter widget for travel agency websites โ โน3,000โโน8,000
โข Unit conversion tool (kmโmiles, kgโlbs, ยฐCโยฐF) for educational apps โ โน2,000โโน5,000
โข GST calculator with input validation for small businesses โ โน2,000โโน6,000
โข EMI calculator widget for loan comparison websites โ โน5,000โโน12,000
| Platform | Best For | Typical Rate |
|---|---|---|
| Internshala | Java internships & fresher projects | โน3,000โโน10,000/project |
| Fiverr | Quick calculator/converter gigs | $15โ$60/gig (โน1,200โโน5,000) |
| Upwork | Java development projects | $20โ$50/hour |
| Direct outreach to startups | โน5,000โโน15,000/project | |
| GitHub + Portfolio | Showcase projects for placements | Leads to โน4โ6 LPA jobs |
โฑ๏ธ Time to First Earning: 2โ4 weeks (complete all 3 lab tiers, push to GitHub, create Fiverr/Internshala gig)
Chapter Summary & Code Tweet
๐ง Key Takeaways from Unit 2
- 8 primitive types: byte (1B), short (2B), int (4B), long (8B), float (4B), double (8B), char (2B), boolean (~1 bit)
- Widening = automatic (small โ big, no data loss). Narrowing = manual cast (big โ small, risk of data loss)
- 53 keywords โ reserved words like
class,static,void.const&gotoreserved but unused - Identifiers follow PascalCase (classes), camelCase (methods/variables), UPPER_SNAKE (constants)
- 3 variable types: Local (method scope, no default), Instance (object scope, has default), Static (class scope, shared)
- 4 access modifiers: public โ protected โ default โ private (decreasing visibility)
- static = belongs to class: 5 uses โ variable, method, block, nested class, import
- Wrapper classes wrap primitives into objects: Integer, Double, Character, Boolean
- Autoboxing = primitive โ Wrapper. Unboxing = Wrapper โ primitive
- Key methods:
parseInt(),valueOf(),toString(),parseDouble(),isDigit(),isLetter()
๐ฑ Code Tweet (< 280 chars)
int holds your salary,
long holds your Aadhaar,
double holds your wallet โน,
boolean holds your payment status,
and Integer.parseInt() makes it all work.
#Java #DataTypes #EduArtha ๐ฎ๐ณโ
Earning Checkpoint โ What You've Mastered
| Skill Learned | Tool/Method | Portfolio Output | Earning-Ready? |
|---|---|---|---|
| 8 Primitive Data Types | Java code | Type demo program | โ Yes โ fundamental interview skill |
| Type Casting & Conversion | Widening/Narrowing | Converter programs | โ Yes โ used in every Java project |
| 53 Keywords & Identifiers | Java reference | โ | โ Yes โ MCQ/exam essential |
| Variable Types & Scope | Local/Instance/Static | Class design programs | โ Yes โ core interview topic |
| Access Modifiers | public/private/protected | OOP class design | โ Yes โ architecture skill |
| Static Keyword (5 uses) | Static var/method/block | Utility class programs | โ Yes โ top interview question |
| Wrapper Classes | Integer, Double, etc. | Converter with validation | โ Yes โ used in every production app |
| Currency Converter | Complete Java app | GitHub portfolio project | โ Yes โ โน3Kโโน8K freelance gig |
โ Unit 2 complete. MCQs: 30. Ready for Unit 3!
[QR: Link to EduArtha video tutorial โ Java Data Types & Wrapper Classes]