📘 Java Learning – Collections Framework (Part 9: Queue, PriorityQueue, NavigableSet & NavigableMap) 🚦🚀 Continuing my Java Collections series, today I explored collections used for ordering, prioritizing, and navigation of data. 🔰 Queue (I) • Child interface of Collection • Used to hold objects prior to processing • Generally follows FIFO (First In First Out) • From Java 1.5, LinkedList implements Queue • LinkedList-based Queue always follows FIFO 📌 Important Queue Methods • offer() → add element • peek() → returns head (null if empty) • element() → returns head (Exception if empty) • poll() → remove & return head (null if empty) • remove() → remove & return head (Exception if empty) 🧪 Example Queue q = new LinkedList(); q.offer(10); q.offer(20); System.out.println(q.poll()); // 10 🔰 PriorityQueue (C) • Used to process objects based on priority • Priority can be: • Default natural sorting • Custom sorting (Comparator) • Duplicate objects ✅ • Insertion order ❌ • Null insertion ❌ 📌 Sorting Rules • Natural order → objects must be homogeneous & Comparable • Comparator → no such restriction 📌 Constructors PriorityQueue q1 = new PriorityQueue(); PriorityQueue q2 = new PriorityQueue(int capacity); PriorityQueue q3 = new PriorityQueue(int capacity, Comparator c); PriorityQueue q4 = new PriorityQueue(Collection c); PriorityQueue q5 = new PriorityQueue(SortedSet s); 🧪 Example Queue pq = new PriorityQueue(); pq.offer(20); pq.offer(10); pq.offer(30); System.out.println(pq); // Order NOT guaranteed 🔰 NavigableSet (I) • Child interface of SortedSet • Provides navigation support for TreeSet 📌 Important Methods • ceiling(e) → ≥ e • higher(e) → > e • floor(e) → ≤ e • lower(e) → < e • pollFirst(), pollLast() • descendingSet() 🧪 Example NavigableSet ns = new TreeSet(); ns.add(10); ns.add(20); ns.add(30); System.out.println(ns.ceiling(15)); // 20 🔰 NavigableMap (I) • Child interface of SortedMap • Provides navigation methods for TreeMap 📌 Important Methods • ceilingKey() • higherKey() • floorKey() • lowerKey() • pollFirstEntry() • pollLastEntry() • descendingMap() 🧪 Example NavigableMap nm = new TreeMap(); nm.put(1, "Java"); nm.put(3, "Spring"); nm.put(2, "Boot"); System.out.println(nm.floorKey(2)); // 2 ⭐ Key Takeaways • Queue → FIFO processing • PriorityQueue → priority-based processing • NavigableSet → navigation on sorted sets • NavigableMap → navigation on sorted maps Understanding these collections helps in efficient data processing and retrieval 💡 Building strong Java fundamentals, one collection at a time ☕💻 #Java #CoreJava #CollectionsFramework #Queue #PriorityQueue #NavigableSet #NavigableMap #JavaCollections #LearningJourney
Java Collections Framework: Queue, PriorityQueue, NavigableSet & NavigableMap
More Relevant Posts
-
📘 Java Learning – Collections Framework (Final Part: Collections Class & Arrays Class) 🚀🎯 Wrapping up my Java Collections journey with two powerful utility classes from java.util package: 👉 Collections class 👉 Arrays class These classes provide utility methods for sorting, searching, reversing, and converting data structures efficiently. 🔰 Collections Class A utility class that provides methods for Collection implemented classes. 📌 Sorting a List Collections.sort(List l); // Natural sorting Collections.sort(List l, Comparator c); // Custom sorting ✔ Elements must be homogeneous & Comparable (for natural sorting) ✔ Null elements not allowed (NullPointerException) 📌 Searching in a List Collections.binarySearch(List l, Object obj); Collections.binarySearch(List l, Object key, Comparator c); ⚠ Important Rules: • List must be sorted before searching • Uses Binary Search algorithm • Successful search → returns index • Unsuccessful search → returns insertion point • Must use same Comparator used for sorting 📌 Reversing a List Collections.reverse(List l); // Reverses list Collections.reverseOrder(); // Returns Comparator (descending) ✔ reverse() → works on List ✔ reverseOrder() → returns Comparator 🔰 Arrays Class Utility class for array operations (primitive & object arrays). 📌 Sorting Arrays Arrays.sort(int[] arr); // Primitive (natural order) Arrays.sort(Object[] arr); // Natural order Arrays.sort(Object[] arr, Comparator c); // Custom sorting ✔ Primitive arrays → only natural sorting ✔ Object arrays → natural or custom sorting 📌 Searching in Arrays Arrays.binarySearch(int[] arr, key); Arrays.binarySearch(Object[] arr, key); Arrays.binarySearch(Object[] arr, key, Comparator c); ✔ Same rules as Collections.binarySearch() 🔰 Converting Array to List List list = Arrays.asList(Object[] arr); ⚠ Important: • Creates a List view, not independent list • Changes in list reflect in array & vice versa • Cannot change size (add/remove → UnsupportedOperationException) • Replacement allowed but type must match (else ArrayStoreException) 🧪 Combined Example Integer[] arr = {30, 10, 20}; Arrays.sort(arr); // Sorting array System.out.println(Arrays.toString(arr)); // [10, 20, 30] int index = Arrays.binarySearch(arr, 20); System.out.println(index); // 1 List list = Arrays.asList(arr); Collections.reverse(list); System.out.println(list); // [30, 20, 10] ⭐ Final Takeaways • Collections → Utility methods for List • Arrays → Utility methods for Arrays • Always sort before binarySearch • asList() creates a fixed-size list view This completes my Java Collections Framework journey 🎯 Understanding these utilities makes data handling more efficient and interview-ready 💡 Building strong Java fundamentals, one collection at a time ☕💻 #Java #CoreJava #CollectionsFramework #CollectionsClass #ArraysClass #JavaCollections #LearningJourney
To view or add a comment, sign in
-
📘 Java Learning – Multithreading (Part 3: Runnable Interface, Thread Names & Priorities) 🚀🎯 Continuing my learning journey into Java Multithreading. In this post, I explored how to define threads using the Runnable interface, along with concepts like thread names and priorities. 🔰 Defining a Thread using Runnable Interface A thread can also be defined by implementing the Runnable interface, which is present in the java.lang package and contains only one method: • run() 📌 Two Approaches to Define a Thread 1️⃣ Extending Thread class 2️⃣ Implementing Runnable interface 📌 Example – Runnable Implementation class MyRunnable implements Runnable { public void run() { System.out.println("Child Thread"); } public static void main(String[] args) { MyRunnable r = new MyRunnable(); Thread t = new Thread(r); t.start(); System.out.println("Main Thread"); } } ✔ Output may appear in mixed order because execution depends on the Thread Scheduler. 🔰 Best Approach to Define a Thread Between the two approaches, implementing Runnable is recommended. Reason: • If a class extends Thread, it cannot extend any other class • If a class implements Runnable, it can still extend another class ✔ This provides better flexibility in design. 🔰 Common Thread Constructors Some commonly used constructors of the Thread class: Thread() Thread(Runnable r) Thread(String name) Thread(Runnable r, String name) Thread(ThreadGroup g, String name) Thread(ThreadGroup g, Runnable r) Thread(ThreadGroup g, Runnable r, String name) Thread(ThreadGroup g, Runnable r, String name, long stackSize) 🔰 Getting and Setting Thread Name Every thread in Java has a name (default or programmer-defined). Methods used: • getName() • setName(String name) Example: System.out.println(Thread.currentThread().getName()); // main Thread.currentThread().setName("first thread"); System.out.println(Thread.currentThread().getName()); To get the current executing thread reference: Thread.currentThread() 🔰 Thread Priority Every thread has a priority ranging from 1 (lowest) to 10 (highest). Standard constants: • Thread.MIN_PRIORITY • Thread.NORM_PRIORITY • Thread.MAX_PRIORITY If two threads have the same priority, the execution order depends on the Thread Scheduler. 🔰 Default Priority • Default priority of main thread → 5 • Child threads inherit priority from the parent thread Methods used: • getPriority() • setPriority(int p) Example: t.setPriority(5); t.setPriority(10); t.setPriority(100); // IllegalArgumentException ⭐ Key Takeaways • Threads can be created using the Runnable interface • Implementing Runnable offers better design flexibility • Every thread has a name and priority • Priority range: 1 to 10 Learning multithreading step by step while strengthening Java fundamentals ☕💻 #Java #CoreJava #Multithreading #JavaDeveloper #Concurrency #LearningJourney
To view or add a comment, sign in
-
Day 6-7 of Learning Java : Today I started my journey into Java programming which is taught by Aditya Tandon Sir. Here are the key concepts I learned today: Conditional Statements In Java:- Java uses conditional statements to decide which block of code should execute based on condition is true or false. Types:- • If statement • If else statement • Else If ladder • Switch statement • The Ternary Operator ∆ If statement:-The most basic control flow statement. It executes a block of code only if the given condition is true. Example:- if (age >= 18) { System.out.println("You are eligible to vote."); } ∆ If else statement:-It executes a block of code, when if condition is false, the else block runs. Example:- if (score >= 50) { System.out.println("Pass"); } else { System.out.println("Fail"); } ∆ Else If ladder:-When you have multiple conditions to check, you use a ladder. Java tests them from top to bottom and executes the first one that is true. Example:- int score = 85; if (score >= 90) { System.out.println("Grade: A"); } else if (score >= 80) { System.out.println("Grade: B"); } else { System.out.println("Grade: F (Fail)"); } ∆ The switch Statement:-Instead of a long chain of else if statements, a switch is comparing a single variable against a list of constant values. Example:- int day = 3; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Invalid day"); } ∆ The Ternary Operator (? :):-This is a shorthand of the if-else statement. It is the only operator in Java that takes three operands. Syntax: variable = (condition) ? value_if_true : value_if_false; This is just the beginning. Excited to continue this journey Special thanks to Rohit Negi bhaiya & Aditya Tandon Sir. #Day6 #Java #Coding #Learning #Consistency
To view or add a comment, sign in
-
-
🚀 Day 33 | Core Java Learning Journey 📌 Topic: File Handling in Java Today, I explored File Handling in Java — how applications store and retrieve data from files. This is a very important concept for building real-world applications where data persistence is required. 🔹 What is File Handling? ✔ File Handling is used to store data permanently in files ✔ It allows Java applications to read, write, and modify files ✔ Available through the java.io package 🔹 Why We Use File Handling? ✔ To store data permanently (even after program ends) ✔ To read existing data from files ✔ To build data-driven applications ✔ Used in logging, reports, configs, etc. 🔹 Important Classes in java.io.* ✔ File → Represents file or directory ✔ FileWriter → Writes data to file (character stream) ✔ FileReader → Reads data from file ✔ BufferedWriter → Efficient writing (faster) ✔ BufferedReader → Efficient reading (line by line) ✔ FileInputStream → Reads binary data ✔ FileOutputStream → Writes binary data ✔ InputStreamReader → Converts byte stream → character stream 🔹 Steps to Work with Files ✔ Step 1: Import package • import java.io.*; ✔ Step 2: Create File Object • File file = new File("test.txt"); ✔ Step 3: Write Data • FileWriter fw = new FileWriter(file); • fw.write("Hello Students"); ✔ Step 4: Read Data • FileReader fr = new FileReader(file); ✔ Step 5: Close Resources • Always close streams → fw.close(), fr.close() 🔹 Important Methods ✔ createNewFile() → Creates new file ✔ exists() → Checks file existence ✔ delete() → Deletes file ✔ write() → Writes data ✔ read() → Reads single character ✔ readLine() → Reads line (BufferedReader) ✔ flush() → Clears buffer and forces write ✔ close() → Closes stream 🔹 Key Concepts ✔ Buffered Streams → Faster performance ⚡ ✔ Character Streams → FileReader, FileWriter ✔ Byte Streams → FileInputStream, FileOutputStream ✔ Exception Handling → Must handle IOException ✔ Try-with-resources → Recommended (auto close) ✅ 🔹 Example (Best Practice) ✔ Using try-with-resources: • try (FileWriter fw = new FileWriter("test.txt")) { fw.write("Hello Students"); } 🔹 Store & Fetch Data ✔ Store → Using FileWriter / BufferedWriter ✔ Fetch → Using FileReader / BufferedReader ✔ Supports both text and binary data 📌 When to Use File Handling? ✅ When saving user data locally ✅ When working with logs or reports ✅ When database is not required ✅ When handling configuration files 💡 Key Takeaway: File Handling is essential for data persistence in Java. Understanding streams and proper resource management helps build efficient and reliable applications. Special thanks to Vaibhav Barde Sir for the guidance! #CoreJava #JavaLearning #JavaDeveloper #FileHandling #JavaIO #Programming #LearningJourney
To view or add a comment, sign in
-
-
🚀 Day 25 | Core Java Learning Journey 📌 Topic: ArrayList & LinkedList in Java Today I learned about ArrayList and LinkedList, two important classes in the Java Collections Framework that implement the Java List Interface. Both are used to store ordered collections of elements, but they use different internal data structures and have different performance characteristics. 🔹 ArrayList ✔ ArrayList is a dynamic (growable) array implementation of the List interface. ✔ It automatically resizes when elements are added or removed. ✔ It allows duplicate elements and maintains insertion order. ✔ Elements can be accessed quickly using an index. Internal Data Structure: • Uses a resizable array. 📌Key Features: ✔ Fast random access using index (get, set operations) ✔ Allows null values and duplicate elements ✔ Maintains insertion order ✔ Automatically increases capacity when needed Best Use Case: ✔ When frequent data access (reading) is required. Example Implementation: • ArrayList 🔹 LinkedList ✔ LinkedList is another implementation of the List interface. ✔ It stores elements using nodes connected through links. ✔ Each node contains data and references to other nodes. ✔ It also implements Deque, so it can be used as a queue or stack. Internal Data Structure: • Doubly Linked List Each node contains: • Data • Reference to the previous node • Reference to the next node 📌Key Features : ✔ Efficient insertion and deletion of elements ✔ Allows duplicate elements ✔ Maintains insertion order ✔ Can be used as List, Queue, or Deque 🔹Types of Linked Lists (Conceptually): • Singly Linked List – Node points to next node • Doubly Linked List – Node points to both previous and next node • Circular Linked List – Last node connects back to the first node In Java, LinkedList is implemented as a Doubly Linked List. Example Implementation: • LinkedList 📌 Key Differences ✔ ArrayList uses a dynamic array ✔ LinkedList uses a doubly linked list structure ✔ ArrayList provides faster element access ✔ LinkedList provides faster insertion and deletion 📌 Key Takeaways ✔ Both ArrayList and LinkedList implement the List interface ✔ ArrayList is best for fast access and reading data ✔ LinkedList is better for frequent insertions and deletions ✔ Choosing the right data structure improves performance and efficiency Understanding these implementations helps developers select the most suitable data structure when working with collections in Java 💻⚡ Special thanks to Vaibhav Barde Sir for explaining these concepts clearly. #CoreJava #JavaLearning #ArrayList #LinkedList #JavaCollections #JavaDeveloper #Programming #LearningJourney
To view or add a comment, sign in
-
-
📅 Day 38 & 39 – Java Learning Journey | ArrayList (Java Collections Framework) 🚀 In the past two days, I explored ArrayList, one of the most commonly used classes in the Java Collection Framework. Understanding how it works internally helps write efficient and optimized Java programs. 🔹 What is ArrayList? ArrayList is a dynamic array implementation in Java that can automatically grow or shrink in size. Unlike traditional arrays, we don't need to define the size in advance. 🔹 Default Capacity & Internal Resizing When an ArrayList is created: ArrayList<Integer> list = new ArrayList<>(); • Default capacity = 10 • When the array becomes full, Java increases capacity by 50% Formula used internally: newCapacity = oldCapacity + (oldCapacity / 2); Example growth: 10 → 15 → 22 → 33 → 49 → ... Example: import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Mango"); System.out.println(fruits.get(1)); // Access element } } 🔹 Common Operations in ArrayList ✔ Insertion ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Mango"); System.out.println(fruits); Output: [Apple, Banana, Mango] ✔ Accessing Elements System.out.println(fruits.get(1)); Output: Banana ArrayList allows fast access using index. ✔ Updating Elements fruits.set(1, "Orange"); System.out.println(fruits); Output: [Apple, Orange, Mango] ✔ Deleting Elements fruits.remove("Apple"); or fruits.remove(1); Output: [Orange, Mango] ✔ Size of ArrayList System.out.println(fruits.size()); 🔹 Time Complexity of ArrayList Operation TimeComplexity Add element (end)O(1) (Amortized) Access elementO(1) Update elementO(1) Insert element (middle)O(n) Delete elementO(n) Search elementO(n) 💡 Key Takeaways ✔ Dynamic resizing ✔ Maintains insertion order ✔ Allows duplicate values ✔ Null insertion is Possible ✔ Provides fast access with indexes Learning how these internal mechanisms work helps us choose the right data structure while building real-world applications. 🙏 Special thanks to my mentor Suresh Bishnoi from Kodewala Academy for guiding me step by step in my Java Backend Developer journey. #Java #JavaCollections #ArrayList #BackendDevelopment #100DaysOfCode #LearningInPublic #JavaDeveloper
To view or add a comment, sign in
-
-
🚀 Day 23 | Core Java Learning Journey 📌 Topic: Collection Framework in Java Today I learned about the Collection Framework, one of the most important parts of Java used to store and manage groups of objects efficiently. 🔹 What is a Collection? ✔ A Collection is a framework that provides architecture to store and manipulate a group of objects. ✔ It allows developers to store, retrieve, and manage data dynamically. ✔ Collections can grow or shrink in size automatically unlike arrays. (Wikipedia) 🔹 Important Characteristics of Collections ✔ Collections store objects (non-primitive types) ✔ If primitive data is needed, use wrapper classes like Integer, Double, etc. ✔ Collection size is dynamic (not fixed) ✔ It helps manage large amounts of data efficiently 🔹 Java Collection Framework ✔ The Collection Framework is a unified architecture that provides interfaces, classes, and algorithms to work with groups of objects. (Wikipedia) ✔ It provides ready-to-use data structures like List, Set, Queue, and Map. 🔹 Main Interfaces in Collection Framework 1️⃣ List ✔ Ordered collection ✔ Allows duplicate elements ✔ Example: ArrayList, LinkedList, Vector 2️⃣ Set ✔ Does not allow duplicate elements ✔ Unordered collection ✔ Example: HashSet, LinkedHashSet, TreeSet 3️⃣ Queue ✔ Follows FIFO (First In First Out) principle ✔ Example: PriorityQueue, ArrayDeque 4️⃣ Map ✔ Stores data in key-value pairs ✔ Keys are unique ✔ Example: HashMap, LinkedHashMap, TreeMap ⚠ Note: Map is part of the Collection Framework but it does not extend the Collection interface. 🔹 Packages Used in Collection Framework Most collection classes and interfaces are available in: ✔ import java.util.*; This package includes important interfaces like List, Set, Map, Queue and classes like ArrayList, HashMap, HashSet, LinkedList. (JavaTechOnline) 🔹 Difference Between Collection and Collections ✔ Collection • It is an interface • Root interface of the collection hierarchy • Represents a group of objects ✔ Collections • It is a utility class • Contains static methods for operations like sorting, searching, and synchronization Example methods: Collections.sort() Collections.reverse() Collections.shuffle() 📌 Key Takeaways ✔ Collection Framework helps manage groups of objects efficiently ✔ Collection stores only objects (non-primitive types) ✔ Size of collections is dynamic ✔ Main interfaces: List, Set, Queue, Map ✔ Collection is an interface while Collections is a utility class Understanding the Collection Framework is essential for building efficient and scalable Java applications 💻⚡ Special thanks to Vaibhav Barde Sir. #CoreJava #JavaLearning #JavaCollections #CollectionFramework #JavaDeveloper #Programming #LearningJourney
To view or add a comment, sign in
-
-
🚀 Day 129 of My Java Learning Journey 😉 Hello LinkedIn family, Today I practiced a logical program to find all vowels from a list of strings using nested loops in Java 💡 This helped me understand how to work with: List of Strings Converting String to char array Checking characters using indexOf() ------------------------------------------------------------------------------------------- 💻 Code: =======> import java.util.*; public class VowelFind { public static void main(String[] args) { List<String> listOfString = Arrays.asList("aab", "xyz", "iiu"); List<Character> vowels = new ArrayList<>(); for (String str : listOfString) { for (char cha : str.toCharArray()) { if ("aeiou".indexOf(cha) != -1) { vowels.add(cha); } } } System.out.println("vowels :" + vowels); } } ------------------------------------------------------------------------------------------- 🖥 Output: =========> vowels : [a, a, i, i, u] 📖 Output Explanation: Input List: ["aab", "xyz", "iiu"] Step 1️⃣ → Convert each string into characters Step 2️⃣ → Check if character exists in "aeiou" Step 3️⃣ → If yes, add to vowels list From: "aab" → a, a "xyz" → no vowels "iiu" → i, i, u Final list: [a, a, i, i, u] 🔎 Important Concept: ✅ toCharArray() → Converts String into character array ✅ "aeiou".indexOf(cha) → Checks if character exists ✅ != -1 → Means character is found ✅ Nested loops → Loop inside loop 💡 Important Tip: Instead of writing multiple OR conditions like: if(cha=='a' || cha=='e' || cha=='i' ...) Using indexOf() makes code cleaner and more readable. This logic can be used in: ✔ Password validation ✔ Text processing ✔ Data filtering ✔ Interview questions What would you improve in this code? 🤔 Should I convert this into Java 8 Stream version next? 😄 Let’s keep learning 🚀 #Java #JavaLearning #CodingJourney #JavaDeveloper #BackendDeveloper #Streams #ProblemSolving #DevOps #Day129 #codewithyuvi #logicalworld
To view or add a comment, sign in
-
-
📘 Java Learning – Multithreading (Part 1: Multitasking & Thread Creation) 🚀🎯 Starting my learning journey into Java Multithreading, one of the most powerful features of Java used for executing multiple tasks simultaneously. 🔰 Multitasking Executing several tasks simultaneously is called Multitasking. There are two types of multitasking: 👉 Process Based Multitasking 👉 Thread Based Multitasking 1️⃣ Process Based Multitasking Executing several tasks simultaneously where each task is a separate independent process. Example: Running multiple applications at the same time: • Browser • Music Player • Code Editor ✔ Best suited at Operating System level 2️⃣ Thread Based Multitasking (Multithreading) Executing several tasks simultaneously where each task is an independent part of the same program. Each independent path of execution is called a Thread. ✔ Best suited for Programmatic level 🎯 Objective of Multitasking • Improve system performance • Reduce response time 📌 Applications of Multithreading Multithreading is widely used in: • Video games • Multimedia graphics • Animations • High performance applications 🔰 Multithreading Support in Java Java provides rich API support for multithreading through: • Thread • Runnable • ThreadGroup • ThreadLocal ✔ Java provides built-in APIs for multithreading, and programmers use these APIs to create and manage threads. This makes multithreading easier in Java compared to C++. 🔰 Ways to Create a Thread A thread can be defined in two ways: 1️⃣ Extending Thread class 2️⃣ Implementing Runnable interface 📌 Example – Extending Thread Class class MyThread extends Thread { public void run() { for(int i=0;i<5;i++){ System.out.println("Child Thread"); } } } public class ThreadDemo { public static void main(String[] args) { MyThread t = new MyThread(); // instantiation of thread t.start(); // starting of a thread for(int i=0;i<5;i++){ System.out.println("Main Thread"); } } } 📌 start() does NOT directly execute run(). It does: start() ↓ JVM asks Thread Scheduler ↓ New Thread Created ↓ run() executes in new thread ⭐ Key Points • start() method creates a new thread • run() contains the task executed by thread • Multiple threads execute simultaneously More concepts like Thread Scheduler, start() vs run(), Thread Lifecycle in the next post. #Java #CoreJava #Multithreading #JavaDeveloper #Concurrency #LearningJourney
To view or add a comment, sign in
-
🚀 Java Revision Journey – Day 12 Today I revised the BigInteger class in Java, which is used to perform calculations involving very large integer values that exceed the limits of primitive data types such as int and long. 🔖 BigInteger Class: The BigInteger class, available in the java.math package, allows Java programs to work with integers of virtually unlimited size. Unlike primitive data types that have fixed memory limits, BigInteger can handle extremely large numbers and perform precise mathematical operations without overflow. 🔖 Why BigInteger is Needed: Primitive data types like int (32-bit) and long (64-bit) have a maximum range. When computations exceed these limits, overflow occurs and results become incorrect. The BigInteger class overcomes this limitation by providing a way to perform large integer calculations reliably. 🔖 Initialization of BigInteger: There are several ways to create a BigInteger object in Java: • Using the new keyword BigInteger a = new BigInteger("12345"); • Passing a String variable String b = "43215"; BigInteger a = new BigInteger(b); • Using the valueOf() static method BigInteger a = BigInteger.valueOf(34567); 🔖 Common Methods of BigInteger: The BigInteger class provides many built-in methods to perform arithmetic operations and value conversions. • add() – Performs addition • subtract() – Performs subtraction • multiply() – Performs multiplication • divide() – Performs division • remainder() / mod() – Finds remainder • pow() – Calculates power of a number • sqrt() – Computes square root • abs() – Returns absolute value • max() / min() – Finds maximum or minimum value • intValue(), longValue(), doubleValue() – Converts BigInteger to primitive types • toString() – Converts BigInteger to String representation 🔖 Practice Problems Using BigInteger: To better understand the usage of this class, I practiced implementing problems such as: • Factorial of very large numbers • Fibonacci series with large values • Prime number checking with large integers 💻 The BigInteger class is widely used in applications that require precise large-number computations, such as cryptography, financial systems, scientific calculations, and competitive programming. Continuing to strengthen my Java fundamentals step by step. #Java #JavaLearning #JavaDeveloper #OOP #BackendDevelopment #Programming #JavaRevisionJourney
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