💡 A small Java error that taught me a BIG lesson about JVM Java be like: “It runs.” JVM be like: “Yes… but WHERE is your .class file?” 😅 Today I met this classic Java error: Error: Could not find or load main class Everything looked fine. Folder ✔ Class ✔ Confidence ❌ Then Java 11 entered the chat. Its not search .class file. When you run: java HelloWorld.java Java says: “No worries, I’ll compile and run it for you.” And the funny part? 👉 No HelloWorld.class is created 🤯 It’s compiled in memory and gone like magic. Helpful? Yes. Confusing while learning JVM fundamentals? Absolutely 😄 But when you run: java com.package.HelloWorld JVM says: “I don’t do magic. Show me the .class file, correct package declaration, and proper folder structure.” 🔍Folder is NOT a package utill not mention in java class as package JVM never guesses For compilation you should be on project root. C:\Users\abcd\OneDrive\Attachments>javac duke\choice\ShopApp.java Java 11 source-file mode is helpful… and sneaky No .class file ≠ no rules 😄 Once everything aligned for JVM— C:\Users\abcd\OneDrive\Attachments>java com.don.htt.HelloWorld Hello, Java! finally appeared ☕️ #Java #JVM #CoreJava #DeveloperLife #LearningInPublic #BackendDevelopment
Java Error: Could not find or load main class
More Relevant Posts
-
Fun with pattern matching scope in Java 21 I’m switching to Java 21 and I stumbled upon a comment under 2023 article that was good to share as Java puzzle: By coincidence, one of our projects, is still on Java 11. At the same time, some dependencies have moved to Java 17. So I ended up by using OpenRewrite to backport modern Java features. Along the way, I learned many interesting things. For example, that this is perfectly valid Java: if (!(obj instanceof String str)) { throw new IllegalArgumentException(); } System.out.println(str.length()); And also this (yes, these are two different str variables): if (!(obj instanceof String str)) { Integer str = null; System.out.println(str); } else { System.out.println(str); } Now let’s play a game. Without running this code or copying it into an IDE, can you confidently tell in which cases str is available in the else branch on attached screenshot? Still too easy? Add more conditions. Nest a few "if". Use multiple pattern variables. Go wild. At some point, str starts behaving like a Heisenberg variable: until you paste the code into an IDE, you can’t be 100% sure about its scope In the end, I wrote more tests than actual transformation code: tests: https://lnkd.in/e4PncArw transformation: https://lnkd.in/emqktnFC Comment source: https://lnkd.in/eP-H2Cza
To view or add a comment, sign in
-
-
Immutable class in Java: What is immutable class? Its a class whose instances cannot be changed after creation. How to create an immutable class? 1️⃣declare class as `final` - Prevents other classes from extend it 2️⃣ declare fields as `private` and `final` - `private` prevents the fields cannot be accessed outside of the class; `final` assures the value will be set only once 3️⃣ no setter methods - Prevents overriding the values 4️⃣ constructor initialisation - Initialises all the fields in the all arguments consructor Here are some of the ways to create an immutable class(refer the image). 1️⃣ Using plain Java 2️⃣ Using lombok library - lombok provides `Value` annotation to create immutable class with minimal code 3️⃣ Using records - `public record User(int id, String name){}` Reference: https://lnkd.in/ghDmd4Ww Note: Lombok doesn't convert a collections like List, Set or Map to immutable internally. Make sure you're passing an immutable collections to the constructor. `Arrays.asList`, Factories like `List.of`, `Set.of`, and `Map.of` return immutable collection. `java.util.Collections` provides utility methods to convert the mutable connections to immutable. #java #lombok #immutable #LearnJava #programming
To view or add a comment, sign in
-
-
>Modern switch Expression (Recommended – Java 14+) ✔ Returns a value ✔ No break needed ✔ More readable >Java 17 significantly improved the switch statement, making it more concise and powerful. The most notable features are Switch Expressions and the Arrow (->) syntax, which eliminate the need for break statements and reduce boilerplate. 1) The Arrow Syntax (->) ================= Instead of the traditional case L :, Java 17 uses case L ->. No Fall-through: You no longer need to write break; after every case. Only the code to the right of the arrow is executed. Single Expressions: If you only have one line of code, you don't even need curly braces. 2) Switch as an Expression ================= You can now assign the result of a switch directly to a variable. 3. Multiple Constants ============== You can comma-separate multiple labels in a single case line, making the code much easier to read than the old "stacked" case blocks. 4. The yield Keyword ============== If you need a block of code (more than one line) inside a switch expression, you use yield to return the value. 5. Exhaustiveness ============ When using switch as an expression, the compiler checks to ensure every possible input is covered. If you are switching on an enum, you must cover all constants; if you are using String or int, a default case is mandatory.
To view or add a comment, sign in
-
-
How to add all elements of an array in Java (Explained simply) Imagine you’re sitting in front of me and you ask: 👉 “How do I add all the numbers present in an array using Java?” I’d explain it like this 👇 Think of an array as a box that already contains some numbers. For example: [2, 4, 6, 8] Now our goal is simple: ➡️ Take each number one by one ➡️ Keep adding it to a total sum Step-by-step thinking: First, we create a variable called sum and set it to 0 (because before adding anything, the total is zero) Then we loop through the array Each time we see a number, we add it to sum After the loop finishes, sum will contain the final answer Java Code: int[] arr = {2, 4, 6, 8}; int sum = 0; for (int i = 0; i < arr.length; i++) { sum = sum + arr[i]; } System.out.println(sum); What’s happening here? arr[i] → current element of the array sum = sum + arr[i] → keep adding elements one by one Loop runs till the last element Final Output: 20 One-line explanation: “We start from zero and keep adding each element of the array until nothing is left.” If you understand this logic, you’ve already learned: ✔ loops ✔ arrays ✔ problem-solving mindset This is the foundation of many real-world problems in Java 🚀 #Java #Programming #DSA #BeginnerFriendly #LearnJava #CodingBasics
To view or add a comment, sign in
-
📘 Day 12 – Java String | == vs equals() Today while learning Java, I understood an important concept about String comparison — the difference between == and equals(). What I learned 👇 🔹 String in Java String is a class String is immutable (once created, it cannot be changed) 🔹 == operator Checks memory reference Used to check whether both variables point to the same object String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); // true 🔹equals() method Checks the actual value/content of the string String s3 = new String("Java"); String s4 = new String("Java"); System.out.println(s3.equals(s4)); // true System.out.println(s3 == s4); // false 🔹 Difference == → compares memory equals() → compares value ✅ Conclusion: This concept is very important for Java interviews and for writing correct code. Learning basics like this helps me build strong Java fundamentals. #Day12 #Java #String #CoreJava #JavaBasics #JavaInterview #LearningJourney #PlacementPreparation
To view or add a comment, sign in
-
-
🔹 Question: What are Records in Java 17? How are they different from traditional POJOs? 🔹 Answer: Records are a special type of class introduced to represent immutable data carriers with minimal boilerplate. Before Java 17, a simple DTO required: fields constructor getters equals() / hashCode() toString() 🔹 Traditional POJO: public class User { private final String name; private final int age; public User(String name, int age) { this.name = name; this.age = age; } public String name() { return name; } public int age() { return age; } } 🔹 Java 17 Record: public record User(String name, int age) {} 🔹 What Java Automatically Generates: ✅ private final fields ✅ Canonical constructor ✅ Accessor methods ✅ equals() and hashCode() ✅ toString() 🔹 Why Records Were Introduced: Promote immutability by default Reduce boilerplate Improve readability Encourage value-based design 🔹 Important Constraints (Interview Favorite): Records are final (cannot be extended) Fields are implicitly final Can implement interfaces Can contain validation logic inside the constructor public record User(String name, int age) { public User { if (age < 0) throw new IllegalArgumentException("Age cannot be negative"); } } 🔹 Real-World Use Cases: REST API request/response DTOs Event payloads Database projections Configuration objects 🔹 Interview Tip: Use Records when the class is meant to hold data, not behavior. 📌 Records + Sealed Classes + Pattern Matching = Modern Java Design #Java17 #JavaInterview #Records #BackendDevelopment #SpringBoot #CleanCode #JavaDeveloper #LTS
To view or add a comment, sign in
-
-
Most Java developers write code for years without ever asking this question: How does the JVM know that a file is actually a Java class file? The answer is hidden in the first 4 bytes. Every .class file starts with a 𝐦𝐚𝐠𝐢𝐜 𝐧𝐮𝐦𝐛𝐞𝐫. 0xCAFEBABE Not a joke. Not a coincidence. A deliberate design choice. When the JVM loads a class, the very first check it performs is this: “Do the first four bytes match CAFEBABE?” If they don’t, the JVM immediately rejects the file. No bytecode parsing. No execution. No mercy. That one constant acts as a gatekeeper. It protects the JVM from: Invalid or corrupted files Random binaries Misleading inputs pretending to be bytecode In other words, before Java cares about methods, fields, or performance, it first asks a basic question: “Are you even a Java class?” What I find fascinating is what this represents philosophically. Java doesn’t assume trust. It verifies first. Even before version checks, constant pools, or instructions, the JVM demands identity. This tiny detail explains a lot about Java as a platform: Defensive by default Explicit validation Designed for long-running, safe systems Once you start noticing details like this, Java stops feeling “magical” and starts feeling intentionally engineered. Sometimes, the most important lessons are hidden in the first four bytes. #Java #JVM #Bytecode #BackendEngineering #SoftwareEngineering #ComputerScience #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 11/15 – Strings in Java (What Really Happens Behind the Scenes) 🧵 Strings look simple. But in Java, they quietly test how well you understand memory, performance, and design choices. Today’s focus wasn’t just using strings — it was understanding how Java treats them differently. 🔹 Why Strings Are Special in Java In real applications, strings are everywhere: User names Passwords API responses Logs Messages So Java treats them very carefully. 🔹 String vs StringBuilder vs StringBuffer (Real Thinking) Instead of definitions, this is how I now think about them 👇 String When data should not change (usernames, IDs, constants) StringBuilder When data keeps changing (loops, building responses, performance-critical code) StringBuffer When multiple threads might touch the same data (rare, but important) 👉 Choosing the wrong one doesn’t break code — but it hurts performance. 🧠 The Big Learning for Me The biggest mistake beginners make is: > “All strings are the same.” They are not. Java forces you to think before you modify text — and that mindset carries into clean coding everywhere else. 🏦 Real-World Example In a Bank Application: Account number → String (never changes) Transaction message → StringBuilder (keeps appending) Shared log message → StringBuffer (thread-safe) Same data type… very different intent. ✨ Simple Takeaway > Strings are not about text — they are about intent and performance. Once this clicks, a lot of Java suddenly makes sense. 💬 Community Question Have you ever faced a performance issue just because of string concatenation in loops? #Java #Strings #15DaysChallenge #JavaDeveloper #CleanCode #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
Annotations in Java Do vs Don’t ⚠️ Annotations are powerful. But they are often misunderstood. This Do vs Don’t cheat sheet summarizes what actually works in real Java systems 👇 ✅ DO Use Annotations Correctly: • Use annotations to express intent • Treat annotations as hints to frameworks, not guarantees • Combine annotations with explicit logic • Understand where and when annotations apply • Keep validation and rules close to the code Annotations help frameworks help you. ❌ DON’T Common Mistakes: • Don’t assume annotations enforce correctness • Don’t rely on annotations for business rules • Don’t assume they always work at runtime • Don’t treat annotations as a replacement for testing • Don’t ignore execution paths and configuration Annotations can be bypassed more easily than most teams realize. 🧠 Simple mental model Annotations answer: 👉 How should the framework treat this code? They do not answer: 👉 Is this code correct? 🔑 Golden rule Annotations support correctness. They do not enforce it. Correctness still comes from: • clear boundaries • explicit validation • careful design • predictable control flow Annotations reduce boilerplate. They improve readability. But responsibility still lives in code, not metadata. 👇 Which annotation do you see most misunderstood in real projects? #Java #JavaIn2026 #CleanCode #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
📘 Java Basics Series | Topic: Methods in Java Today, I learned one of the most important concepts in Java — Methods 🚀 🔹 What is a Method? A method is a block of code that performs a specific task. It helps us reuse code, reduce repetition, and write clean programs. 🔹 Why Methods are Important? ✔ Code reusability ✔ Better readability ✔ Easy maintenance ✔ Structured programming 🔹 Types of Methods in Java 1️⃣ Method without parameters & without return value void greet() { System.out.println("Hello Java"); } 2️⃣ Method with parameters & without return value void add(int a, int b) { System.out.println(a + b); } 3️⃣ Method without parameters & with return value int getNumber() { return 10; } 4️⃣ Method with parameters & with return value int multiply(int a, int b) { return a * b; } 🔹 Static vs Non-Static Methods Static Method → Called using class name Non-Static Method → Called using object 💡 Key Takeaway: Methods make Java programs modular, reusable, and easy to understand. 📈 Learning Java step by step and enjoying the journey! #Java #JavaProgramming #MethodsInJava #CoreJava #LearningJava #ProgrammingBasics #DeveloperJourney
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