📘 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
Java Collections Framework: Collections & Arrays Classes
More Relevant Posts
-
Day 6 – TreeSet in Java Collections | Sorted Set | Custom Sorting (Backend Developer Learning Series) Today I revised TreeSet, one of the important implementations of the Set interface in Java Collection Framework. TreeSet is very useful when we need unique elements along with automatic sorting. 📌 What is TreeSet? TreeSet is a class that implements the NavigableSet interface, which extends SortedSet. It is available in the java.util package. TreeSet was introduced in JDK 1.2 as part of the Collection Framework. ⚙ Underlying Data Structure TreeSet internally uses a Red-Black Tree. Because of this, elements are stored in sorted order. Sorting happens using: Natural sorting (Comparable) Custom sorting (Comparator) ✨ Characteristics of TreeSet ✔ Duplicate values are NOT allowed ✔ Elements are stored in sorted order ✔ Insertion order is NOT maintained ✔ Null values are NOT allowed ✔ Heterogeneous objects are not allowed ✔ It is not index based 📊 Example Program – TreeSet with Integer import java.util.*; public class TreeSetExample { public static void main(String[] args) { TreeSet<Integer> t = new TreeSet<>(); t.add(10); t.add(50); t.add(9); t.add(12); t.add(45); t.add(55); t.add(1); System.out.println(t); } } TreeSet with Custom Object If we want to store custom objects in TreeSet, the object must implement: Comparable interface or use Comparator Example fields: ticketNo price source destination **Sorting can be done based on price, ticket number, or destination. Practice Java Programs (Based on TreeSet) 1️⃣ Add integer objects to TreeSet and display sorted output. 2️⃣ Write a program to store String values in TreeSet and display them in sorted order. 3️⃣ Write a program to store Integer values in TreeSet in descending order. 4️⃣ Write a program to remove duplicates using TreeSet. 5️⃣ Create a Ticket class and store objects in TreeSet sorted by price. 6️⃣ Write a program to check if an element exists in TreeSet using contain(); 7️⃣ Write a program to display first and last element of TreeSet. 8️⃣ Write a program to remove the highest element from TreeSet. Method: pollLast() 9️⃣ Write a program to store custom objects in TreeSet using Comparator. 🔟 Write a program to convert ArrayList → TreeSet to remove duplicates and sort data. #Java #BackendDeveloper #JavaCollections #TreeSet #Set #SpringBoot #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
Day 7 – Queue, Deque & PriorityQueue in Java Collections (Backend Developer Learning Series) Today I revised Queue, Deque, and PriorityQueue from the Java Collection Framework — important data structures used in task scheduling, message queues, and backend processing systems. 📌 What is Queue? Queue is a sub-interface of Collection defined in the java.util package. Queue follows the FIFO principle (First In First Out). ➡ Elements are inserted from the rear (tail) ➡ Elements are removed from the front (head) Example: Insert → 10 20 30 40 Remove → 10 (first inserted element) ⚙ Queue Implementations Some commonly used Queue classes: ✔ LinkedList ✔ PriorityQueue ✔ ArrayDeque 📌 Important Queue Methods 1️⃣ offer() q.offer(40); Adds an element to the rear of the queue. 2️⃣ poll() q.poll(); Removes and returns the head element. 3️⃣ peek() q.peek(); Returns the head element without removing it. 📌 What is Deque? Deque stands for Double Ended Queue. It allows insertion and deletion from both ends. ✔ Insert from front and rear ✔ Remove from front and rear Deque is defined in java.util package. ⚙ Deque Implementations ✔ ArrayDeque ✔ LinkedList 📌 Important Deque Methods Insert Methods offerFirst() offerLast() addFirst() addLast() Remove Methods pollFirst() pollLast() removeFirst() removeLast() Access Methods peekFirst() peekLast() getFirst() getLast() 📌 ArrayDeque ArrayDeque is a class that implements the Deque interface. Key Points ✔ Introduced in JDK 1.6 ✔ Uses resizable array internally ✔ Faster than Stack in many cases ✔ Default capacity = 16 📌 PriorityQueue PriorityQueue is another implementation of the Queue interface. Unlike normal queues, elements are ordered based on priority instead of insertion order. ✔ Default sorting → Natural order (Ascending) ✔ Uses Heap data structure internally ✔ Does NOT allow null values 💻 Example Program – PriorityQueue import java.util.*; public class PriorityQueueExample { public static void main(String[] args) { PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.offer(30); pq.offer(10); pq.offer(50); pq.offer(20); System.out.println(pq); while(!pq.isEmpty()) { System.out.println(pq.poll()); } } } Output 10 20 30 50 Elements are removed in priority order (ascending) PriorityQueue is used in: ✔ Task priority scheduling ✔ Load balancing ✔ Path finding algorithms ✔ CPU scheduling 🧠 Key Learning Queue → FIFO data processing Deque → Flexible queue with operations from both ends PriorityQueue → Processes elements based on priority Understanding these structures helps build efficient backend processing systems. #Java #BackendDeveloper #JavaCollections #Queue #Deque #PriorityQueue #SpringBoot #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Java Collections Deep Dive: Mastering the ArrayList ✔️ If you are working with data in Java, the ArrayList is likely your most-used tool. But knowing the methods is only half the battle—you also need to know how to handle them safely! 📦 1. Essential ArrayList Methods ✔️ The ArrayList is a dynamic array that provides a massive range of built-in functionality: 🔸 add(element): Add a single element. 🔸 get(index): Retrieves the element at a specific position. 🔸set(index, element): Replaces the element at a specific index. 🔸 remove(index/object): Deletes a specific element or an element at a certain index. 🔸 contains(element): Checks if a single element exists in the list. 🔸 containsAll(collection): Checks if the list contains a group of elements. 🔸 indexOf(element): Finds the first occurrence of an item. 🔸 lastIndexOf(element): Finds the last occurrence of an item. 🔸 size(): Returns the number of elements. 🔸 addAll(collection): Merges another collection into your list. 🔸 clear(): Wipes the entire list clean. 🔸 isEmpty(): A quick boolean check to see if the list is empty. 🛡️ 2. The Role of Generics <T> ✔️ Before Generics, lists could hold any object, which often led to runtime crashes. ✔️By using Generics, we enforce Type Safety. ✔️ Example: ArrayList<String> ensures that only Strings can be added. The compiler checks this for you, so you don't have to worry about ClassCastException later. ⚠️ 3. The ConcurrentModificationException Trap ➡️ Have you ever tried to remove an element while looping through a list using a for-each loop? ❌ CRASH! You’ll get a ConcurrentModificationException. This happens because Java doesn't allow the list's structure to change while it is being traversed by a standard loop. 🔄 4. The Solution: Using an Iterator ✔️ To overcome the crash above, we use an Iterator. It is an object that allows us to traverse the list and modify it safely. 🔹 hasNext(): Checks if there is a next element. 🔹 next(): Returns the next element. 🔹remove(): Safely removes the current element from the list. 💻 The "Interview Special" ➡️ import java.util.*; public class ArrayListMastery { public static void main(String[] args) { ArrayList<String> skills = new ArrayList<>(); skills.add("Java"); skills.add("Spring Boot"); skills.add("Microservices"); skills.add("Java"); System.out.println("Get Index 1: " + skills.get(1)); System.out.println("Contains Java? " + skills.contains("Java")); System.out.println("Last Index: " + skills.lastIndexOf("Java")); //The Interview "Trick": Safe Removal using Iterator // Overcomes ConcurrentModificationException Iterator<String> it = skills.iterator(); while (it.hasNext()) { if (it.next().equals("Java")) { it.remove(); } } System.out.println("Final List: " + skills); } } #Java #CodingInterview #SoftwareEngineering #JavaCollections
To view or add a comment, sign in
-
🚀 Day 31 | Core Java Learning Journey 📌 Topic: HashMap & Map Implementations (Internal Working + Concepts) Today, I deep-dived into how HashMap actually works internally along with LinkedHashMap, TreeMap, and Hashtable. This helped me understand not just usage, but the logic behind performance. 🔹 What is HashMap? ✔ HashMap is a class that implements Map interface ✔ Stores data in key-value pairs ✔ Allows one null key and multiple null values ✔ Not synchronized (not thread-safe) 🔹 Internal Working of HashMap ✔ Default initial capacity = 16 (bucket size) ✔ Data is stored in buckets (array of nodes) ✔ Each key’s hashCode() is used to find bucket index ✔ Formula: index = hash(key) & (n - 1) ✔ If two keys have same bucket index → Collision occurs 👉 Collision Handling: • Uses Linked List (before Java 8) • Uses Linked List + Balanced Tree (after Java 8) • If bucket size > 8 → converts into Red-Black Tree • If reduced → converts back to Linked List ✔ Load Factor = 0.75 (default) ✔ When threshold exceeds → resizing (rehashing) happens 🔹 Important Concepts ✔ Bucket → Each index of internal array ✔ Hashing → Converting key into integer hash ✔ Collision → Multiple keys at same index ✔ Rehashing → Increasing size & redistributing data 🔹 LinkedHashMap ✔ Extends HashMap ✔ Maintains insertion order ✔ Uses doubly linked list internally ✔ Slightly slower than HashMap 🔹 TreeMap ✔ Implements NavigableMap ✔ Stores keys in sorted order (natural/custom comparator) ✔ Uses Red-Black Tree internally ✔ Does NOT allow null key 🔹 Hashtable ✔ Legacy class (introduced before collections framework) ✔ Thread-safe (synchronized) ✔ Does NOT allow null key or value ✔ Slower due to synchronization 🔹 Key Differences ✔ HashMap → Fastest, no ordering ✔ LinkedHashMap → Maintains insertion order ✔ TreeMap → Sorted data ✔ Hashtable → Thread-safe but slower 📌 When to Use What? ✅ Use HashMap → Best performance, general use ✅ Use LinkedHashMap → Order matters ✅ Use TreeMap → Sorted output required ✅ Use Hashtable → Thread-safe (but prefer ConcurrentHashMap in modern Java) 💡 Key Takeaway: Understanding internal working of HashMap (buckets, hashing, collisions, rehashing) helps write optimized and scalable code instead of just using it blindly. Special thanks to Vaibhav Barde Sir for the guidance! #CoreJava #JavaLearning #JavaDeveloper #HashMap #LinkedHashMap #TreeMap #Hashtable #JavaCollections #Programming #LearningJourney
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 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
-
-
🚀 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
-
-
🚀 Mastering Dynamic Arrays in Java with ArrayList Today, I worked on an interesting problem that highlights the power of dynamic data structures in Java — specifically using ArrayList. 💡 Problem Insight: We are given multiple lines of input where each line can have a different number of integers. Then, we need to answer queries to fetch specific elements based on position. 👉 Sounds simple? The twist is: Each row has variable length Some queries may be invalid We must handle errors gracefully 🔧 Key Learning Points: ✅ Using ArrayList of ArrayLists to handle dynamic 2D data ✅ Understanding 0-based vs 1-based indexing ✅ Writing clean exception handling for invalid queries ✅ Avoiding fixed-size arrays when data is unpredictable 📌 Core Concept: ArrayList<ArrayList<Integer>> list = new ArrayList<>(); This allows each row to grow independently — something traditional arrays cannot handle efficiently. ⚠️ Important Tip: Instead of checking bounds manually every time, using try-catch simplifies error handling: public class Solution1 { public static void main(String[] args) { Scanner sn = new Scanner(System.in); int n = sn.nextInt(); // number of lines // ArrayList of ArrayLists ArrayList<ArrayList<Integer>> list = new ArrayList<>(); // Input lines for (int i = 0; i < n; i++) { int d = sn.nextInt(); // number of elements in this line ArrayList<Integer> row = new ArrayList<>(); for (int j = 0; j < d; j++) { row.add(sn.nextInt()); } list.add(row); } // Queries int q = sn.nextInt(); for (int i = 0; i < q; i++) { int x = sn.nextInt(); // line number int y = sn.nextInt(); // position try { // x-1 and y-1 because indexing starts from 0 System.out.println(list.get(x - 1).get(y - 1)); } catch (Exception e) { System.out.println("ERROR!"); }} sn.close();} } 🎯 Why this matters? Problems like these are commonly asked in: Coding interviews Competitive programming Real-world applications dealing with dynamic datasets 💬 As a Java trainer, I always emphasize: Choosing the right data structure simplifies half the problem. #Java #ArrayList #DataStructures #CodingInterview #JavaProgramming #Learning #Developers #ProgrammingTips
To view or add a comment, sign in
-
What actually happens when we use Runnable vs Thread. While studying Java Multithreading, I explored how the Runnable interface works and some interesting cases. Let me Breakdown to you, I. Creating a Thread using Runnable Instead of extending the Thread class, we can implement the Runnable interface. Steps: 1. Create a class that implements Runnable 2. Override the run() method 3. Pass the Runnable object to a Thread 4. Call start() Example: class MyRunnable implements Runnable { public void run() { System.out.println("Child Thread"); } } class ThreadDemo { public static void main(String[] args) { MyRunnable r = new MyRunnable(); Thread t = new Thread(r); t.start(); } } Once start() is called, a new thread is created and the run() method executes. But things become interesting when explore different cases. Case 1: t.start() A new thread is created. The run() method executes in that new thread while the main thread continues running. Case 2: t.run() No new thread is created. run() behaves like a normal method call, and everything runs in the main thread. Case 3: r.run() Again, no thread is created. This simply executes the method like a normal function. Case 4: r.start() This causes a compile-time error. Why? Because the Runnable interface does not contain the start() method. Only the Thread class has it. Why Runnable is Preferred? Java supports single inheritance. If we extend the Thread class, our class cannot extend any other class. But when we implement Runnable: • We still get multithreading • We can extend another class • The design becomes more flexible That’s why the Runnable approach is recommended in real-world applications. II. Thread Names in Java Every thread has a default name like: main Thread-0 Thread-1 We can get or change the name using: • getName() • setName() Example: Thread.currentThread().getName(); Thread.currentThread().setName("MyMainThread"); III. Getting the Current Thread To know which thread is currently executing: Thread.currentThread() This is very useful while debugging multithreaded programs. #Day5 #Java #Multithreading #BackendDevelopment #SystemDesign #SoftwareEngineering
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
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