𝗗𝗔𝗬 𝟯 – 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲 𝗼𝗳 𝗮 𝗝𝗮𝘃𝗮 𝗣𝗿𝗼𝗴𝗿𝗮𝗺 + 𝗝𝗮𝘃𝗮 𝗧𝗼𝗸𝗲𝗻𝘀 𝗜𝗻 𝘁𝗵𝗲 𝗹𝗮𝘀𝘁 𝘁𝘄𝗼 𝗽𝗼𝘀𝘁𝘀 𝘄𝗲 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗼𝗼𝗱: • Why Java is Platform Independent • How JDK, JRE, and JVM work together to run a Java program Now it's time to move from 𝘁𝗵𝗲𝗼𝗿𝘆 → 𝗮𝗰𝘁𝘂𝗮𝗹 𝗰𝗼𝗱𝗲. 𝗟𝗲𝘁’𝘀 𝘄𝗿𝗶𝘁𝗲 𝗮 𝘀𝗶𝗺𝗽𝗹𝗲 𝗝𝗮𝘃𝗮 𝗽𝗿𝗼𝗴𝗿𝗮𝗺. ``` 𝚙𝚞𝚋𝚕𝚒𝚌 𝚌𝚕𝚊𝚜𝚜 𝙷𝚎𝚕𝚕𝚘𝚆𝚘𝚛𝚕𝚍 { 𝚙𝚞𝚋𝚕𝚒𝚌 𝚜𝚝𝚊𝚝𝚒𝚌 𝚟𝚘𝚒𝚍 𝚖𝚊𝚒𝚗(𝚂𝚝𝚛𝚒𝚗𝚐[] 𝚊𝚛𝚐𝚜) { 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗("𝙷𝚎𝚕𝚕𝚘 𝚆𝚘𝚛𝚕𝚍"); } } ``` At first glance this may look confusing. But if we break it down, the structure becomes very simple. 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲 𝗼𝗳 𝗮 𝗝𝗮𝘃𝗮 𝗣𝗿𝗼𝗴𝗿𝗮𝗺 Every Java program generally contains: 1️⃣ 𝗖𝗹𝗮𝘀𝘀 𝗗𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻 𝚙𝚞𝚋𝚕𝚒𝚌 𝚌𝚕𝚊𝚜𝚜 𝙷𝚎𝚕𝚕𝚘𝚆𝚘𝚛𝚕𝚍 In Java, everything starts with a class. The filename must match the class name. Example: 𝙷𝚎𝚕𝚕𝚘𝚆𝚘𝚛𝚕𝚍.𝚓𝚊𝚟𝚊 2️⃣ 𝗠𝗮𝗶𝗻 𝗠𝗲𝘁𝗵𝗼𝗱 𝚙𝚞𝚋𝚕𝚒𝚌 𝚜𝚝𝚊𝚝𝚒𝚌 𝚟𝚘𝚒𝚍 𝚖𝚊𝚒𝚗(𝚂𝚝𝚛𝚒𝚗𝚐[] 𝚊𝚛𝚐𝚜) This is the entry point of every Java program. When we run a program, the JVM starts execution from the 𝗺𝗮𝗶𝗻() 𝗺𝗲𝘁𝗵𝗼𝗱. 3️⃣ 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁𝘀 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗("𝙷𝚎𝚕𝚕𝚘 𝚆𝚘𝚛𝚕𝚍"); This statement simply prints output on the console. 𝗡𝗼𝘄 𝗹𝗲𝘁’𝘀 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 𝘀𝗼𝗺𝗲𝘁𝗵𝗶𝗻𝗴 𝘃𝗲𝗿𝘆 𝗶𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗶𝗻 𝗝𝗮𝘃𝗮. 𝗝𝗮𝘃𝗮 𝗧𝗼𝗸𝗲𝗻𝘀 Tokens are the smallest building blocks of a Java program. Java programs are basically made up of tokens. 𝗧𝗵𝗲𝗿𝗲 𝗮𝗿𝗲 𝗺𝗮𝗶𝗻𝗹𝘆 𝟱 𝘁𝘆𝗽𝗲𝘀: • 𝗞𝗲𝘆𝘄𝗼𝗿𝗱𝘀 → public, class, static, void • 𝗜𝗱𝗲𝗻𝘁𝗶𝗳𝗶𝗲𝗿𝘀 → names of variables, classes, methods • 𝗟𝗶𝘁𝗲𝗿𝗮𝗹𝘀 → actual values (10, "Hello", true) • 𝗦𝗲𝗽𝗮𝗿𝗮𝘁𝗼𝗿𝘀 → { } ( ) [ ] ; , • 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿𝘀 → + - * / = == Example identifier rules: ✔ Cannot start with a number ✔ Cannot use Java keywords ✔ No spaces allowed ✔ Can use letters, numbers, _ and $ Once you understand structure + tokens, reading Java code becomes much easier. If you look at the Java program again, you’ll now notice: It is simply a combination of tokens working together. Once you understand tokens and structure, reading Java code becomes much easier. 𝗧𝗼𝗺𝗼𝗿𝗿𝗼𝘄 (𝗗𝗮𝘆 𝟰) 𝗪𝗲’𝗹𝗹 𝗴𝗼 𝗱𝗲𝗲𝗽𝗲𝗿 𝗶𝗻𝘁𝗼 𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝗶𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝘁𝗼𝗽𝗶𝗰𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮: • Data Types • Variables • Primitive vs Non-Primitive types • Memory basics behind variables Because before writing real programs, understanding how Java stores data is critical. 𝗦𝗲𝗲 𝘆𝗼𝘂 𝗶𝗻 𝗗𝗮𝘆 𝟰. #Java #BackendDevelopment #Programming #LearnInPublic #Day3
Java Program Structure and Tokens
More Relevant Posts
-
Day 49 – Java 2026: Smart, Stable & Still the Future Difference Between Static and Non-Static Initializers in Java In Java, initializer blocks are used to initialize variables during the class loading or object creation phase. There are two types: Static Initializer Non-Static (Instance) Initializer Understanding their difference helps in learning how JVM memory management and class loading work. 1. Static Initializer A static initializer block is used to initialize static variables of a class. It executes only once when the class is loaded into memory by the ClassLoader. class Example { static int a; static { a = 10; System.out.println("Static initializer executed"); } public static void main(String[] args) { System.out.println(a); } } Key idea: It runs once during class loading. 2. Non-Static Initializer A non-static initializer block is used to initialize instance variables. It executes every time an object is created. class Example { int b; { b = 20; System.out.println("Non-static initializer executed"); } Example() { System.out.println("Constructor executed"); } public static void main(String[] args) { new Example(); new Example(); } } Key idea: It runs every time an object is created. 3. Key Differences FeatureStatic InitializerNon-Static InitializerKeywordUses staticNo keywordExecution timeWhen class loadsWhen object is createdRuns how many timesOnce per classEvery object creationVariables initializedStatic variablesInstance variablesMemory areaMethod AreaHeapExecution orderBefore main()Before constructor4. Execution Flow in JVM When a Java program runs: ClassLoader loads the class Static initializer executes main() method starts Object is created Non-static initializer executes Constructor executes Flow: Program Start ↓ Class Loaded ↓ Static Initializer ↓ Main Method ↓ Object Creation ↓ Non-Static Initializer ↓ Constructor Key Insight Static initializer → class-level initialization (runs once) Non-static initializer → object-level initialization (runs every object creation) Understanding these concepts helps developers clearly see how JVM manages class loading, memory, and object initialization. #Java #JavaDeveloper #JVM #OOP #Programming #BackendDevelopment
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
-
-
🚀 Day 44 – Core Java | Functional Interfaces, Lambda Expressions & Java Execution Today’s session connected multiple advanced Java concepts and clarified how modern Java simplifies coding while maintaining performance. 🔹 Functional Interface A Functional Interface is an interface that contains only one abstract method. Example: @FunctionalInterface interface Vehicle { void ride(); } Functional interfaces are important because they enable lambda expressions and modern functional-style programming in Java. Common examples from Java API: Runnable Comparable Comparator 🔹 Ways to Implement a Functional Interface We explored four different approaches: 1️⃣ Regular Class class Bicycle implements Vehicle { public void ride() { System.out.println("Pedal the cycle"); } } 2️⃣ Inner Class Class defined inside another class for better encapsulation. 3️⃣ Anonymous Inner Class A class without a name, created and used at the same location. 4️⃣ Lambda Expression (Modern Approach) Vehicle v = () -> { System.out.println("Pedal the cycle"); }; Lambda expressions help reduce boilerplate code and make programs more concise. 🔹 Key Rules of Lambda Expressions ✔ Works only with functional interfaces ✔ Can remove method signature because interface has only one abstract method ✔ Parameter types are optional in many cases ✔ Parentheses are optional when there is one parameter Example: (a) -> System.out.println(a); 🔹 Java Program Execution (Refresher) We also revisited how a Java program executes internally: .java file (High-Level Code) ↓ Java Compiler (javac) ↓ .class file (Bytecode) ↓ JVM ↓ JIT Compiler ↓ Machine Code ↓ Output Key components involved: JVM (Java Virtual Machine) Class Loader JIT Compiler (Just-In-Time Compiler) Because Java uses both compiler and interpreter concepts, it is often called a hybrid programming language. 🔹 Syntax Errors vs Exceptions Another important distinction: ✔ Syntax Error Occurs during compilation time due to faulty coding. Example: System.out.prinln("Hello"); ✔ Exception Occurs during runtime due to faulty input or unexpected situations. Example: ArithmeticException NullPointerException ArrayIndexOutOfBoundsException 💡 Key Takeaway Understanding functional interfaces, lambda expressions, and Java execution flow builds the foundation for advanced topics like multithreading, streams, and modern Java frameworks. Next concept starting: Exception Handling. #Day44 #CoreJava #JavaLearning #LambdaExpression #FunctionalInterface #JavaProgramming #DeveloperJourney #JavaOOPS
To view or add a comment, sign in
-
🚀 Java Evolution: From Java 8 to Java 25 (LTS) – Don’t Call It “Old” Yet! 👀 Think Java is just a relic of the past? Think again. It’s quietly become one of the most modern, scalable, and developer-friendly languages out there. Let’s take a whirlwind tour of its transformation. Buckle up! 🔍 🔹 Java 8 – The Revolution Begins (2014) This is where Java stopped being “that verbose enterprise thing” and started flexing. ✅ Lambdas & Functional Programming: Say hello to cleaner, expressive code. ✅ Stream API: Data processing got a functional makeover. ✅ Date & Time API: Finally, no more Calendar class nightmares. 🔹 Java 11 – Polished & Production-Ready (2018) Java shed some baggage and became a smoother ride. ✅ Standard HTTP Client: Networking without the third-party hassle. ✅ String & API Enhancements: Small tweaks, big quality-of-life wins. ✅ Developer Experience: Less friction, more focus. 🔹 Java 17 (LTS) – The Modern Backbone (2021) The go-to for most companies today. It’s stable, modern, and packed with goodies. ✅ Records: Boilerplate? What boilerplate? Data classes made easy. ✅ Sealed Classes: Control your inheritance like a pro. ✅ Pattern Matching for instanceof: Cleaner, smarter type checks. 🔹 Java 21 (LTS) – Concurrency King (2023) This is where Java redefined scalability. Mind-blowing stuff. ✅ Virtual Threads (Project Loom): Handle thousands of threads without breaking a sweat. ✅ Pattern Matching for switch: Logic so clean, it’s almost poetic. ✅ Sequenced Collections: Ordered data structures, done right. 🔹 Java 22 – Refining the Craft (2024) Java keeps trimming the fat, making life easier for devs. ✅ Unnamed Variables & Patterns: Less typing, more doing. ✅ Stream API Enhancements: Even more power for data wrangling. ✅ String Templates (Preview): Formatting strings without the mess. 🔹 Java 25 (LTS) – Future-Proofed & Ready (2025) The next frontier (based on current roadmaps and speculation). ✅ Advanced Pattern Matching: Code that reads like plain English. ✅ Performance & Garbage Collection Boosts: Faster, leaner, meaner. ✅ Virtual Thread Ecosystem: Concurrency on steroids. ✅ Expressive Syntax: Java, but somehow even prettier. 💡 Key Takeaway from This Journey: Java isn’t just about “write once, run anywhere” anymore. It’s a powerhouse of performance, scalability, and developer productivity. Ignore the memes – this language is thriving. 📌 If You’re Learning Java Today: Master Java 17 for a solid foundation (it’s the current LTS sweet spot). Get comfy with Java 21 for cutting-edge features like Virtual Threads. Keep an eye on Java 25 – it’s where the future is heading. 👇 Drop a Comment: Which Java version are you rocking right now? Are you hyped for Java 25, or sticking with the tried-and-true? Let’s chat! #Java #SoftwareEngineering #BackendDevelopment #JavaDeveloper #Programming #Coding #Tech #Developers #Learning #CareerGrowth
To view or add a comment, sign in
-
-
☕ Don’t Overwhelm to Learn Java — Java is Only This Much 🚀 🔹 FOUNDATIONS 1️⃣ Java Basics What is Java JDK, JRE, JVM How Java works First Java program Compilation & execution (Understand this first ⭐) 2️⃣ Variables & Data Types Primitive types → int, float, double, char, boolean Non-primitive types Type casting Constants (final keyword) 3️⃣ Operators Arithmetic → + - * / % Comparison → == != > < Logical → && || ! Assignment operators Ternary operator 4️⃣ Control Flow if, else if, else switch statement break & continue 5️⃣ Loops for loop while loop do-while loop Nested loops 🔥 CORE JAVA CONCEPTS 6️⃣ Methods (Functions) Method declaration Parameters & return types Method overloading Recursion 7️⃣ Arrays 1D & 2D arrays Array traversal Sorting arrays 8️⃣ Strings String class String methods StringBuilder & StringBuffer String immutability 9️⃣ Object-Oriented Programming (Very Important ⭐) Core OOP principles: Class & Object Encapsulation Inheritance Polymorphism Abstraction (🔥 Heart of Java interviews) 🔟 Constructors Default constructor Parameterized constructor Constructor overloading 1️⃣1️⃣ Access Modifiers public private protected default 1️⃣2️⃣ Static Keyword Static variables Static methods Static block 1️⃣3️⃣ this & super Keywords Current object reference Parent class access 🚀 ADVANCED JAVA 1️⃣4️⃣ Exception Handling try, catch, finally throw & throws Custom exceptions 1️⃣5️⃣ Collections Framework (Must Know ⭐) List → ArrayList, LinkedList Set → HashSet Map → HashMap Queue Iterators (🔥 Most used in real projects) 1️⃣6️⃣ Generics Generic classes Type safety 1️⃣7️⃣ File Handling Reading & writing files File operations 1️⃣8️⃣ Multithreading Thread creation Synchronization Concurrency basics 1️⃣9️⃣ Java 8+ Features Lambda expressions Stream API Functional interfaces Optional class (🔥 Highly important today) ⚙️ JAVA ECOSYSTEM 2️⃣0️⃣ Build Tools Maven Gradle 2️⃣1️⃣ JDBC (Database Connectivity) Connecting Java with database SQL execution 2️⃣2️⃣ Testing JUnit testing Test cases 2️⃣3️⃣ Logging Log4j / logging basics 🌟 FRAMEWORKS (NEXT STEP) 2️⃣4️⃣ Spring Framework Spring Core Spring Boot ⭐ REST APIs (🔥 Required for backend jobs) 2️⃣5️⃣ Hibernate (ORM) Database mapping JPA basics Follow KUNDAN KUMAR for more such content. #Java #Interview #CodingInterview #multithreading #coding #coder #codinglife #code
To view or add a comment, sign in
-
🔥 Core Java (Must Prepare) 1. What is the difference between == and .equals()? == → compares reference (memory location) .equals() → compares content/value 2. Why String is immutable? Security (used in DB, network, etc.) Thread-safe String pool optimization 3. What is String Pool? A memory area in heap where unique String literals are stored. Avoids duplicate objects → improves performance 4. Difference: ArrayList vs LinkedList FeatureArrayListLinkedListStructureDynamic ArrayDoubly Linked ListAccessFastSlowInsert/DeleteSlowFast 5. How HashMap works internally? Uses hashing (hashCode + equals) Stores data in buckets Collision handled using: LinkedList (Java 7) Tree (Java 8 → Balanced Tree) 6. Difference: HashMap vs ConcurrentHashMap HashMap → not thread-safe ConcurrentHashMap → thread-safe (segment locking / CAS) 🔥 OOP & Design 7. What are OOP principles? Encapsulation Inheritance Polymorphism Abstraction 8. Method Overloading vs Overriding Overloading → same method name, different parameters Overriding → runtime polymorphism (same method in subclass) 9. What is SOLID principle? S → Single Responsibility O → Open/Closed L → Liskov Substitution I → Interface Segregation D → Dependency Injection 🔥 Multithreading (VERY IMPORTANT) 10. What is Thread? Lightweight process for parallel execution 11. Runnable vs Callable Runnable → no return Callable → returns value + throws exception 12. What is Synchronization? Prevents multiple threads accessing same resource 13. What is Deadlock? When threads are waiting on each other forever 14. What is Executor Framework? Manages thread pool → improves performance 15. What is volatile keyword? Ensures visibility of changes across threads 🔥 Java 8+ (VERY IMPORTANT) 16. What is Lambda Expression? Short way to write functional code (list) -> list.size() 17. What is Functional Interface? Interface with one abstract method Example: Runnable 18. Stream API? Used for data processing (filter, map, reduce) 19. Optional class? Avoids NullPointerException 🔥 Exception Handling 20. Checked vs Unchecked Exception Checked → compile-time (IOException) Unchecked → runtime (NullPointerException) 21. Difference: throw vs throws throw → used to throw exception throws → declares exception 🔥 Memory & JVM 22. What is JVM? Executes Java bytecode 23. Heap vs Stack Heap → Objects Stack → Method calls, variables 24. What is Garbage Collection? Automatically removes unused objects 🔥 Advanced (4+ Year Level) 25. What is Serialization? Convert object → byte stream 26. transient keyword? Skips variable during serialization 27. Comparable vs Comparator Comparable → natural sorting Comparator → custom sorting 28. Fail-fast vs Fail-safe Fail-fast → throws exception (ArrayList) Fail-safe → works on copy (ConcurrentHashMap) 🔥 Real Interview Scenario Questions 29. How do you handle high traffic in Java? Caching (Redis) Thread pool Load balancing 30. How do you debug production issue? Logs (ELK) Thread dump Heap dump
To view or add a comment, sign in
-
🚀 Day 6/100 — Methods in Java 🔧 As programs grow bigger, repeating the same code again and again becomes messy. This is where methods help. A method is a reusable block of code that performs a specific task. Instead of rewriting logic multiple times, you write it once and call it whenever needed. This follows the DRY principle — Don't Repeat Yourself. 🔹 Basic Method Syntax returnType methodName(parameters){ // method body } Example: public static void greet(){ System.out.println("Hello Java!"); } Calling the method: greet(); Output: Hello Java! 🔹 Method with Parameters Parameters allow methods to work with different inputs. Example: public static void add(int a, int b){ int sum = a + b; System.out.println(sum); } add(5, 3); Output: 8 🔹 Method with Return Value Sometimes a method needs to return a result. Example: public static int square(int num){ return num * num; } int result = square(4); System.out.println(result); Output: 16 🔹 Method Overloading Java allows multiple methods with the same name but different parameters. This is called method overloading. Java automatically chooses the correct method based on the arguments. Example: public static int add(int a, int b){ return a + b; } public static int add(int a, int b, int c){ return a + b + c; } Usage: System.out.println(add(5,3)); // calls first method System.out.println(add(5,3,2)); // calls second method 🔴 Live Example — Max of 3 Numbers public static int max(int a, int b, int c){ if(a >= b && a >= c){ return a; } else if(b >= a && b >= c){ return b; } else{ return c; } } public static void main(String[] args){ int result = max(10, 25, 15); System.out.println("Maximum number is: " + result); } Output: Maximum number is: 25 🎯 Challenge: Write a method to find the maximum of 3 numbers and test it with different inputs. Drop your solution in the comments 👇 #Java #CoreJava #100DaysOfCode #JavaMethods #ProgrammingJourney
To view or add a comment, sign in
-
-
☕🧠 GUESS THE JAVA VERSION: ASSERT EDITION Java has evolved a lot over the years. Some features that feel “basic” today were actually introduced later than many developers think. Let’s test your Java history knowledge 👇 🔸 THE QUESTION What is the minimum Java version required to compile this code? class Example { void test(int x) { assert x > 0 : "x must be positive"; assert x < 100; } } Choose the correct answer: ▪️ Java 1.2 ▪️ Java 1.4 ▪️ Java 6 ▪️ Java 16 ▪️ Java 18 Take a moment to think before scrolling 👇 🔸 TLDR ▪️ The assert keyword appeared in Java 1.4 ▪️ It checks conditions during runtime ▪️ If the condition fails, Java throws AssertionError ▪️ Assertions are disabled by default unless enabled with -ea 🔸 THE ANSWER ✅ Java 1.4 🔸 WHY THIS IS THE CORRECT ANSWER Java 1.4 introduced the assert keyword. Assertions allow developers to verify assumptions in the code while the program runs. If the condition is false, Java throws an AssertionError. They are mostly used for: ▪️ checking internal logic ▪️ verifying program invariants ▪️ detecting bugs during development Assertions are not intended for validating user input. 🔸 TWO WAYS TO WRITE ASSERTIONS Java supports two formats: assert condition; and assert condition : message; The second form allows you to provide a message that explains the problem. Example: class Example { static int abs(int x) { int r = (x >= 0) ? x : -x; assert r >= 0 : "abs result must be non-negative"; return r; } } 🔸 IMPORTANT DETAIL Assertions are disabled by default in many runtime environments. To enable them when running a program: java -ea MyProgram If assertions are disabled: ▪️ the condition is not evaluated ▪️ no error is thrown This makes them safe to keep in production code. 🔸 A BIT OF HISTORY The assertion mechanism was introduced in Java 1.4 (JSR-41). The goal was to give developers a simple debugging tool to verify assumptions without adding heavy validation logic everywhere. 🔸 TAKEAWAYS ▪️ Assertions help detect programming mistakes early ▪️ They are designed for internal checks, not user validation ▪️ They can be safely left in code because they can be disabled at runtime ▪️ Knowing when Java features were introduced helps in certifications and legacy code maintenance 💬 Did you know assert appeared only in Java 1.4? Or did you expect it to be older? #Java #JavaDeveloper #JavaProgramming #Programming #SoftwareEngineering #Coding #Developers #TechQuiz #JavaHistory #LearnJava src: https://lnkd.in/exEmMjwC Go further with Java certification: Java👇 https://lnkd.in/eZKYX5hP Spring👇 https://lnkd.in/eADWYpfx SpringBook👇 https://bit.ly/springtify JavaBook👇 https://bit.ly/jroadmap
To view or add a comment, sign in
-
-
Standard Signature of main() Method in Java In every programming language there must be an entry point of execution from where program execution begins. In C/C++, the entry point is the main() function, which is invoked by the Operating System. OS expects 0 as exit status indicating successful program execution so the return type of main is commonly int. In Java, the entry point is also the main() method, but it is invoked by the Java Virtual Machine (JVM) instead of the OS. Since the JVM handles execution internally, there is no need to return a status code, therefore the return type of the main method is always void. In Java, every method belongs to a class, so the main method must be defined inside a class. Example: class Main { void main() { // code } } However, this method cannot be executed by the JVM because it is not accessible outside the class. To allow the JVM to access it, the method must be declared public. class Main { public void main() { // code } } In Java, methods normally belong to objects and are invoked using an object reference. If the main method were not static, the JVM would have to create an object of the class before calling it. Since main is the entry point of every program, this would add unnecessary overhead. To allow the JVM to invoke the method without creating an object, the main method is declared static. class Main { public static void main() { // code } } But this method still cannot receive data from the command line arguments. To accept input from the command line during program execution, the main method takes a parameter which is an array of strings. Each element of this array represents one argument passed from the command line. Final standard signature of the main method: class Main { public static void main(String[] args) { // code } } Here: public → allows the JVM to access the method static → allows the JVM to call the method without creating an object void → no return value required String[] args → receives command line arguments However, for a beginner writing "public static void main(String[] args)" is overwhelming. So Java developer decided to introduce simplified syntax for new comer to maintain language acceptance and popularity among all. In newer Java versions, we can write a simpler program like: void main() { System.out.println("Hello"); } Introduced in JDK 21 and finally accepted in JDK 25 (2025). The compiler automatically wraps this into a class behind the scenes. However, this feature is mainly designed for learning and small scripts, while the traditional main method remains the standard approach used in real applications. Grateful to my mentor Syed Zabi Ulla for explaining these concepts so clearly and helping me build a strong foundation in programming. #OOP #Java #Programming #ComputerScience #LearningJourney #SoftwareDevelopment
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