📄Java clone() 1️⃣ What clone means Shallow copy → copy the Object reference Deep copy → copy the Object reference+ copy their fields deeply 2️⃣ What Java actually does by default super.clone() ➡ Copies object structure ➡ Inner objects are shared So Java clone copies: ✔ primitives ❌ references (pointer copied, not object) 3️⃣ How we make it Deep Copy Manually clone inner objects: new Location(this.location) So: super.clone() + manual cloning = Deep Copy 4️⃣ Return Type Confusion Java forces method signature: Object clone() Compiler only sees Object So we cast: User copy = (User) original.clone(); 🧠 Casting does NOT create or convert objects It only changes how compiler views the reference 5️⃣ What actually happens internally clone() → memory duplication (no constructor called) Casting → only permission to access methods Object ref = userClone; ((User)ref).getName(); // allowed after cast No new object created here. 6️⃣ Important internal fact clone() in Object is a native method Real implementation exists inside JVM (C/C++), so IDE cannot open its source code. return (User) super.clone(); → works, but only shallow copy return new User(this); → works and can be deep copy GitHub Link: https://lnkd.in/g5Zj48m6 🔖Frontlines EduTech (FLM) #java #coreJava #BackendDevelopment #Programming #CleanCode #ResourceManagement #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs #cloneMethod #deepCopy #shallowCopy
Prasanna Peethambaram’s Post
More Relevant Posts
-
Java Compiled Or Interpreted. Is Java a compiled or interpreted language? The standard picture of Java is of a language that’s compiled into .class files before being run on a JVM. Lot of developers can also explain that bytecode starts off by being interpreted by the JVM but will undergo just-in-time (JIT) compilation at some later point. Here, however, many people’s understanding breaks down into a somewhat hazy conception of bytecode as basically being machine code for an imaginary or simplified CPU. In fact, JVM bytecode is more like a halfway house between human-readable source and machine code. In the technical terms of compiler theory, bytecode is really a form of intermediate language (IL) rather than actual machine code. This means that the process of turning Java source into bytecode isn’t really compilation in the sense that a C++ or a Go programmer would understand it, And javac isn’t a compiler in the same sense as gcc is — it’s really a class file generator for Java source code. The real compiler in the Java ecosystem is the JIT compiler. Some people describe the Java system as “dynamically compiled.” This emphasizes that the compilation that matters is the JIT compilation at runtime, not the creation of the class file during the build process. So, the real answer to “Is Java compiled or interpreted?” is “both.” I’m building a complete Senior Java Interview Guide. If this helps you, you can support the series here #Java #JavaStreams #SoftwareEngineering #Programming #CleanCode #Interviews #interviewGuide
To view or add a comment, sign in
-
-
⚠️ Java Tip - Compound Operators Can Hide Type Conversions - Consider this code: int result = 20; result -= 2.5; System.out.println("result = " + result); // This DOES compile: // This does NOT compile: // result = result - 5.5; // possible lossy conversion from double to int // But this DOES compile: result -= 5.5; System.out.println("Hidden behavior here: result = " + result); Why does result -= 5.5 compile, but result = result - 5.5 does not? Because compound assignment operators in Java perform an implicit cast. Behind the scenes, this: result -= 5.5; is actually doing this: result = (int)(result - 5.5); Java silently casts the result back to int, potentially losing precision. That means: The compiler protects you in result = result - 5.5 But allows a silent narrowing conversion in result -= 5.5 This is not a bug it’s defined behavior in the Java Language Specification. If you're getting into programming, remember: - Understand what the language does for you automatically - Never assume implicit conversions are safe - Read compound operators carefully in numeric operations Small details like this 😉 separate someone who writes code… from someone who understands it. #Java #Programming #Backend #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
🚀 #WhyGoroutinesAreLightweight? 1️⃣ Very Small Initial Stack Size * A goroutine starts with ~2 KB stack (can grow dynamically). * A Java thread typically starts with ~1 MB stack (configurable, but large by default). 👉 That means you can run hundreds of thousands of goroutines in the same memory where you could only run thousands of threads. 2️⃣ #Managed by Go Runtime (Not OS) * Java threads = 1:1 mapping with OS threads. * Goroutines = M:N scheduler model This means: * Many goroutines (N) are multiplexed onto fewer OS threads (M). * Go runtime scheduler decides which goroutine runs. This reduces: * OS context switching cost * Kernel-level overhead 3️⃣ #CheapContextSwitching Switching between goroutines: * Happens in user space * Much faster than OS thread switching * Does not require kernel involvement Java threads: * Context switching handled by OS * More expensive 4️⃣ #EfficientBlockingModel When a goroutine blocks (e.g., I/O): * Go runtime parks it * Another goroutine runs on the same thread In Java: Blocking thread often blocks OS thread (unless using async frameworks) 5️⃣ #DynamicStackGrowth Goroutines: * Stack grows and shrinks automatically * Memory efficient Java threads: * Fixed stack size * Allocated upfront Summary Feature Goroutine Java Thread Stack Size ~2KB (dynamic) ~1MB (fixed) Scheduling. Go runtime OS Context Switching User-level Kernel-level Scalability. Massive Limited 🔥 Real Example You can easily spawn: for i := 0; i < 100000; i++ { go process() } Try doing that with 100,000 Java threads 😅 — you’ll likely run out of memory. #TechCareers #SoftwareEngineer #BackendEngineer #Developers #TechCommunity #CodingLife #golangdeveloper
To view or add a comment, sign in
-
-
🚀 Day 30 and 31 – Deep Dive into Static in Java Over the last two days, I gained a strong understanding of the Static concept in Java from both execution and real-world perspectives. 1️⃣ How Java Program Executes (Memory Understanding) I understood how a Java program runs inside JRE memory, which includes: 1.Code Segment 2.Stack 3.Heap 4.Method Area (Static Segment / Meta space) 2️⃣ Execution Order in Java 1.Static variables 2.Static block 3.main() method 4.Object creation 5.Instance block 6.Constructor 7.Instance methods This clearly explains the difference between class-level loading and object-level creation. 3️⃣ Static vs Instance – Core Difference 🔹 Static Belongs to Class Memory allocated once Loaded during class loading Shared among all objects 🔹 Instance Belongs to Object Memory allocated per object Loaded during object creation Separate copy for each object 4️⃣ 💡 Real-Time Use Case of Static (Banking Example) Using a loan interest calculation example: If 10000 objects are created Instance variable creates 10000 copies in memory Static variable creates only 1 shared copy ✅ This improves memory efficiency and application performance. 5️⃣ 🔧 Static Members and Their Use Cases 🔹 Static Variable Used when value must be common for all objects Example: rate of interest, PI value, shared counters 🔹 Static Block Executes once during class loading Used to initialize static variables 🔹 Static Method Can be called without creating an object Used for utility/helper methods Example: Math class methods 6️⃣ 📌 Key Takeaways Static improves memory optimization Static belongs to class, not object Static variables load only once Static block runs once during class loading Static methods do not require object creation Execution flow understanding is important before learning Inheritance Feeling more confident about how Java works internally in memory 💻✨ Grateful to my trainer Sharath R for explaining the concept clearly and practically 🙌 #Java #CoreJava #OOPS #StaticKeyword #LearningJourney #BackendDevelopment #SoftwareEngineering #FullStackDeveloper
To view or add a comment, sign in
-
-
Many people write Java code every day, but very few stop and think about how memory actually works behind the scenes. Understanding this makes debugging and writing efficient code much easier. Here’s a simple way to think about Java memory inside the JVM: 1. Heap Memory This is where all the objects live. Whenever we create an object using "new", the memory for that object is allocated in the heap. Example: "Student s = new Student();" The reference "s" is stored somewhere else, but the actual "Student" object is created inside the Heap. Heap memory is shared and managed by Garbage Collection, which automatically removes unused objects. 2. Stack Memory Stack memory is used for method execution. Every time a method runs, a new stack frame is created. This frame stores local variables and references to objects. When the method finishes, that stack frame is removed automatically. That’s why stack memory is fast and temporary. 3. Method Area (Class Area) This part stores class-level information such as: • Class metadata • Static variables • Method definitions • Runtime constant pool It is created once when the class is loaded by the ClassLoader. 4. Thread Area / Program Counter Each thread has its own program counter which keeps track of the current instruction being executed. It helps the JVM know exactly where the thread is in the program. In simple terms: Stack → Method execution Heap → Object storage Method Area → Class definitions Thread Area → Execution tracking Understanding this flow gives a much clearer picture of what really happens when a Java program runs. #Java #JVM #BackendDevelopment #SoftwareEngineering #Programming
To view or add a comment, sign in
-
-
Performance tuning in Java gets interesting the moment you stop looking at your code… and start looking at the JVM itself. Hotspots, inlining, GC strategies, thread contention—there’s a whole world of behavior happening underneath your application that decides how fast it really runs. If you’ve ever wondered why two pieces of code that look identical don’t perform the same, this article digs into the JVM mechanics that explain it. https://bit.ly/463CL01
To view or add a comment, sign in
-
Most Java performance problems weren't caused by bad algorithms. They were caused by objects no one thought twice about creating. Here's the hidden cost most developers overlook: Every object you create in Java lands on the heap. The Garbage Collector is responsible for cleaning it up. And that cleanup isn't free — it consumes CPU, and at worst, it pauses your entire application. Here's how it unfolds: → Every new object is born in Eden — a small, fast memory space → Fill it too quickly with throwaway objects and Java triggers a GC sweep → Most short-lived objects die there — that part is cheap and fast → But survivors get promoted deeper into memory (Old Generation) → When Old Generation fills up, Java runs a Full GC — and your app pauses That final pause isn't milliseconds. In heavy systems, it can be seconds. Users feel it. And the surprising part? Most of this pressure comes from innocent-looking code: ❌ new String("hello") instead of just "hello" ❌ String concatenation inside loops ❌ Autoboxing primitives (int → Integer) without thinking ❌ Calling Pattern.compile() inside a method that runs thousands of times ❌ Creating SimpleDateFormat repeatedly instead of using java.time None of these feel dangerous when you write them. But at scale, they add up to thousands of short-lived objects per second — and a GC that's constantly playing catch-up. The fix isn't complicated: ✅ Prefer primitives over wrapper types ✅ Use StringBuilder for string building in loops ✅ Cache reusable objects as static final constants ✅ Embrace immutable java.time classes — they're designed for reuse The best object, from a GC perspective, is the one you never created. I'm curious — what's the worst unnecessary allocation you've come across in a real codebase? And did it actually cause a production issue? Drop your story below 👇 Let's learn from each other. #Java #SoftwareEngineering #Performance #GarbageCollection #BackendDevelopment #CleanCode #CodeReview
To view or add a comment, sign in
-
🚀 Java 8 Streams – A Small Problem That Tests Big Concepts Today I revisited a classic interview question that seems simple but hides some heavy duty concepts: 👉 Find the last repeating character in a string using Java 8 Streams. Example: Input: "programming" Output: g (The repeated chars are 'r', 'g', 'm'. 'g' is the last one to appear in the original sequence.) Here is an elegant way to solve it: Java String input = "programming"; Optional<Character> result = input.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), LinkedHashMap::new, // Key: Maintains insertion order Collectors.counting() // Value: Frequency count )) .entrySet() .stream() .filter(e -> e.getValue() > 1) .reduce((first, second) -> second) // The "Last" logic .map(Map.Entry::getKey); result.ifPresent(System.out::println); ✨ Why this is a great test of fundamentals: It’s not just about the syntax it’s about what’s happening under the hood: It’s easy to write code that works it’s harder to write code that is both expressive and efficient. I’m curious how would you tackle this 😄? 1️⃣ Stick to the modern Streams approach? 2️⃣ Go back to a traditional for loop for potential performance gains? 3️⃣ Use a different collection entirely? #Java #Java8 #Streams #BackendDevelopment #CodingInterview #SoftwareEngineering #CleanCode #InterviewQuestion
To view or add a comment, sign in
-
-
how Java handles variables, memory allocation, and program execution inside JRE. 🔹 What I Learned: ✅ Variables & Identifiers Variables are containers used to store data. In Java, we mainly work with: Instance Variables – Declared inside a class but outside methods. Stored in the Heap Memory. Local Variables – Declared inside methods. Stored in the Stack Memory. ✅ Key Difference: Instance variables get default values (int → 0, float → 0.0, boolean → false, char → '\u0000') Local variables do not get default values – they must be initialized before use. ✅ JRE (Java Runtime Environment) When we run a Java program: HLL → Compiler → Bytecode → JVM → Execution inside JRE Memory is divided into: 📌 Code Segment 📌 Heap Segment (Objects & Instance variables) 📌 Stack Segment (Method calls & Local variables) 📌 Static Segment ✅ Methods in Java Methods define behavior of an object. They can: Take input & return output Take input & not return output Not take input but return output Not take input & not return output 💡 Real-Time Example: Banking Application Imagine a Banking App: Java 👇 class BankAccount { double balance = 5000; // Instance variable (Heap) public void deposit(double amount) { double newBalance = balance + amount; // Local variable (Stack) balance = newBalance; System.out.println(balance); } } ✔ balance belongs to the object → stored in Heap ✔ newBalance is temporary → stored in Stack ✔ After method execution, newBalance is removed from memory This explains how Java efficiently manages memory during execution. 📌 Understanding memory flow (Stack vs Heap) helped me connect theory with real execution behavior inside JVM. Learning Java is not just about writing code — it’s about understanding how it works internally. 🚀 TAP Academy #Java #InternshipJourney #JRE #JVM #MemoryManagement #ProgrammingBasics #LearningInPublic
To view or add a comment, sign in
-
-
Why Java isn't just "Write Once, Run Anywhere"—It’s "Check Once, Execute Twice." Most developers know that Java has a Compile-time and a Runtime. But internally, the "Brain" of Java switches focus during these two phases. 🚀 The Core Difference: Compile-time (The Architect): Works strictly on the Reference Type. Runtime (The Builder): Works strictly on the Actual Object Type. Let’s break down the internals: 🔹 Compile-time (The Static Phase): The Compiler (javac) is like a strict security guard. It only looks at the "Label" (Reference Type). If you have Animal myDog = new Dog();, the compiler only sees Animal. It checks if the method you are calling exists in the Animal class. It doesn't care what is actually sitting in memory yet. 🔹 Runtime (The Dynamic Phase): The JVM (Java Virtual Machine) is the executor. It looks at the actual memory heap. It sees the new Dog() object. When you call makeSound(), the JVM uses Dynamic Method Dispatch to look up the method in the Dog class, even if the reference was Animal. Key Takeaway: If your code doesn't pass the "Reference Check" at compile-time, it will never get to the "Object Execution" at runtime. #Java #Programming #Backend #SoftwareEngineering #JVM #CodingTips
To view or add a comment, sign in
-
Explore related topics
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