What is var? var lets the compiler infer the data type of a local variable from the assigned value. With Java’s Local Variable Type Inference (var), we can write cleaner and more readable code — but only if we understand its boundaries. According to Oracle Docs: 🔗 https://lnkd.in/dzPr83eS Here are 8 practical rules every Java developer must know 1. Works with Different Data Types var name = "Alok"; // String var age = 19; // int var salary = 50000.5; // double Compiler infers the type at compile time. 2. Only for Local Variables public void demo() { var x = 10; // ✅ valid } var is limited to local scope only. 3. Not for Instance or Global Variables class Test { var x = 10; // ❌ compile-time error } 4. Not a Generic Type var list = new ArrayList<String>(); // ✅ var<String> list = new ArrayList<>(); // ❌ 5. No Explicit Generic Declaration with var You can’t mix var with explicit type parameters. ⚠️ 6. Must Be Initialized var x; // ❌ error Compiler needs a value to infer the type. 7. Not Valid for Lambda (Without Target Type) var f = () -> {}; // ❌ error Lambdas require a target type. 8. Not for Method Parameters or Return Types public var getData() { } // ❌ 💡 Key Insight: var reduces boilerplate but Java is still strongly typed — the type is inferred at compile time, not dynamic. Pro Tip: Use var when the type is obvious → avoid it when readability suffers. A big thank you to my mentor Syed Zabi Ulla & PW Institute of Innovation for continuous support and guidance. Your insights and encouragement have played a huge role in shaping my learning journey. #Java #Programming #Developers #Coding #JavaTips #SoftwareEngineering #Learning
Java var Keyword: 8 Essential Rules for Cleaner Code
More Relevant Posts
-
Oracle just announced Project Detroit at JavaOne. They're embedding 𝗖𝗣𝘆𝘁𝗵𝗼𝗻 𝗱𝗶𝗿𝗲𝗰𝘁𝗹𝘆 𝗶𝗻𝘀𝗶𝗱𝗲 𝘁𝗵𝗲 𝗝𝗩𝗠. Not a bridge. Not a wrapper. Not "call a Python process and parse stdout." The 𝘢𝘤𝘵𝘶𝘢𝘭 CPython runtime, running inside your Java process. You call Python through javax.script — the same API Java has had for years. Think about what this means for a second. All the best AI libraries live in Python. PyTorch, scikit-learn, LangChain. And most enterprise backends? Java. Spring Boot, Kafka, Kubernetes-native services. If you wanted both until now, you ran two separate services and duct-taped them together with HTTP calls or message queues. Detroit is basically saying: 𝗪𝗵𝗮𝘁 𝗶𝗳 𝘆𝗼𝘂 𝗷𝘂𝘀𝘁... 𝗱𝗶𝗱𝗻'𝘁? What if your Java service called a Python ML pipeline directly, in-process, zero network hop? I've been building the same AI agents in both Java and Python lately. The friction was never the languages. It's always been the wall between their ecosystems. Detroit is trying to knock that wall down. Early? Very. Production-ready? Nowhere close. But the direction is interesting. The repo is already up on GitHub under OpenJDK. 𝗜'𝗺 𝗴𝗼𝗶𝗻𝗴 𝘁𝗼 𝘁𝗿𝘆 𝗶𝘁 𝘁𝗵𝗶𝘀 𝘄𝗲𝗲𝗸 and see what actually works today.
To view or add a comment, sign in
-
-
Phase 6 update — percentile statistics added to the C++ benchmark. The original run reported a single mean. That's not enough. In HFT, the tail is what kills you — a 655ms GC pause doesn't happen often, but when it does, you're done. So I instrumented ComputeStatistics with 10,000 repetitions and measured the full distribution. C++ mmap — 64-byte append, pinned to core 1: - median → 4.3 ns (L1D warm, no jitter) - p99 → 9.5 ns - p99.9 → 6,566 ns (OS kernel interrupt — not the engine) - p99.99 → 7,318 ns - p100 → 7,721 ns Now compare across the full journey: Java baseline (ByteBuffer.allocate on every write): - p50 → 3,900 ns | p99.99 → 306,000 ns | p100 → 40,000,000 ns | GC → 655ms Java Phase 5 (off-heap MemorySegment slabs, GC eliminated): - p50 → 4,432 ns | p99.99 → 70,519 ns (−77%) | p100 → 11,993,000 ns (−70%) | GC → 2ms flat C++ mmap (syscall boundary removed): - median → 4.3 ns | p99.99 → 7,318 ns † | p100 → 7,721 ns † | GC → none † OS jitter, not the engine. Eliminated by isolcpus + IRQ affinity. The Java Phase 5 work was real — GC pauses eliminated, tail down 77%. But the floor is still the syscall. FileChannel crosses the kernel boundary on every write. mmap doesn't. The p99.99 went from 306 µs to 7.3 µs. Worst case from 40ms to 7.7 µs. 📂 https://lnkd.in/gifTNMSB #LowLatency #CPlusPlus #HFT #SystemsProgramming #PerformanceEngineering #DistributedSystems
To view or add a comment, sign in
-
📌 Collectors in Java Streams — Transforming Data Efficiently Collectors are used with streams to transform and gather results into collections or other structures. They are mainly used with: collect() — a terminal operation --- 1️⃣ What is collect()? collect() converts a stream into a final result like: • List • Set • Map • Grouped data Example: List<Integer> list = stream.collect(Collectors.toList()); --- 2️⃣ Common Collectors 🔹 toList() Convert stream to List list.stream() .collect(Collectors.toList()); --- 🔹 toSet() Removes duplicates list.stream() .collect(Collectors.toSet()); --- 🔹 toMap() Convert to Map list.stream() .collect(Collectors.toMap( key -> key.getId(), value -> value )); --- 3️⃣ groupingBy (Very Important) Groups elements based on a key Example: Map<String, List<Employee>> map = employees.stream() .collect(Collectors.groupingBy( e -> e.getDepartment() )); --- 4️⃣ counting() Counts elements long count = list.stream() .collect(Collectors.counting()); --- 5️⃣ joining() Joins strings String result = list.stream() .collect(Collectors.joining(", ")); --- 6️⃣ Why Collectors Are Powerful ✔ Transform data easily ✔ Replace complex loops ✔ Enable grouping and aggregation ✔ Improve readability --- 🧠 Key Takeaway Collectors turn streams into meaningful results. They are essential for data transformation and aggregation. #Java #Java8 #Streams #Collectors #BackendDevelopment
To view or add a comment, sign in
-
Stack vs Heap Memory in Java – Where Does Your Data Live? 🧠 Stack Memory: ▸ Method calls + local variables ▸ LIFO (Last In, First Out) ▸ Very fast, auto-cleared after method ends ▸ Each thread has its own stack Heap Memory: ▸ Stores objects & instance variables ▸ Shared across threads ▸ Managed by Garbage Collector ▸ Slower than Stack, can throw OutOfMemoryError Example: void demo() { int x = 10; String s = new String("Java"); } ▸ x → Stack ▸ s (reference) → Stack ▸ "Java" object → Heap Rule: → Primitives → Stack → References → Stack → Objects → Heap #Java #SpringBoot #BackendDevelopment #Memory #JavaDeveloper
To view or add a comment, sign in
-
-
Stack vs Heap Memory in Java – Where Does Your Data Live? 🧠 Stack Memory: ▸ Method calls + local variables ▸ LIFO (Last In, First Out) ▸ Very fast, auto-cleared after method ends ▸ Each thread has its own stack Heap Memory: ▸ Stores objects & instance variables ▸ Shared across threads ▸ Managed by Garbage Collector ▸ Slower than Stack, can throw OutOfMemoryError Example: void demo() { int x = 10; String s = new String("Java"); } ▸ x → Stack ▸ s (reference) → Stack ▸ "Java" object → Heap Rule: → Primitives → Stack → References → Stack → Objects → Heap #Java #SpringBoot #BackendDevelopment #Memory #JavaDeveloper
To view or add a comment, sign in
-
-
➡️ Encapsulation in Java with Example ➡️ Encapsulation = Binding data + methods together and restricting direct access using private variables. Let’s understand with a simple program class Employee { // ✅ Step 1: Make variables private (Data Hiding) private int id; private String name; // ✅ Step 2: Getter method (Read data) public int getId() { return id; } // ✅ Step 3: Setter method (Write data) public void setId(int id) { this.id = id; } // Getter for name public String getName() { return name; } // Setter for name public void setName(String name) { this.name = name; } } public class Main { public static void main(String[] args) { Employee emp = new Employee(); // 🎯 Accessing data using setter emp.setId(101); emp.setName("John"); // 🎯 Accessing data using getter System.out.println(emp.getId()); System.out.println(emp.getName()); } } 📌 Highlight: ✔ Variables are private → cannot access directly ✔ We use getters & setters to control access ✔ This ensures data security and flexibility 💡 Why? Instead of exposing data directly, we control how it is accessed and modified. This is the foundation for building secure and maintainable applications! #Java #Encapsulation #OOP #Programming #Developers
To view or add a comment, sign in
-
🚀 Still writing complex JOIN queries to manage relationships? What if you could handle everything using simple Java objects… without worrying about SQL complexity? That’s exactly where Association Mapping in Spring Boot (JPA) becomes a game-changer 🔥 🔍 What this image explains Managing relationships between database tables is one of the most challenging parts of backend development. 👉 Association Mapping solves this by: ✔ Defining how entities are connected ✔ Mapping real-world relationships directly in your code ✔ Letting JPA handle the underlying SQL 📌 Types of Relationships 🔹 One-to-One → One entity is linked to exactly one other entity 🔹 One-to-Many → One parent can have multiple children 🔹 Many-to-One → Multiple entities can relate to one parent 🔹 Many-to-Many → Complex relationships using a join/lookup table 💡 Why It Matters ✔ Cleaner & more readable code ✔ Maintains strong data integrity ✔ Reduces the need for complex SQL queries ✔ Improves scalability and maintainability 🔥 Core Insight: Stop thinking in tables… Start thinking in objects and relationships — JPA will handle the rest. 💬 Quick Question: Which mapping do you use most in real projects — One-to-Many or Many-to-One? #SpringBoot #Java #JPA #Hibernate #BackendDevelopment #SoftwareEngineering #DatabaseDesign #LearningInPublic #Developers #TechContent
To view or add a comment, sign in
-
-
One trace. 572,789 spans. 62% of all trace data in a five-minute sample, from a single service. This was a batch processing job. The #OpenTelemetry Java auto-instrumentation agent created a span for every database call inside a loop. The agent does not have a built-in span count cap per trace. It instruments what it finds, and a batch job iterating over hundreds of thousands of records will produce hundreds of thousands of spans. The trace was unusable. No backend renders half a million spans in a waterfall view. The cost was astronomical, and the four largest traces in the sample had no root span metadata, suggesting missing or disconnected parent spans. Most originated from batch or scheduled tasks like `https://lnkd.in/dBWthabm`. This organization runs 3,532 services, all on Java auto-instrumentation v1.33.6. The agent works well for request-response services. It was never designed for uncapped iteration over data. The fix depends on the batch pattern. For jobs that process items independently, use span links instead of parent-child relationships. Each item gets its own trace, linked back to the batch trace. This keeps individual traces small and queryable while preserving the connection to the batch context. For specific instrumentation that generates noise, the agent supports suppression flags. Setting `otel.instrumentation.common.experimental.suppress-messaging-receive-spans=true` eliminates receive spans for messaging consumers. Similar flags exist for JDBC, Redis, and other libraries. Review which instrumentations fire inside your loops and suppress the ones that add volume without insight. Auto-instrumentation assumes your services handle requests. When your workload does not fit that model, you need guardrails. The agent will not set them for you. And about last Friday's quiz: what does `stability: stable` mean for an OpenTelemetry semantic convention attribute? The answer is that it follows semver deprecation rules. A stable attribute is not frozen. It can still be deprecated, but the project must provide a migration path and maintain backward compatibility for a defined period. An `experimental` attribute carries no such guarantee and might be renamed or removed between releases. If you build dashboards or code generation around an experimental attribute, you accept the risk of breakage on upgrade.
To view or add a comment, sign in
-
🚀 Java Records — Clean, Concise, and Immutable Data Models Tired of writing boilerplate code for simple data carriers in Java? That’s exactly where Java Records shine ✨ 👉 Introduced in Java 14 (finalized in Java 16), records provide a compact way to model immutable data. 🔹 What is a Record? A record is a special type of class designed to hold data — no unnecessary getters, setters, equals(), hashCode(), or toString() needed. 🔹 Example: java public record User(String name, int age) {} That’s it. Java automatically generates: ✔️ Constructor ✔️ Getters (name(), age()) ✔️ equals() & hashCode() ✔️ toString() 🔹 Why use Records? ✅ Less boilerplate → more readability ✅ Immutable by default → safer code ✅ Perfect for DTOs, API responses, and data transfer ✅ Encourages clean architecture 🔹 Custom logic? You still can: java public record User(String name, int age) { public String nameInUpperCase() { return name.toUpperCase(); } } 🔹 Important points: ⚠️ Fields are final ⚠️ Cannot extend other classes (but can implement interfaces) ⚠️ Best suited for data carriers, not business-heavy objects 💡 When to use? - Microservices DTOs - API request/response models - Immutable configurations 👉 Records are a step toward more expressive and maintainable Java code. Are you using records in your projects yet? 🤔 #Java #Java17 #BackendDevelopment #CleanCode #SoftwareEngineering #FullStackDev
To view or add a comment, sign in
-
🚀 Day 2 of My Advanced Java Journey – JDBC Deep Dive Today, I explored deeper into JDBC, focusing on retrieving data, scrollable ResultSets, and metadata. 🔹 Retrieving Data from ResultSet JDBC provides multiple methods to fetch data from each column. We can retrieve data using: Column Index (int) Column Name (String) 👉 Common methods: getInt() getString() getFloat() getDouble() ✔️ Example concept: Using while(res.next()), we can iterate through rows and fetch values like id, name, designation, and salary. 🔹 Scrollable ResultSet (TYPE_SCROLL_SENSITIVE) Unlike normal ResultSets, scrollable ResultSets allow moving the cursor in multiple directions. 👉 Important methods: beforeFirst() afterLast() first() last() next() previous() absolute(int row) 💡 Helps in flexible data navigation. 🔹 ResultSet Metadata Metadata means data about data. Using ResultSetMetaData, we can get: Number of columns → getColumnCount() Column names → getColumnName(int column) Column types → getColumnType(int column) 🔍 What I explored beyond the session Difference between TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, and TYPE_SCROLL_SENSITIVE Importance of CONCUR_READ_ONLY vs CONCUR_UPDATABLE Additional methods like getBoolean(), getDate(), getLong() Why column names are preferred over index (better readability & maintainability) 💡 Mastering ResultSet handling makes JDBC much more powerful for real-world backend applications. 🙌 Special thanks to the amazing trainers at TAP Academy: kshitij kenganavar Sharath R MD SADIQUE Bibek Singh Hemanth Reddy Vamsi yadav Harshit T Ravi Magadum Somanna M G Rohit Ravinder TAP Academy 📌 Learning in public. Growing every day. #Java #AdvancedJava #JDBC #BackendDevelopment #LearningInPublic #100DaysOfCode #VamsiLearns
To view or add a comment, sign in
-
Explore related topics
- Coding Best Practices to Reduce Developer Mistakes
- Idiomatic Coding Practices for Software Developers
- Writing Clean, Dynamic Code in Software Development
- Clear Coding Practices for Mature Software Development
- Ways to Improve Coding Logic for Free
- How to Write Clean, Error-Free Code
- Clean Code Practices For Data Science Projects
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