Generic Classes in Java – Clean Explanation with Examples 🚀 Generics in Java are a compile-time type-safety mechanism that allows you to write parameterized classes, methods, and interfaces. Instead of hardcoding a type, you define a type placeholder (like T) that gets replaced with an actual type during usage. 🔹Before Generics (Problem): class Box { Object value; } Box box = new Box(); box.value = "Hello"; Integer x = (Integer) box.value; // Runtime error ❌ Issues: • No type safety • Manual casting required • Errors occur at runtime 🔹With Generics (Solution): class Box<T> { private T value; public void set(T value) { this.value = value; } public T get() { return value; } } 🔹Usage: public class Main { public static void main(String[] args) { Box<Integer> intBox = new Box<>(); intBox.set(10); int num = intBox.get(); // ✅ No casting Box<String> strBox = new Box<>(); strBox.set("Hello"); String text = strBox.get(); } } 🔹Bounded Generics: 1.Upper Bound (extends) → Read Only: Restricts type to a subclass List<? extends Number> list; ✔ Allowed: Integer, Double ❌ Not Allowed: String 👉 Why Read Only? You can safely read values as Number, but you cannot add specific types because the exact subtype is unknown at compile time. 2.Lower Bound (super) → Write Only: Restricts type to a superclass List<? super Integer> list; ✔ Allowed: Integer, Number, Object ❌ Not Allowed: Double, String 👉 Why Write Only? You can safely add Integer (or its subclasses), but when reading, you only get Object since the exact type is unknown. 🔹Key Takeaway: Generics = Type Safety + No Casting + Compile-Time Errors Clean code, fewer bugs, and better maintainability - that’s the power of Generics 💡 #Java #Generics #Programming #SoftwareEngineering #Coding
Pramod Kumar.A S’ Post
More Relevant Posts
-
🔍 Understanding Arrays in Java (Memory & Indexing) Today I learned an important concept about arrays in Java: Given an array: int[] arr = {10, 20, 30, 40, 50}; We often think about how elements are stored in memory. In Java: ✔ Arrays are stored in memory (heap) ✔ Each element is accessed using an index ✔ JVM handles all memory internally So when we write: arr[0] → 10 arr[1] → 20 arr[2] → 30 arr[3] → 40 arr[4] → 50 👉 We are NOT accessing memory directly 👉 We are using index-based access Very-Important Point: 👉 Concept (Behind the scenes) we access elements using something like base + (bytes × index) in Java 💡 Let’s take an example: int[] arr = {10, 20, 30, 40, 50}; When we write: arr[2] 👉 We directly get 30 But what actually happens internally? 🤔 Behind the scenes (Conceptual): Address of arr[i] = base + (i × size) let's suppose base is 100 and we know about int takes 4 bytes in memory for every element :100,104,108,112,116 So internally: arr[2] → base + (2 × 4) Now base is : 100+8=108 now in 108 we get the our value : 30 Remember guys this is all happening behind the scenes 👉 You DON’T calculate it 👉 JVM DOES it for you 👉 But You Still need to know ✔ Instead, it provides safety and abstraction 🔥 Key Takeaway: “In Java, arrays are accessed using indexes, and memory management is handled by the JVM.” This concept is very useful for: ✅ Beginners in Java ✅ Understanding how arrays work internally ✅ Building strong programming fundamentals #Java #Programming #DSA #Coding #Learning #BackendDevelopment
To view or add a comment, sign in
-
💻 String vs StringBuffer vs StringBuilder in Java – Know the Difference! In Java, handling text data is very common. Let’s understand the three important classes: 🔹 1. String ✔ Immutable (cannot be changed once created) ✔ Any modification creates a new object ✔ Safe and widely used Example: "String s = "Hello";" "s = s + " World"; // creates new object" --- 🔹 2. StringBuffer ✔ Mutable (can be changed) ✔ Thread-safe (synchronized) ✔ Slightly slower due to synchronization Example: "StringBuffer sb = new StringBuffer("Hello");" "sb.append(" World");" --- 🔹 3. StringBuilder ✔ Mutable (can be changed) ✔ Not thread-safe ✔ Faster than StringBuffer Example: "StringBuilder sb = new StringBuilder("Hello");" "sb.append(" World");" --- 💡 Key Difference: String = Immutable StringBuffer = Mutable + Thread-safe StringBuilder = Mutable + Faster 🚀 Use String for simple tasks, StringBuffer for multi-threading, and StringBuilder for better performance in single-threaded applications. #FortuneCloudTechnology #Java #Programming #String #JavaBasics #Coding #Developers #Learning
To view or add a comment, sign in
-
Day 9 of Java Series ☕💻 Today’s topic is BufferedReader — a powerful way to take fast input in Java 🚀 🧠 What is BufferedReader? BufferedReader is a class in Java used to read text efficiently from input streams (like keyboard or file). It reads data in chunks (buffer) instead of character-by-character → faster performance ⚡ ⚙️ Why Use BufferedReader? ✔ Faster than Scanner ✔ Efficient for large input ✔ Reduces I/O operations ✔ Used in competitive programming 🔗 How it Works? 👉 Works with InputStreamReader to convert bytes into characters System.in → InputStreamReader → BufferedReader 💻 Example Code: import java.io.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter your name: "); String name = br.readLine(); System.out.println("Hello " + name); } } ⚡ Important Methods: readLine() → Reads full line read() → Reads single character close() → Closes stream ⚠️ Important Notes: Does NOT parse input automatically Must handle exceptions (IOException) Needs conversion for numbers 👉 Example: Java id="br2" Copy code int num = Integer.parseInt(br.readLine()); 🎯 Why Important? ✔ Used in interviews & CP ✔ Improves performance ✔ Important for backend & file handling 🚀 Pro Tip: Use BufferedReader + StringTokenizer for ultra-fast input in competitive programming 🔥 📢 Hashtags: #Java #BufferedReader #JavaSeries #Coding #Programming #Developers #LearnJava #Tech
To view or add a comment, sign in
-
-
💻 Generics in Java — Write Flexible & Type-Safe Code 🚀 If you’ve ever faced ClassCastException or messy type casting… Generics are your solution 🔥 This visual breaks down Java Generics in a simple yet practical way 👇 🧠 What are Generics? Generics allow you to write type-safe and reusable code by using type parameters (<T>). 👉 Instead of hardcoding data types, you write code that works with any type 🔍 Why Generics? ✔ Eliminates explicit type casting ✔ Ensures compile-time type safety ✔ Improves code reusability ✔ Makes code cleaner and readable 🔄 Core Concepts: 🔹 Generic Class class Box<T> { T data; } 👉 Same class → works with String, Integer, etc. 🔹 Generic Method public <T> void printArray(T[] arr) 👉 Works for any data type 🔹 Bounded Types <T extends Number> 👉 Restrict types (only numbers allowed) 🔹 Wildcards (?) <?> → Any type <? extends T> → Upper bound <? super T> → Lower bound 🔹 Type Inference (Diamond Operator) List<String> list = new ArrayList<>(); 👉 Cleaner code, compiler infers type ⚡ Generics with Collections: List<String> names = new ArrayList<>(); 👉 Ensures only String values are stored 💡 Real impact: Without generics → Runtime errors ❌ With generics → Compile-time safety ✅ 🎯 Key takeaway: Generics are not just syntax — they are the foundation of writing robust, scalable, and reusable Java code. #Java #Generics #Programming #BackendDevelopment #SoftwareEngineering #Coding #100DaysOfCode #Learning
To view or add a comment, sign in
-
-
💻 Generics in Java — Write Flexible & Type-Safe Code 🚀 If you’ve ever faced ClassCastException or messy type casting… Generics are your solution 🔥 This visual breaks down Java Generics in a simple yet practical way 👇 🧠 What are Generics? Generics allow you to write type-safe and reusable code by using type parameters (<T>). 👉 Instead of hardcoding data types, you write code that works with any type 🔍 Why Generics? ✔ Eliminates explicit type casting ✔ Ensures compile-time type safety ✔ Improves code reusability ✔ Makes code cleaner and readable 🔄 Core Concepts: 🔹 Generic Class class Box<T> { T data; } 👉 Same class → works with String, Integer, etc. 🔹 Generic Method public <T> void printArray(T[] arr) 👉 Works for any data type 🔹 Bounded Types <T extends Number> 👉 Restrict types (only numbers allowed) 🔹 Wildcards (?) <?> → Any type <? extends T> → Upper bound <? super T> → Lower bound 🔹 Type Inference (Diamond Operator) List<String> list = new ArrayList<>(); 👉 Cleaner code, compiler infers type ⚡ Generics with Collections: List<String> names = new ArrayList<>(); 👉 Ensures only String values are stored 💡 Real impact: Without generics → Runtime errors ❌ With generics → Compile-time safety ✅ 🎯 Key takeaway: Generics are not just syntax — they are the foundation of writing robust, scalable, and reusable Java code. #Java #Generics #Programming #BackendDevelopment #SoftwareEngineering #Coding #100DaysOfCode #Learning
To view or add a comment, sign in
-
-
⏳ Day 15 – 1 Minute Java Clarity – static Keyword in Java One keyword… but it changes everything! ⚡ 📌 What is static? When something is static, it belongs to the CLASS — not to any object. 👉 All objects share the same static member. 📌 Static Variable: class Student { String name; static String school = "Java Academy"; } 👉 Every student object shares the same school name. ✔ Memory created only ONCE in Method Area. 📌 Static Method: class MathUtils { static int square(int n) { return n * n; } } MathUtils.square(5); // No object needed! ⚠️ Static methods CANNOT access non-static variables directly. ⚠️ this keyword is NOT allowed inside static methods. 📌 Static Block: static { System.out.println("Runs before main()!"); } 👉 Executes ONCE when class loads — even before main() runs! ✔ Used for one-time setup like DB config loading. 💡 Real-time Example: Think of a company: Every employee has their own name → non-static But company name is the same for all → static ✅ ⚠️ Interview Trap: Why is main() static? 👉 JVM calls main() without creating any object. If main() wasn't static — who would create the object first? 🤔 💡 Quick Summary ✔ static = belongs to class, not object ✔ Static block runs before main() ✔ Static methods can't use this or non-static members 🔹 Next Topic → final keyword in Java Did you know static block runs before main()? Drop 🔥 if this was new! #Java #JavaProgramming #StaticKeyword #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
To view or add a comment, sign in
-
-
Most Java mistakes I see in code reviews come from the same 20 misunderstandings. After reviewing thousands of pull requests, these patterns keep showing up, especially from developers in their first 2 years. Here is what trips people up the most: → Using == instead of .equals() for String comparison → Mutating Date objects when LocalDate exists → Throwing checked exceptions for programming errors → Using raw types instead of generics → Concatenating Strings in loops instead of StringBuilder → Writing nested null checks instead of using Optional → Defaulting to arrays when ArrayList gives you flexibility → Wrapping everything in synchronized when ConcurrentHashMap exists → Catching Exception instead of the specific type you expect → Making utility methods static when they should be instance methods → Using new String("hello") instead of string literals → Using Integer when int would suffice → Repeating type args instead of using the diamond operator → Manual close() in finally instead of try-with-resources → Using static final int constants instead of enums → Writing verbose for-if-add loops instead of streams → Using Arrays.asList when List.of gives true immutability → Spelling out full types when var keeps code clean → Writing boilerplate classes when records do the job → Concatenating strings with \n instead of using text blocks None of these are hard to fix once you see the pattern. The real problem is that nobody points them out early enough. Save this for your next code review. #Java #SoftwareDevelopment #Programming #CleanCode #CodingTips
To view or add a comment, sign in
-
🚀 Day 6 of Java Series — Count Vowels Using Streams Ever wondered how to count vowels in a string using Java 8 in a clean and functional way? Here’s a simple yet powerful approach using Streams 👇 import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; public class CountOfVowels { public static void main(String[] args) { String name = "Microservices"; List<String> vowels = Arrays.asList("a", "e", "i", "o", "u"); Map<String, Long> map = Arrays.stream(name.split("")) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); List<Map.Entry<String, Long>> finalMap = map.entrySet().stream() .filter(entry -> vowels.contains(entry.getKey())) .toList(); System.out.println(finalMap); } } 🔍 How it works: 1️⃣ name.split("") → Converts string into individual characters 2️⃣ groupingBy(Function.identity(), counting()) → Counts frequency of each character 3️⃣ Filter step → Keeps only vowels 4️⃣ Final result → List of vowels with their count 👉 Output: [e=2, i=2, o=1] #Java #Java8 #Streams #Coding #Developers #Learning
To view or add a comment, sign in
-
Day14 Java Practice: Maximum Product of Three Elements in an Array While practicing Java, I solved an interesting array problem: 👉 Find the maximum product that can be formed using any three elements from the array. Example: Input: {10, 3, 5, 6, -20} At first, it looks like we just need the three largest numbers. But the twist is: negative numbers can change the result! 🧠 Key Idea: The product of two negative numbers becomes positive So we must compare: Product of the three largest numbers Product of two smallest (most negative) numbers and the largest number ================================================= // Online Java Compiler // Use this editor to write, compile and run your Java code online import java.util.*; class Main { public static void main(String[] args) { int a [] ={10,3,5,6,-20}; Arrays.sort(a); int n=a.length; System.out.println(Arrays.toString(a)); int result1=a[n-1]*a[n-2]*a[n-3]; int result2=a[0]*a[1]*a[n-1]; int result =Math.max(result1,result2); System.out.println(result); } } Output:[-20, 3, 5, 6, 10] 300 #JavaDeveloper #Arrays #CodingPractice #QualityEngineering #TechLearning
To view or add a comment, sign in
-
-
Primitives vs. Objects in Java Why does some Java code turn purple in your IDE while other code stays black? It's not random—it's telling you something important. Primitive types like int, char, long, and double turn purple because they're baked directly into Java. They're the building blocks, the simplest forms of data the language recognizes. Objects like String don't get that color treatment because they're more complex structures. Here's the practical difference that matters: Objects give you access to the dot (.) operator—a key that unlocks built-in methods. With a String, you can call .toUpperCase(), .toLowerCase(), .length(), and dozens of other methods that manipulate your data. Primitives? They just hold a value. No dot, no methods, no extras. Once you understand this distinction, you'll start reading your IDE's color coding like a second language. Did you know this difference when you started? Drop a 🟣 if this clicked something for you. #java
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development