Java and JavaScript are not call by reference. It's time to clarify a common myth: “Java / JavaScript pass objects by reference” is not true. Both languages strictly use call by value, similar to Python. Why the confusion? When you pass objects, changes can sometimes reflect outside the function, which may appear to be call by reference. However, it’s actually value copying. To understand this, consider the memory architecture: - Stack: Stores variables and function calls, with each call creating a new stack frame. - Heap: Stores actual objects. Here’s what happens during a function call: 1. Variable Creation: - Primitives store actual values. - Objects store references (memory addresses). 2. Function / Method Call: - A new stack frame is created, and parameters become new local variables. 3. Core Step — Value Copy: - The value of the argument is copied. For primitives, the data is copied; for objects, the reference (address) is copied. It’s still a copy in both cases. 4. Inside Function: - Mutation works (e.g., 'obj.name = "Ishwar"' changes the same object in the heap). - Reassignment does not work (e.g., 'obj = new Object()' only changes the local copy). 5. Function Ends: - The stack frame is destroyed, and original variables remain unchanged. Mental Model: The caller variable copies the value to the function parameter, providing no direct access to the original variable—only a copy is used. This behavior applies to multiple languages: - Java: Call by value - JavaScript: Call by value - Python: Call by value (object reference) - C#: Call by value (default) Final truth: “Everything is pass by value. Some values just happen to be references.” 🔖 Follow CodeWithIshwar for more deep dives into real-world programming concepts. #CodeWithIshwar #Java #JavaScript #Python #Programming #SoftwareEngineering #BackendDevelopment #Coding #Developers #Tech #ComputerScience #OOP #Debugging
Java and JavaScript Call by Value, Not Reference
More Relevant Posts
-
Hey 👋🏾 guys, it's been a minute. Today i want to talk about my programming language tourism (which has now come to an end) and the languages i have settled on for life and why. I have spent the better part of the last 5 years touring programming languages to get a sense of their capabilities and their use cases (i.e. where they shine above others) In no particular order: - Golang (over Java/C++) - Zig (over Rust) - Erlang/Elixir (over Haskell/Ocaml) - JavaScript/Typescript (over CoffeeScript 😁) - Python (over R) - PHP (over C#.NET) - Bash (over Powershell) - C (over Fortran/Cobol) - Assembly (where necessary) #NOTE: Now, i am not saying that i will never write Java, Rust, Odin or C#. For the right amount of money i will yet if i had the chance to choose based on tradeoffs and longevity of the software project, i will choose the languages above. #FUNFACT: I am currently writing and redesigning a toy programming language (my side project: #Antro) in Java. REASONS ======== #PHP: When i need to build a set of web pages really quickly and i am not too pressed about high performance or speed. I just want something simple to setup and manage. #Golang: When I need to build resilient web-based, optionally cloud-native solutions that stand the test of time and stress. I am keen on high performance and throughput. Something that i can manage without breaking much sweat no matter the domain complexity. #Zig. Let me just say it. Zig, Rust and Go have made me avoid the following (as much as i can) with passion: - Monads (with transforms/higher-kinderd types & repeated piping) - Try/Catch (without explicit limits on error chaining+checked exceptions) - Exceptions (without being paired with invariant checking) 1. monads don't compose well and are difficult to compose fully. 2. monads can have complicated & bloated types signatures. 3. monads cannot specify particular effects (e.g. using I/O effects but no specifics around file I/O or socket I/O). 4. using monads, error-handling for I/O-bound tasks is leaky and messy and not debug-friendly. 5. Monads do solve problems but they create many more. 1. try is low on granularity of statements that can go into it which creates problems for the catch block. 2. the catch block (without error chaining paired tightly with checked exceptions) becomes a nightmare to manage. 3. try/catch solve problems but they're mostly abused without constraints. 1. Great exception handling relies heavily on limiting the number of check exceptions thrown by a function/method and invariant checking where it is cheap to do so. Zig is a breathe of fresh air when it comes to programming more this age. It's use of error unions and the `try` keyword is lovely. For serious, no bullshit, joyful programming of toy projects to serious stuff like solving NP problems for bin packing in the freight/haulage industry. Of course, i still use language that employ monads, try/catch and exceptions but not without serious constraints.
To view or add a comment, sign in
-
-
🚀 ArrayDeque in Java 📌 How to use ArrayDeque ad = new ArrayDeque(); ad.add(10); ad.add(20); ad.add(30); System.out.println(ad); 📌 Points to Remember 1️⃣ Initial capacity = 16 2️⃣ Heterogeneous data → Yes, it will store 3️⃣ Preserves order of insertion 4️⃣ Duplicates are allowed 5️⃣ Null values are NOT allowed 📌 Constructors (3) 1. ArrayDeque() 2. ArrayDeque(int) 3. ArrayDeque(Collection) Example: LinkedList ll = new LinkedList(); ll.add(10); ll.add(20); ArrayDeque ad = new ArrayDeque(ll); 📌 Internal Structure 👉 Resizable array (Dynamic array) 📌 Hierarchy Iterable → Collection → Queue → Deque → ArrayDeque 📌 Accessing Elements ❌ No indexes in ArrayDeque ❌ Normal for loop will not work ✔️ Use for-each loop for(Object a : ad){ System.out.println(a); } 📌 Iterator (Forward) Iterator cursor = ad.iterator(); while(cursor.hasNext()){ System.out.println(cursor.next()); } 📌 Descending Iterator (Backward) Iterator cursor = ad.descendingIterator(); while(cursor.hasNext()){ System.out.println(cursor.next()); } 📌 When to use ArrayDeque ✔️ Heterogeneous data ✔️ Duplicate entries ✔️ No null values ✔️ Preserves order of insertion 🎯 Summary: ArrayDeque is a resizable array-based data structure that allows insertion and deletion from both ends, preserves order, allows duplicates, but does not allow null values and indexing. #Java #ArrayDeque #JavaCollections #Programming #Coding #Developers #Learning
To view or add a comment, sign in
-
💡 Python vs Java: Naming Conventions Every Developer Should Know Clean code starts with good naming. Whether you're coding in Python or Java, following proper naming conventions makes your code more readable, maintainable, and professional. 🔹 Python Naming Conventions ✔️ Basic Rules: Use letters, numbers, and underscores only Must start with a letter or underscore (not a number) Case-sensitive (e.g., myVar, myvar, MYVAR are different) Avoid reserved keywords like if, else, while, def ✔️ Best Practices: Variables & Functions → snake_case (e.g., user_age, calculate_total) Constants → UPPER_CASE_WITH_UNDERSCORES (e.g., MAX_RETRIES) Classes → PascalCase (e.g., UserSession) Modules/Packages → lowercase (e.g., data_utils) 🔹 Java Naming Conventions ✔️ Basic Rules: Use letters, digits, _, and $ Must start with a letter, _, or $ (not a digit) Case-sensitive No spaces allowed Avoid keywords like int, class, boolean ✔️ Best Practices: Variables & Methods → camelCase (e.g., studentName, calculateTotal) Constants → UPPER_CASE (e.g., MAX_SPEED) Classes → PascalCase (e.g., MyMainClass) Packages → lowercase (e.g., datautil) ✨ Pro Tip: Use meaningful and descriptive names — your future self (and your teammates) will thank you! #Python #Java #CodingStandards #CleanCode #ProgrammingTips #Developers #TechLearning
To view or add a comment, sign in
-
Java Method Overloading I was revising notes on method overloading, and it reminded me how easy it is to memorize definitions… but miss the real mechanics behind it. Let’s break it down in a way that actually sticks What the Compiler Actually Uses When Java resolves an overloaded method, it ONLY looks at: ✔️ Method name ✔️ Number of parameters ✔️ Data types of parameters ✔️ Order (sequence) of parameters This combination is called the method signature ❌ Return type is completely ignored What is “Overload Resolution”? It’s the process where the compiler decides which method to call from multiple overloaded methods. Important: This decision happens at compile time, not runtime That’s why method overloading is also called: Compile-time polymorphism Static polymorphism Early binding Static binding Real Understanding (From Notes → Reality) “Compiler binds method call with method body during compilation” Let’s make that practical: void add(int x, int y) { } void add(int x, float y) { } void add(float x, float y) { } add(10.5f, 20.5f); 👉 Compiler instantly picks: add(float, float) ✔️ Decision made at compile time ✔️ Execution happens later at runtime ⚡ Where Most People Go Wrong Many think: “Return type helps differentiate methods” ❌ Wrong. int add(int a, int b) { return 0; } double add(int a, int b) { return 0; } // ❌ Error 👉 Same signature → Compilation Error The Hidden Rule When multiple methods match, Java follows priority: 1️⃣ Exact match 2️⃣ Widening 3️⃣ Autoboxing 4️⃣ Varargs If two methods fall at same level → ❌ Compilation Error The Illusion “It creates an illusion that one method performs multiple activities” In reality: Methods are different Only the name is same Each method handles a specific case Overloading improves readability, not magic Reference For deeper understanding of invalid cases: 🔗 https://lnkd.in/gD3W_efG Thanks to PW Institute of Innovation and my mentor Syed Zabi Ulla sir for helping me truly understand how Java thinks under the hood. Your guidance made these concepts much clearer and interview-ready. 🚨 One-Line Truth Method overloading is not about flexibility at runtime — it’s about clarity and compile-time precision #Java #Programming #SoftwareEngineering #CodingInterview #FAANG #JavaDeveloper #TechLearning
To view or add a comment, sign in
-
-
💻 Generics in Java — Write Flexible & Type-Safe Code 🚀 If you’ve ever faced ClassCastException or messy type casting… Generics are your solution 🔥 This visual breaks down Java Generics in a simple yet practical way 👇 🧠 What are Generics? Generics allow you to write type-safe and reusable code by using type parameters (<T>). 👉 Instead of hardcoding data types, you write code that works with any type 🔍 Why Generics? ✔ Eliminates explicit type casting ✔ Ensures compile-time type safety ✔ Improves code reusability ✔ Makes code cleaner and readable 🔄 Core Concepts: 🔹 Generic Class class Box<T> { T data; } 👉 Same class → works with String, Integer, etc. 🔹 Generic Method public <T> void printArray(T[] arr) 👉 Works for any data type 🔹 Bounded Types <T extends Number> 👉 Restrict types (only numbers allowed) 🔹 Wildcards (?) <?> → Any type <? extends T> → Upper bound <? super T> → Lower bound 🔹 Type Inference (Diamond Operator) List<String> list = new ArrayList<>(); 👉 Cleaner code, compiler infers type ⚡ Generics with Collections: List<String> names = new ArrayList<>(); 👉 Ensures only String values are stored 💡 Real impact: Without generics → Runtime errors ❌ With generics → Compile-time safety ✅ 🎯 Key takeaway: Generics are not just syntax — they are the foundation of writing robust, scalable, and reusable Java code. #Java #Generics #Programming #BackendDevelopment #SoftwareEngineering #Coding #100DaysOfCode #Learning
To view or add a comment, sign in
-
-
💻 Generics in Java — Write Flexible & Type-Safe Code 🚀 If you’ve ever faced ClassCastException or messy type casting… Generics are your solution 🔥 This visual breaks down Java Generics in a simple yet practical way 👇 🧠 What are Generics? Generics allow you to write type-safe and reusable code by using type parameters (<T>). 👉 Instead of hardcoding data types, you write code that works with any type 🔍 Why Generics? ✔ Eliminates explicit type casting ✔ Ensures compile-time type safety ✔ Improves code reusability ✔ Makes code cleaner and readable 🔄 Core Concepts: 🔹 Generic Class class Box<T> { T data; } 👉 Same class → works with String, Integer, etc. 🔹 Generic Method public <T> void printArray(T[] arr) 👉 Works for any data type 🔹 Bounded Types <T extends Number> 👉 Restrict types (only numbers allowed) 🔹 Wildcards (?) <?> → Any type <? extends T> → Upper bound <? super T> → Lower bound 🔹 Type Inference (Diamond Operator) List<String> list = new ArrayList<>(); 👉 Cleaner code, compiler infers type ⚡ Generics with Collections: List<String> names = new ArrayList<>(); 👉 Ensures only String values are stored 💡 Real impact: Without generics → Runtime errors ❌ With generics → Compile-time safety ✅ 🎯 Key takeaway: Generics are not just syntax — they are the foundation of writing robust, scalable, and reusable Java code. #Java #Generics #Programming #BackendDevelopment #SoftwareEngineering #Coding #100DaysOfCode #Learning
To view or add a comment, sign in
-
-
🚀 Java Streams Practice - First Non-Repeating Character Ever come across this classic question? 👉 "Find the first non-repeating character in a string" Here’s a clean and efficient way to solve it using Java Streams 👇 String str = "swiss"; 💡 Approach Explained 1️⃣ Convert String → Stream of Characters i. str.chars() gives an IntStream .mapToObj(c -> (char) c) converts it into a Stream<Character> 2️⃣ Count Frequency (Preserving Order) i. Collectors.groupingBy(...) groups characters ii. Function.identity() -> key is the character itself iii. Collectors.counting() -> counts occurrences iv. LinkedHashMap::new -> preserves insertion order (important!) 👉 Why LinkedHashMap? Because we need the first non-repeating character in the original order. 3️⃣ Filter First Non-Repeating Character i. entrySet().stream() -> iterate over map entries ii. .filter(e -> e.getValue() == 1) -> only unique characters iii. .map(Map.Entry::getKey) -> extract character iv. .findFirst() -> get first match 🧠 Pro Tip If you use HashMap instead of LinkedHashMap, you might get the wrong answer because order is not guaranteed. 💬 Have you solved this problem differently? Drop your approach in the comments! 💻 I’ve added my Java solution in the comments below. Please let me know if there are any other approaches I could try. #Java #Java8 #JavaStreams #CodingInterview #DSA #FunctionalProgramming #Developers #BackendDevelopment
To view or add a comment, sign in
-
-
Stop writing Python like Java/C++ when thinking about backend performance. The 'Pythonic' way to approach background tasks isn't about threads for every little thing. It's about offloading work that doesn't need to happen immediately, so your main request handler can respond quickly. This frees up your web server to serve more incoming requests, rather than getting stuck waiting for a long-running process. Think of it like a restaurant: the waiter (your main request handler) takes your order and brings it to the kitchen. The kitchen staff (background workers) then prepare your food without the waiter standing there waiting. The waiter can then go take the next order. Here's a quick look: Okay (Blocking) # In your web request handler def process_data(request): longrunningtask() # This blocks the request until it's done return HttpResponse("Done!") Best (Non-Blocking with Background Worker) # In your web request handler def processdataasync(request): enqueuetask(longrunning_task) # Task is put in a queue, request returns immediately return HttpResponse("Task accepted, processing in background!") # Separate process/thread manages enqueuetask and longrunning_task Background workers improve backend performance by separating time-consuming operations from the main request-response cycle, allowing your application to handle more concurrent users. #Python #CodingTips
To view or add a comment, sign in
-
-
🚀 Mastering ArrayDeque in Java — A Powerful Alternative to Stack & Queue If you're working with Java collections, one underrated yet powerful class you should know is ArrayDeque. It’s fast, flexible, and widely used in real-world applications. Here’s a crisp breakdown 👇 🔹 What is ArrayDeque? ArrayDeque is a resizable-array implementation of the Deque interface, which allows insertion and deletion from both ends. 💡 Key Features of ArrayDeque ✔️ Default initial capacity is 16 ✔️ Uses a Resizable Array as its internal data structure ✔️ Capacity grows using: CurrentCapacity × 2 ✔️ Maintains insertion order ✔️ Allows duplicate elements ✔️ Supports heterogeneous data ❌ Does NOT allow null values 🛠️ Constructors in ArrayDeque There are 3 types of constructors: 1️⃣ ArrayDeque() → Default capacity (16) 2️⃣ ArrayDeque(int numElements) → Custom initial capacity 3️⃣ ArrayDeque(Collection<? extends E> c) → Initialize with another collection 🔍 Accessing Elements Unlike Lists, ArrayDeque has some restrictions: ❌ Cannot use: Traditional for loop (index-based) ListIterator ✅ You can use: for-each loop Iterator Descending Iterator (for reverse traversal) 🧬 Hierarchy of ArrayDeque Iterable ↓ Collection ↓ Queue ↓ Deque ↓ ArrayDeque 👉 In simple terms: ArrayDeque implements Deque Deque extends Queue Queue extends Collection Collection extends Iterable 🔥 Why use ArrayDeque? ✔️ Faster than Stack (no synchronization overhead) ✔️ Efficient double-ended operations ✔️ Ideal for sliding window, palindrome checks, and BFS/DFS algorithms 💬 Final Thought If you're still using Stack, it might be time to switch to ArrayDeque for better performance and flexibility! #Java #DataStructures #ArrayDeque #Programming #JavaCollections #CodingInterview #SoftwareDevelopment TAP Academy
To view or add a comment, sign in
-
-
🚀 Do you really know the order in which Java executes your code? Most developers write code… But fewer truly understand how Java executes it behind the scenes. Let’s break one of the most asked (and misunderstood) concepts 👇 🧠 Java Execution Order (Class → Object) Whenever a class is used and an object is created, Java follows this strict order: 👉 Step 1: Static Phase (Runs only once) - Static variables - Static blocks ➡ Executed top to bottom 👉 Step 2: Instance Phase (Runs every time you create an object) - Instance variables - Instance blocks ➡ Executed top to bottom 👉 Step 3: Constructor - Finally, the constructor is executed --- 🔥 Final Order (Must Remember) ✔ Static Variables ✔ Static Blocks ✔ Instance Variables ✔ Instance Blocks ✔ Constructor --- 🧩 Example class Demo { static int a = print("Static A"); static { print("Static Block"); } int x = print("Instance X"); { print("Instance Block"); } Demo() { print("Constructor"); } static int print(String msg) { System.out.println(msg); return 0; } public static void main(String[] args) { new Demo(); } } 💡 Output: Static A Static Block Instance X Instance Block Constructor --- ⚠️ Pro Tips 🔹 Static runs only once per class 🔹 Instance logic runs for every object 🔹 In inheritance: - Parent → Child (Static) - Parent → Constructor → Child (Instance) --- 🎯 Why this matters? Understanding this helps you: ✔ Debug tricky initialization issues ✔ Write predictable code ✔ Perform better in interviews --- 💬 Next time you write a class, ask yourself: “What runs first?” #Java #JavaInternals #Programming #Developers #CodingInterview #TechLearning
To view or add a comment, sign in
-
More from this author
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
Quick check: ------------- If you pass an object to a method and reassign it inside… Will the original object change? Yes or No — drop your answer 👇