🚀 Day 113 | Java Logical Program ++>> Check Whether an Array Is Sorted or Not Hello coders👋, Today I worked on a simple but very important array logic problem in Java. The task is to check whether an array is sorted in ascending order or not. ------------------------------------------------------------------------------------------- 💡 Code -----------> public class ArraySortedOrNot { public static void main(String[] args) { int[] a = {1, 2, 3, 4, 5, 6}; boolean sorted = true; for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { sorted = false; break; } } System.out.println(sorted ? "Sorted Array" : "Not Sorted Array"); } } ------------------------------------------------------------------------------------------- 🖥️ Output --------------> Sorted Array 🔍 Output Explanation The loop compares current element with the next element If any element is greater than the next one → array is not sorted If the loop completes without breaking → array is sorted 📌 Important Concept Array traversal Comparison of adjacent elements Boolean flag usage Early exit using break ⚠️ Important Tip This logic works in O(n) time, which is efficient and recommended for large arrays 🚀 🤔 Engagement How would you check if the array is sorted in descending order? 🤔 👉 CTA If you’re learning Java logic step by step, let’s connect and grow together 🤝💙 #Java #CoreJava #ArrayProgramming #LogicalThinking #JavaDeveloper #CodingJourney #100DaysOfCode #LearnJava #day113 #codewithyuvi
Yuvraj Singh Kushwah’s Post
More Relevant Posts
-
A Marker Interface 👇 A Marker Interface in Java is an interface that contains no methods or fields. It is used to mark a class so that the Java runtime or compiler can identify some special behavior or capability of that class. Example: Here, Serializable has no methods but if a class implements it, Java knows that objects of that class can be serialized. 🔹A Marker Interface (also known as a Tagging Interface) is a design pattern in Java where an interface contains no methods or constants. If you look at the source code of a marker interface, it’s just an empty shell: Java public interface MyMarkerInterface { // Absolutely nothing here } Why use an empty interface? The purpose isn't to define behavior (like a normal interface does), but to deliver a message to the JVM or a framework. It acts like a "stamp" or a "label" on a class. When a class implements a marker interface, it's telling the runtime: "I have a special property. You can treat me differently." 🌟 How It Works (The "Metadata" Approach) Since the interface is empty, the class implementing it doesn't have to write any new code. Instead, other parts of the system use the instanceof operator to check for the "stamp." 🔹The Logic: Class A implements Serializable. ✔ The JVM sees a request to save Class A to a file. ✔ The JVM checks: if (A instanceof Serializable). ✔ If True: The JVM proceeds with the specialized logic to save the data. ✔ If False: The JVM throws a NotSerializableException. Famous Examples in Java 🔹 Serializable: Tells the JVM that the object’s state can be converted into a byte stream (saved to a file or sent over a network). 🔹Cloneable: Tells the Object.clone() method that it is legal to make a field-for-field copy of instances of that class. 🔹Remote: Used in RMI (Remote Method Invocation) to identify interfaces whose methods may be invoked from a non-local virtual machine. I’m truly thankful to my mentor for their valuable guidance Anand Kumar Buddarapu Saketh Kallepu Uppugundla Sairam #Java #CoreJava #MarkerInterface #JavaProgramming #OOP #Serializable #Cloneable #JavaConcepts #Programming #Developers
To view or add a comment, sign in
-
-
🚀 Day 19 – Core Java | Arrays (1D, 2D, 3D) + Length Property Deep Dive Today’s session was not just about writing arrays — it was about understanding how arrays behave internally in memory. 🔑 What We Revised ✔ Arrays are objects in Java ✔ Stored in Heap memory ✔ Hold homogeneous data ✔ Index always starts from 0 📌 1D Array – Execution Clarity int[] a = new int[5]; Default values → 0 Access using a[index] Traversal using loop We reinforced: Why loops are mandatory Why System.out.println(a); prints reference, not elements Why traversal logic never changes in 90% of problems 📌 Important Concept: length Property Instead of hardcoding: for(int i = 0; i < 5; i++) We used: for(int i = 0; i < a.length; i++) Why? Because: If array size changes → code still works Makes program dynamic Prevents logical bugs 📌 2D Array – Internal Understanding int[][] a = new int[2][5]; Meaning: 2 Rows 5 Columns per row Key Insight: a.length → number of rows a[i].length → number of columns in row i Traversal Pattern: for(int i = 0; i < a.length; i++) { for(int j = 0; j < a[i].length; j++) { System.out.print(a[i][j] + " "); } } Exactly like pattern programming logic. 📌 3D Array – Block, Row, Column int[][][] a = new int[2][3][5]; Think in hierarchy: Block → School Row → Classroom Column → Student Length usage: a.length → number of blocks a[i].length → rows in block a[i][j].length → columns in that row 🧠 Major Takeaways ✔ Hardcoding loop limits is a mistake ✔ length property makes code scalable ✔ Traversal logic remains same across dimensions ✔ Interviewers test syntax + clarity Most students understand arrays. Very few understand how length adapts dynamically. That difference matters in interviews. Strong fundamentals → Fewer bugs → Better problem-solving → Better offers 🚀 #Day19 #CoreJava #Arrays #JavaProgramming #LengthProperty #DataStructures #InterviewPreparation #DeveloperGrowth
To view or add a comment, sign in
-
Day 25 of Sharing What I’ve Learned 🚀 Method Overloading in Java — Compile-Time Polymorphism Explained 🔥 When building real-world applications, flexibility in handling different inputs is essential… That’s where method overloading becomes powerful 💡 🔹 What Is Method Overloading? Method overloading is the process of defining multiple methods with the same name within the same class, but with different parameter lists. ✔ Same method name ✔ Different number or type of parameters ✔ Improves readability and usability 🔹 Simple Example — Calculator Add Method class Calculator { void add(int a, int b) { System.out.println(a + b); } void add(float a, float b) { System.out.println(a + b); } void add(int a, int b, int c) { System.out.println(a + b + c); } } Now you can call: calc.add(10, 20); calc.add(10.5f, 20.3f); calc.add(5, 6, 7); Same method name ➜ Different behavior ✔ 🔹 How Java Chooses the Correct Method The Java compiler follows 3 rules: 1️⃣ Method name 2️⃣ Number of parameters 3️⃣ Type of parameters This decision happens at compile time, not runtime. 👉 That’s why method overloading is called: ✔ Compile-time polymorphism ✔ Static binding ✔ Early binding ✔ (Also known as false polymorphism) 🔹 Type Promotion If an exact match isn’t found, Java promotes types to the closest compatible one. Example: void add(float a, float b) { } Calling: add(10, 20); ➡ int values are promoted to float ✔ 🔹 Ambiguity Problem Sometimes the compiler can’t decide which method to call ❌ void add(int a, float b) { } void add(float a, int b) { } add(10, 20); // ❌ ambiguous Both methods are equally valid ➜ Compile-time error 🧠 Key Takeaways ✔ Multiple methods can share the same name (within the same class) ✔ Differentiation is based on parameters, not return type ✔ Resolved at compile time ✔ Supports cleaner and more intuitive APIs ✔ Widely used in real-world Java libraries Method overloading makes code easier to use, easier to read, and more flexible — a fundamental concept for interviews and production code. #Java #CoreJava #MethodOverloading #Polymorphism #OOP #Programming #BackendDevelopment #InterviewPreparation #Day25 Grateful for the guidance from Sharath R, Harshit T, TAP Academy
To view or add a comment, sign in
-
-
🚀 Day 19 – Java Full Stack Journey | Arrays in Depth (1D, 2D, 3D + length Property) Today’s session was a complete deep dive into Arrays in Java — not just creating them, but truly understanding: • Memory behavior • Traversal logic • Why loops are mandatory • How length actually works • Regular vs Jagged arrays 🔹 What is an Array? 👉 Arrays are objects in Java 👉 Stored in the Heap memory 👉 Used to store homogeneous data 👉 Indexed starting from 0 When you print the array reference directly: System.out.println(a); You don’t get elements. You get the address reference — because arrays are objects. To access elements → Traversal using loops is mandatory. 🔹 1️⃣ One-Dimensional Array (1D) int[] a = new int[5]; ✔ Stored in Heap ✔ Default values → 0 ✔ Traversed using single loop Important rule: for(int i = 0; i < a.length; i++) Using a.length makes your code dynamic. Never hardcode size like i < 5. 🔹 2️⃣ Two-Dimensional Array (2D) int[][] a = new int[2][5]; Meaning: 2 rows 5 columns Traversal requires nested loops: for(int i = 0; i < a.length; i++) { for(int j = 0; j < a[i].length; j++) { // Access element } } Important Understanding: a.length → number of rows a[i].length → number of columns in that row This makes the code scalable and flexible. 🔹 3️⃣ Three-Dimensional Array (3D) int[][][] a = new int[2][3][5]; Meaning: 2 blocks 3 rows per block 5 columns per row Traversal requires 3 nested loops: for(int i = 0; i < a.length; i++) { for(int j = 0; j < a[i].length; j++) { for(int k = 0; k < a[i][j].length; k++) { // Access element } } } Understanding flow: Column moves fastest → Then row → Then block That’s how memory gets populated. 🔹 Regular Array vs Jagged Array ✔ Regular Array → All rows have equal number of columns ✔ Looks rectangular Tomorrow’s focus → Jagged Array (Where each row can have different column size) 🔹 Most Important Learning Today Arrays are not about syntax. They are about: • Understanding object behavior • Understanding memory (Heap & Stack) • Writing dynamic loops • Avoiding hardcoded logic • Thinking in dimensions 90% of array problems follow the same pattern: Create → Traverse → Process → Print Once traversal is clear, logic becomes easy. Consistency + Practice + Typing the code yourself = Mastery. Day 19 Complete ✔ #Day19 #Java #CoreJava #Arrays #DataStructures #JVM #FullStackJourney #LearningInPublic #JavaDeveloper #100DaysOfCode TAP Academy
To view or add a comment, sign in
-
-
The "11th Rule" Trap: Why Java’s Map.of() Might Be Misleading You ❌ Have you ever written perfectly logical, declarative code, only to be hit by a strange Compilation Error? You look at your IDE, and it insists on an "Incompatible Types" issue, even though your classes match perfectly. I recently hit a classic, but treacherous problem, using the Map.of() method. 📋 Dispatch Map Pattern I was implementing a "Type-to-Strategy Map" to replace a messy chain of if-else and instanceof blocks. The idea is clean: a map where the key is the Rule class and the value is the mapping function. Ten rules worked flawlessly. But as soon as I added the eleventh, everything broke. 🤯 A Misleading Hint Instead of a clear "Too many arguments" message, the compiler threw a confusing: "Incompatible types: expected... " I spent 15 minutes re-verifying my code, thinking I had made a mistake in the type system. I was convinced the problem was the type of the new rule, while the actual problem was simply the quantity. The compiler's "confused" hint led me down a rabbit hole, when I should have just been counting my arguments. 💡 Why is there a limit of 10? Why can't Map.of() just use varargs like List.of() to accept any number of elements? Varargs can only handle a single type. Type Mixing: In a Map, we have Keys (K) and Values (V). Java's varargs doesn't have a syntax to say "take arguments where every first is K and every second is V". Safety: Using Object... would lose type safety and risk an odd number of arguments, leading to runtime crashes. Performance: To keep Map.of() lightning-fast and "allocation-free" (avoiding temporary arrays), JDK developers manually overloaded it 11 times (from 0 to 10 pairs). Once you hit 11, you've run out of "pre-built" templates! ✅ The Fix: Map.ofEntries() To bypass the "one-type varargs" limit, Java uses Map.ofEntries(). It wraps each pair into a Map.Entry object. Since the type is now uniform (Entry), varargs works perfectly, allowing for any number of elements. 🛠 Lessons Learned: Source over Docs: When a standard method acts weird, Command(Ctrl for Windows) + Click into the JDK source. Don’t trust the error message 100%: The compiler often "guesses" the closest mismatch, leading you away from the actual fix. The Dispatch Map Pattern: Despite this hiccup, it’s a powerful way to keep your code Open/Closed compliant and maintainable. Have you ever been misled by a cryptic compiler error? Share your stories in the comments! 👇 #java #backend #programming #cleancode #softwaredevelopment #tips #generics #jvm
To view or add a comment, sign in
-
-
Hello everyone! 👋 Day 5 of my deep dive into core Java fundamentals! ☕ Today, I explored Type Conversions, specifically answering a crucial question: What is the actual difference between Implicit and Explicit conversions in Java? 🤔 If you think of computer memory as physical boxes, it makes perfect sense! Here is how Java handles moving data between different sized containers: 🟢 1. Implicit Conversion (The Automatic Upgrade) This is also known as a "Widening Conversion". It happens when you move data from a smaller data type (like an 8-bit byte) into a wider/larger data type (like a 32-bit int). Because what fits in a small box will easily fit into a massive box, Java does this completely automatically. You just write int i = b; and the compiler handles it behind the scenes without complaining. 🔴 2. Explicit Conversion (The Manual Override) This is known as a "Narrowing Conversion". This happens when you try to go backwards—stuffing a large container into a smaller one. For example, trying to put a 32-bit int into an 8-bit byte. If you try to do this automatically, Java will throw a compile-time error. Why? Because the compiler is terrified that your data will get chopped off (truncated) during the squeeze! To make it happen, you have to use Type Casting. You have to manually write the target type in brackets, like b = (byte) i;, to explicitly tell Java: "I know the risks, do it anyway!". 🧠 The "Under the Hood" Mindblower: I ran an experiment today: what actually happens if you cast a massive int of 300 into a tiny byte container? Since a byte can only hold up to 127, it obviously overflows. But it doesn't crash! Instead, Java looks at the 32-bit binary representation of 300 and literally chops off the extra bits, keeping only the 8 bits that fit. A massive shortcut I learned: To figure out what number you will end up with, you can just take your number and use the modulo operator against the maximum range of a byte (256). So, 300 % 256 means our new byte will store exactly 44! Understanding how the JVM aggressively protects our memory from data loss makes its strict rules feel so much more logical. 🛡️ #Java #SoftwareEngineering #TypeCasting #TechFundamentals #StudentDeveloper #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
Why Java Is Not a Pure Object-Oriented Language A pure object-oriented programming language is one where everything in the program is treated as an object. In such languages, even basic values like numbers, characters, and boolean values are represented as objects. There are no primitive data types. javava is a language that embraces many object-oriented concepts, yet it does not fully qualify as a purely object-oriented language. Here are the key reasons why: 1. Presence of Primitive Data Types Java includes several primitive data types, such as: - int - float - double - char - boolean - long - short - byte These types are not objects, which contradicts the principle that all values in a program should be objects. For example, in the code snippet below, `a` is a primitive value, not an object: ```java int a = 5; System.out.println(a); ``` In contrast, languages like Smalltalk treat even numbers and boolean values as objects. 2. Use of the static Keyword Java permits the declaration of methods and variables using the static keyword. Static members are associated with the class itself rather than with an instance of the class, allowing access without creating an object. This undermines the principle that all operations should occur through objects. For instance: ```java class Test { static int count = 0; static void show() { System.out.println("Hello"); } } ``` In this example, the method `show()` can be called without instantiating an object. 3. Wrapper Classes and Primitive Conversion Java offers wrapper classes such as: - Integer - Float - Double - Character - Boolean These classes enable primitive values to be treated as objects. However, Java still relies on primitive types through mechanisms like autoboxing and unboxing. For example: ```java public class BoxingExample { public static void main(String[] args) { Integer i = new Integer(10); Integer j = new Integer(20); Integer k = new Integer(i.intValue() + j.intValue()); System.out.println("Output: " + k); } } ``` In this case, primitive values #ProgrammingConcepts #SoftwareEngineering #Coding #BackendDevelopment #JavaInterview #TechLearning #ProgrammingEducation #CodeNewbie #DeveloperLife #ComputerScience #ProgrammingTips #JavaConcepts
To view or add a comment, sign in
-
-
Day 28: Exploring Strings in Java Today I practiced some important concepts related to Strings in Java and how they behave in memory. One of the key characteristics of Java Strings is that they are "immutable". This means once a String object is created, its value cannot be changed. Any operation like replace() or concat() creates a new String object instead of modifying the existing one. For scenarios where frequent modifications are required, using StringBuilder or StringBuffer is recommended because they are mutable. 🔹 Ways to create Strings in Java String str1 = "java"; // String literal String str2 = new String("java"); // Using new operator When Strings are created using literals, they are stored in the String Constant Pool (SCP) inside the heap memory. The SCP avoids duplicate objects to save memory. Because of this: String str1 = "java"; String str3 = "java"; System.out.println(str1 == str3); // true "==" returns true because both references point to the same object in the String Constant Pool. But when we create a String using the new operator: String str3 = new String("java"); System.out.println(str1 == str3); // false System.out.println(str1.equals(str3)); // true == compares memory addresses, while .equals() compares actual values. 🔹 Immutability Example String str7 = "Hello "; str7.concat("Everyone"); System.out.println(str7); // Output: Hello The String is not modified because Strings are immutable. 🔹 Mutable Alternative StringBuilder sb = new StringBuilder("Hello "); sb.append("Everyone"); System.out.println(sb); //Output: Hello Everyone StringBuilder and StringBuffer allow modification without creating multiple objects, making them better for frequent string manipulations in problem solving. 📌 Key Takeaways • Strings are immutable in Java • == compares references, .equals() compares values • String literals use the String Constant Pool • Use StringBuilder/StringBuffer when frequent modifications are required Learning these concepts helped me better understand how Java manages memory and string operations internally. #Java #Programming #JavaDeveloper #CodingJourney #SoftwareDevelopment #LearningInPublic Raviteja T Mohammed Abdul Rahman 10000 Coders
To view or add a comment, sign in
-
-
Want to Level Up Your Java Game? Let's Talk JVM! 🚀 Ever wondered what makes Java tick behind the scenes? 🧐 It’s not just a language; it's an entire ecosystem, and the heart of it all is the Java Virtual Machine (JVM). 💓 Understanding the JVM is like knowing how your car's engine works—it makes you a better driver, or in our case, a better developer! 👩💻👨💻 Think of the JVM as Java’s interpreter and bodyguard. It’s what gives Java its superpower: "Write Once, Run Anywhere." 🌍 Here's a quick, breakdown of how it pulls off the magic. ✨ Your Code's Epic Journey: 1️⃣ Class Loader Subsystem: This is the JVM's "receptionist." It reads your .class files (compiled Java bytecode) and loads them into memory. It also takes care of linking and initialising things so they're ready to go. 🧑✈️ 2️⃣ Runtime Data Areas (Memory): This is where all the action happens! 🏗️ It's divided into key zones: * Method Area: Stores class information and static variables. Think of it as the project blueprint repository. 📂 * Heap: The big arena where all your objects live. 🏟️ This is shared space, and it's where the Garbage Collector does its work. * JVM Stack: Per-thread, private storage for method calls and local variables. Think of it as a personal notebook for each process. 💪 * PC Register: Keeps track of exactly where each thread is in the execution process. The ultimate bookmark! 🔖 * Native Method Stack: Dedicated space for non-Java (native) code. 🌐 3️⃣ Execution Engine: The engine room! 🚂 It takes that bytecode and turns it into real, executable commands. This is where you find the performance boosters: * Interpreter: Executes bytecode line by line, fast for getting things started. ⚡️ * JIT (Just-In-Time) Compiler: The performance wizard. 🧙♂️ It finds the "hot spots" in your code and compiles them directly into native machine code for maximum speed. * Garbage Collector (GC): Your code's janitor. 🧹 It automatically finds and frees up memory occupied by objects you're no longer using, preventing memory leaks and keeping things running smoothly. So, next time you run a Java application, remember the incredibly sophisticated JVM working tirelessly to make it happen! ⚙️ What's your favourite part of JVM architecture? Let me know in the comments! 👇 #Java #JVM #SoftwareEngineering #TechInfluencer #CloudComputing #CodingLife #LearnToCode #JavaDeveloper #TechTutorials #ProgrammerInsights #JVMInternal #PerformanceOptimization
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