☕ Java Generics – Upper Bounded Wildcards Explained In Java Generics, the question mark (?) represents a wildcard, meaning an unknown type. Sometimes, we need to restrict the type of objects that can be passed to a method — especially when working with numbers or specific class hierarchies. That’s where Upper Bounded Wildcards come into play. 🔹 What is an Upper Bounded Wildcard? To restrict a wildcard to a specific type or its subclasses, we use: <? extends ClassName> This means: 👉 Accept ClassName or any of its subclasses. For example, if a method should only work with numeric types, we restrict it to Number and its subclasses like Integer, Double, etc. As explained in the document (Page 1), the syntax uses ? followed by the extends keyword to define the upper bound. 🔹 Practical Example From the example shown (Page 2), a method calculates the sum of elements in a list: public static double sum(List<? extends Number> numberlist) { double sum = 0.0; for (Number n : numberlist) sum += n.doubleValue(); return sum; } 📌 Why ? extends Number? ✔ Ensures only numeric types are allowed ✔ Accepts List<Integer> ✔ Accepts List<Double> ✔ Maintains type safety 🔹 Usage in Main Method List<Integer> integerList = Arrays.asList(1, 2, 3); System.out.println("sum = " + sum(integerList)); List<Double> doubleList = Arrays.asList(1.2, 2.3, 3.5); System.out.println("sum = " + sum(doubleList)); 🔹 Output (Page 3) sum = 6.0 sum = 7.0 This demonstrates how the same method works seamlessly with different numeric types. 💡 Upper bounded wildcards improve flexibility while maintaining compile-time type safety. They are essential for writing reusable and robust generic methods in Java. #Java #Generics #UpperBoundedWildcards #JavaProgramming #OOP #FullStackJava #Developers #AshokIT
Java Generics: Upper Bounded Wildcards Explained
More Relevant Posts
-
ArrayList ✈️ In Java, an ArrayList is a member of the Java Collections Framework and resides in the java.util package. While a standard Java array (e.g., int[]) is fixed in length, an ArrayList is a resizable-array implementation of the List interface. How It Works: The "Growing" Mechanism When you add an element to an ArrayList, Java checks if there is enough room in the underlying memory. If the internal array is full, the ArrayList performs the following: It allocates a new, larger array ✅Key Features in Java Type Safety: It uses Generics, allowing you to specify what type of data it holds (e.g., ArrayList<String>). Wrapper Classes: It cannot store primitive types (like int, double, char) directly. Instead, Java uses "Autoboxing" to convert them into objects (like Integer, Double, Character). Nulls and Duplicates: It allows you to store duplicate elements and null values. Unsynchronized: By default, it is not thread-safe. If multiple threads access it simultaneously, you must handle synchronization manually. It copies all existing elements to the new array. It updates its internal reference to this new array. ✅ArrayList vs. LinkedList A common interview question is when to use ArrayList over LinkedList. ArrayList: Best for frequent access and storing data where you mostly add/remove from the end. LinkedList: Best if you are constantly inserting or deleting items from the beginning or middle of the list. Would you like me to explain the specific differences between ArrayList and Vector, or perhaps show you how to sort an ArrayList using Collections.sort(). Huge thanks for the mentorship on Java ArrayList Anand Kumar Buddarapu Saketh Kallepu Uppugundla Sairam #ArrayList #Java #DataStructures #Programming #Coding #SoftwareEngineering #Backend #JavaDeveloper #Algorithms #TechTips #ComputerScience
To view or add a comment, sign in
-
DAY 24: CORE JAVA 💻 Understanding Buffer Problem & Wrapper Classes in Java While working with Java input using Scanner, many beginners face a common issue called the Buffer Problem. 🔹 What is the Buffer Problem? When we use "nextInt()", "nextFloat()", etc., the scanner reads only the number but leaves the newline character ("\n") in the input buffer. Example: Scanner scan = new Scanner(System.in); int n = scan.nextInt(); // reads number String name = scan.nextLine(); // reads leftover newline ⚠️ The "nextLine()" does not wait for user input because it consumes the leftover newline from the buffer. ✅ Solution: Use an extra "nextLine()" to clear the buffer. int n = scan.nextInt(); scan.nextLine(); // clears the buffer String name = scan.nextLine(); 📌 This is commonly called a dummy nextLine() to flush the buffer. 🔹 Wrapper Classes in Java Java provides Wrapper Classes to convert primitive data types into objects. Primitive Type| Wrapper Class byte| Byte short| Short int| Integer long| Long float| Float char| Character 💡 Wrapper classes allow: - Converting String to primitive values - Storing primitive data in collections - Using useful utility methods Example: String s = "123"; int num = Integer.parseInt(s); // String → int 🔹 Example Use Case Suppose employee data is entered as a string: 1,Swathi,30000 We can split and convert values using wrapper classes: String[] arr = s.split(","); int empId = Integer.parseInt(arr[0]); String empName = arr[1]; int empSal = Integer.parseInt(arr[2]); 🚀 Key Takeaways ✔ Always clear the buffer when mixing "nextInt()" and "nextLine()" ✔ Wrapper classes help convert String ↔ primitive types ✔ They are essential when working with input processing and collections 📚 Concepts like these strengthen the core Java foundation for developers and interview preparation. TAP Academy #Java #CoreJava #JavaProgramming #WrapperClasses #Programming #SoftwareDevelopment
To view or add a comment, sign in
-
-
Core Java Fundamentals :Key Traits of Metaspace Permanent Generation in Java PermGen (Permanent Generation) was a memory area in the Java Virtual Machine (JVM) used before Java 8 to store class metadata, interned strings, and static variables. It was part of the JVM heap space and had a fixed size, making it difficult to manage memory efficiently. Fixed and Hard-to-Tune Size in PermGen PermGen had a fixed maximum size, which was often too small for applications with many classes. Correct Tuning was Tricky Even though it was configurable using -XX:MaxPermSize, tuning it correctly was difficult. PermGen was not dynamically expanding Unlike Metaspace, on the other hand, dynamically expands using native memory, eliminating manual tuning issues. OutOfMemoryError If class metadata exceeded 256MB, the application would crash with OutOfMemoryError: PermGen space. Key Features of Metaspace Stores Class Metadata It holds information about classes, methods, and their runtime representations (like method bytecode and field details). Unlike PermGen, it does not store Java objects (which reside in the heap). Uses Native Memory Unlike PermGen, which had a fixed maximum size, Metaspace dynamically expands using native memory(outside the heap), reducing Out of memory errors. Automatic Growth & GC Handling The JVM automatically manages Metaspace size based on the application’s needs. Class metadata is garbage collected when classes are no longer needed (such as when an application uses dynamic class loading). Configurable Maximum Size -XX:MaxMetaspaceSize=256m // Limits Metaspace to 256MB -XX:MetaspaceSize=128m // Initial size before expanding ☕ If this helped you — support my work: 👉 Buy Me a Coffee -https://lnkd.in/ebXVUJn2 #JVMInternals #JavaPerformance #MemoryManagement #SpringBoot #Microservices #SystemDesign
To view or add a comment, sign in
-
-
Most Java developers get confused by this exception. Let me explain why. You run this code: System.out.println("12345".charAt(6)); And the stack trace says StringIndexOutOfBoundsException. But wait... shouldn't it be IndexOutOfBoundsException? 🤔 Here's the thing: it IS an IndexOutOfBoundsException. Java's exception hierarchy uses inheritance to give you MORE specific information, not different information. The hierarchy looks like this: RuntimeException └── IndexOutOfBoundsException ├── StringIndexOutOfBoundsException └── ArrayIndexOutOfBoundsException This is polymorphism applied to exceptions 💡 → charAt() throws StringIndexOutOfBoundsException because the problem happened in a String → array[10] throws ArrayIndexOutOfBoundsException because the problem happened in an array → list.get(99) throws IndexOutOfBoundsException because the problem happened in a collection → A catch(IndexOutOfBoundsException e) block catches ALL of them Why does this matter? When you write catch blocks, you can choose your level of specificity. Catching the parent handles everything. Catching the child gives you precise control over what you handle and what you propagate. This is the same design principle behind Java's entire exception framework: specificity through inheritance. Understanding this hierarchy is what separates a developer who reads stack traces from one who truly understands them. ⚡ What other Java exceptions have tripped you up? Drop them in the comments 👇 📊 Oracle Java SE 17 Docs - IndexOutOfBoundsException API (2025) https://lnkd.in/eN_5XAp4 📊 Baeldung - Java ArrayIndexOutOfBoundsException (2025) https://lnkd.in/evZcjMHs 📊 Rollbar - How to Handle StringIndexOutOfBoundsException in Java (2022) https://lnkd.in/erHwcX4T #Java #SoftwareEngineering #Backend #ExceptionHandling #Programming #OOP #JavaDeveloper #CleanCode
To view or add a comment, sign in
-
🚀 Java Series – Day 18 📌 Serialization in Java (Why Serializable is a Marker Interface?) 🔹 What is it? Serialization is the process of converting a Java object into a byte stream so it can be stored in a file or transferred over a network. The reverse process is called Deserialization. Java uses the Serializable interface to enable serialization. 🔹 Why do we use it? Serialization is useful when we want to save object state or send objects across systems. For example: In a banking or login system, user session data can be serialized and stored, then later restored when needed. 🔹 Why is Serializable a Marker Interface? A marker interface is an empty interface (no methods) that signals the JVM to perform special behavior. "Serializable" does not contain any methods. It simply tells the JVM: 👉 “This object is allowed to be converted into a byte stream.” If a class does not implement "Serializable", Java will throw a NotSerializableException. 🔹 Example: import java.io.*; class Student implements Serializable { int id; String name; Student(int id, String name) { this.id = id; this.name = name; } } public class Main { public static void main(String[] args) throws Exception { Student s = new Student(1, "Raushan"); // Serialization ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.txt")); out.writeObject(s); out.close(); System.out.println("Object Serialized"); } } 💡 Key Takeaway: "Serializable" is a marker interface that enables object serialization without defining any methods. What do you think about this? 👇 #Java #Serialization #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Java Series – Day 19 📌 Multithreading in Java (Thread vs Runnable) 🔹 What is it? Multithreading is a process of executing multiple threads simultaneously to perform tasks efficiently. A thread is a lightweight unit of execution within a program. Java provides two main ways to create threads: • Extending the Thread class • Implementing the Runnable interface 🔹 Why do we use it? Multithreading helps improve performance and responsiveness. For example: In a web application, one thread can handle user requests while another processes background tasks like data saving or logging. 🔹 Thread vs Runnable: • Thread Class - Extend "Thread" - Less flexible (Java doesn’t support multiple inheritance) • Runnable Interface - Implement "Runnable" - More flexible (can extend another class) - Preferred approach in real-world applications 🔹 Example: // Using Thread class MyThread extends Thread { public void run() { System.out.println("Thread using Thread class"); } } // Using Runnable class MyRunnable implements Runnable { public void run() { System.out.println("Thread using Runnable"); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); Thread t2 = new Thread(new MyRunnable()); t2.start(); } } 💡 Key Takeaway: Use Runnable for better flexibility and scalability in multithreaded applications. What do you think about this? 👇 #Java #Multithreading #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Java 8 – One of the Most Important Releases in Java History Java 8 introduced powerful features that completely changed how developers write Java code. It brought functional programming concepts, cleaner syntax, and more efficient data processing. Here are some of the most important features every Java developer should know 👇 🔹 1. Lambda Expressions Lambda expressions allow writing concise and readable code for functional interfaces. Example: List<String> names = Arrays.asList("Ali", "Sara", "John"); names.forEach(name -> System.out.println(name)); Instead of writing a full anonymous class, we can use a short lambda expression. 🔹 2. Functional Interfaces An interface with only one abstract method is called a functional interface. Example: @FunctionalInterface interface Calculator { int add(int a, int b); } Lambda expressions work with functional interfaces. 🔹 3. Stream API Stream API allows developers to process collections in a functional style. Example: List<Integer> numbers = Arrays.asList(1,2,3,4,5,6); numbers.stream() .filter(n -> n % 2 == 0) .forEach(System.out::println); Benefits: ✔ Less boilerplate code ✔ Better readability ✔ Easy parallel processing 🔹 4. Method References Method references make lambda expressions even shorter and cleaner. Example: names.forEach(System.out::println); Instead of: names.forEach(name -> System.out.println(name)); 🔹 5. Optional Class "Optional" helps avoid NullPointerException. Example: Optional<String> name = Optional.ofNullable(null); System.out.println(name.orElse("Default Name")); 💡 Why Java 8 is still widely used ✔ Introduced functional programming in Java ✔ Improved code readability ✔ Simplified collection processing ✔ Reduced boilerplate code Java 8 fundamentally changed the way modern Java applications are written. #Java #Java8 #Programming #SoftwareDevelopment #JavaDeveloper #Coding
To view or add a comment, sign in
-
-
🚀 Mastering Core Java | Day 10 📘 Topic: Exception Handling Today’s session focused on Exception Handling, a critical concept in Java that helps manage runtime errors gracefully and ensures smooth program execution. 🔑 What is an Exception? An unexpected event that disrupts normal program flow Occurs during execution (e.g., invalid input, missing files, divide by zero) If not handled, it can cause program termination 🧠 Why Exception Handling is Important? Prevents application crashes Improves program reliability and stability Separates error-handling logic from core business logic Makes debugging and maintenance easier 🧩 Key Keywords in Exception Handling: try – Contains risky code catch – Handles the exception finally – Executes whether an exception occurs or not throw / throws – Used to explicitly pass exceptions Simple Syntax & Example: try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Execution completed"); } 📌 Types of Exceptions: Compile‑Time (Checked) – Detected at compile time Examples: IOException, SQLException Run‑Time (Unchecked) – Occur during execution Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException 💡 Key Takeaway: Exception Handling allows applications to handle errors gracefully, improving user experience and making systems more robust. Grateful to my mentor Vaibhav Barde sir for the clear explanations and real‑world examples, which made this concept easy to understand and apply. 📈 Continuing to strengthen my Core Java and OOP fundamentals step by step. #ExceptionHandling #CoreJava #JavaLearning #Day10 #OOPConcepts #SoftwareDevelopment #LearningJourney #ProfessionalGrowth
To view or add a comment, sign in
-
-
☕ JSON.simple in Java – Escaping Special Characters When working with JSON strings in Java, certain characters are considered reserved characters and cannot be used directly. These characters must be escaped properly to ensure the JSON format remains valid. java explanations (28) As shown on Page 1, JSON uses escape sequences to represent these special characters inside strings. 🔹 Reserved Characters in JSON The document lists the following characters and their escape sequences: Backspace → \b Form Feed → \f New Line → \n Carriage Return → \r Tab → \t Double Quote → \" Backslash → \\ These escape sequences allow JSON strings to safely include special characters. 🔹 Escaping Special Characters Using JSON.simple The library provides the JSONObject.escape() method to automatically escape reserved characters in a string. Example program shown on Page 2: import org.json.simple.JSONObject; public class JsonDemo { public static void main(String[] args) { JSONObject jsonObject = new JSONObject(); String text = "Text with special character /\"'\b\f\t\r\n."; System.out.println(text); System.out.println("After escaping."); text = jsonObject.escape(text); System.out.println(text); } } This program demonstrates how special characters are converted into their escaped versions. 🔹 Program Output As shown on Page 5, the output displays the original string and the escaped string. Original text: Text with special character /"' . After escaping: Text with special character \/\"'\b\f\t\r\n. This ensures the string becomes valid JSON-compatible text. 💡 Escaping special characters is essential when generating JSON data dynamically in Java applications, APIs, or microservices to prevent parsing errors and maintain data integrity. #Java #JSON #JSONSimple #JavaProgramming #BackendDevelopment #API #SoftwareDevelopment #AshokIT
To view or add a comment, sign in
-
Confused to learn java? A Simple step by step guide to learn everything about java & become an expert. This roadmap will guide you through the most essential topics in Java, helping you build a solid understanding. |── Java Basics | ├── Variables (int, float, double, char, boolean, String) | ├── Data types (Primitive, Non-primitive) | ├── Operators (Arithmetic, Logical, Relational, Bitwise) | ├── Conditionals (if, else, else if, switch) | ├── Loops (for, while, do-while, for-each) | ├── Methods (static and non-static) | └── Arrays and Collections | |── 𝐎𝐛𝐣𝐞𝐜𝐭-𝐎𝐫𝐢𝐞𝐧𝐭𝐞𝐝 𝐏𝐫𝐨𝐠𝐫𝐚𝐦𝐦𝐢𝐧𝐠 (𝐎𝐎𝐏) | ├── Classes and Objects | ├── Encapsulation (getters and setters) | ├── Inheritance | ├── Polymorphism (method overloading and overriding) | ├── Abstraction (abstract classes and interfaces) | └── Access Modifiers (private, protected, public) | |── Exeption Handling | ├── Try-Catch Blocks | ├── Finally Block | ├── Throws and Throw | └── Custom Exceptions | |── File Handling | ├── Reading and Writing Files | ├── BufferedReader and BufferedWriter | └── Serialization and Deserialization | |── Java Collection Framework | ├── List (ArrayList, LinkedList) | ├── Set (HashSet, TreeSet) | ├── Map (HashMap, TreeMap) | ├── Queue and Deque | └── Iterators | |── MultiThreading | ├── Threads and Runnable Interface | ├── Synchronized Methods | ├── Locks | └── Executors | |── Java 8+ Features | ├── Lambda Expressions (simpler code) | ├── Streams (data processing) | ├── Functional Interfaces (Predicate, Consumer, Supplier) | ├── Default and Static Methods in Interfaces | ├── Optional Class (handling null) | └── Method References | |── 𝐅𝐫𝐚𝐦𝐞𝐰𝐨𝐫𝐤𝐬 𝐚𝐧𝐝 𝐋𝐢𝐛𝐫𝐚𝐫𝐢𝐞𝐬 | ├── Spring Framework | ├── Hibernate (ORM) | ├── Apache Maven and Gradle | └── JavaFX (GUI) | |── Debugging | ├── System.out.println() | ├── Debugging in IDEs (breakpoints, stepping through code) | └── Loggers (Log4j, SLF4J) | |── Others | ├── JVM, JRE, and JDK | ├── Garbage Collection | ├── Inner Classes (static and non-static) | ├── Anonymous Classes | ├── Recursion | ├── Java Memory Model | └── Annotations | |── Advanced Topics | ├── Generics | ├── Reflection API | ├── Networking (Sockets, HTTP, and HTTPS) | ├── Regular Expressions | └── Dependency Injection More Learning Material: 1. Java Full Stack Roadmap: https://lnkd.in/efwYvfHN 2. Java Important Interview Questions: https://lnkd.in/d3a5aN9J 3. Java Interview Questions for Experienced : https://lnkd.in/ddTXn37m 4. Spring Boot Roadmap: https://lnkd.in/dk6XiWJm 5. Spring Boot Interview Questions: https://lnkd.in/eWBYWMQQ If you interested to master frontend technologies, Get the guide here: https://lnkd.in/dauSXK5R Keep coding, keep building!
To view or add a comment, sign in
More from this author
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