📘 Core Java – Day 9 Topic: Pass by Value & Pass by Reference Today I learned how data is passed to methods in Java. Understanding this concept helps avoid confusion while working with variables and objects. 🔹 Pass by Value 🔸 What is Pass by Value? The actual value stored in a variable is passed to a method. Java creates a copy of the value and sends it to the method. Any change made inside the method does not affect the original variable. This ensures data safety and avoids unintended changes. 🔸 Explanation When a primitive data type (like int, float, char, etc.) is passed to a method, Java passes only the value, not the memory address. So, the original variable remains unchanged. 🔸 Example: class PassByValueExample { static void change(int x) { x = 50; // changing copied value } public static void main(String[] args) { int a = 10; change(a); System.out.println(a); } } Output: 10 ✔ Even though x is changed to 50, the original variable a remains 10. 🔹 Pass by Reference (Object Reference) 🔸 What is Pass by Reference? The reference (memory address) of an object is passed to a method. Multiple references can point to the same object. Changes made inside the method affect the original object. This improves memory efficiency. 🔸 Explanation When an object is passed to a method, both the original reference and method parameter point to the same object in memory. So, changes reflect everywhere. 🔸 Example: class Student { int marks; } class PassByReferenceExample { static void update(Student s) { s.marks = 90; // modifying object } public static void main(String[] args) { Student obj = new Student(); obj.marks = 60; update(obj); System.out.println(obj.marks); } } Output: 90 ✔ The object value is updated because both references point to the same memory location. #CoreJava #JavaProgramming #LearningJava #PassByValue #PassByReference #Day9
Pass by Value vs Pass by Reference in Java
More Relevant Posts
-
☕ Java Generics – Upper Bounded Wildcards Explained In Java Generics, the question mark (?) represents a wildcard, meaning an unknown type. Sometimes, we need to restrict the type of objects that can be passed to a method — especially when working with numbers or specific class hierarchies. That’s where Upper Bounded Wildcards come into play. 🔹 What is an Upper Bounded Wildcard? To restrict a wildcard to a specific type or its subclasses, we use: <? extends ClassName> This means: 👉 Accept ClassName or any of its subclasses. For example, if a method should only work with numeric types, we restrict it to Number and its subclasses like Integer, Double, etc. As explained in the document (Page 1), the syntax uses ? followed by the extends keyword to define the upper bound. 🔹 Practical Example From the example shown (Page 2), a method calculates the sum of elements in a list: public static double sum(List<? extends Number> numberlist) { double sum = 0.0; for (Number n : numberlist) sum += n.doubleValue(); return sum; } 📌 Why ? extends Number? ✔ Ensures only numeric types are allowed ✔ Accepts List<Integer> ✔ Accepts List<Double> ✔ Maintains type safety 🔹 Usage in Main Method List<Integer> integerList = Arrays.asList(1, 2, 3); System.out.println("sum = " + sum(integerList)); List<Double> doubleList = Arrays.asList(1.2, 2.3, 3.5); System.out.println("sum = " + sum(doubleList)); 🔹 Output (Page 3) sum = 6.0 sum = 7.0 This demonstrates how the same method works seamlessly with different numeric types. 💡 Upper bounded wildcards improve flexibility while maintaining compile-time type safety. They are essential for writing reusable and robust generic methods in Java. #Java #Generics #UpperBoundedWildcards #JavaProgramming #OOP #FullStackJava #Developers #AshokIT
To view or add a comment, sign in
-
🚀 Learning Core Java – Understanding Strings in Java Today, I explored an important concept in Java — Strings. In Java, Strings are objects, not primitive data types. They are stored in the heap memory, and Java manages them in a special way for memory optimization. ⸻ 🔹 Types of Strings in Java Strings can be categorized into: ✔ Immutable Strings Once created, their value cannot be changed. Any modification results in a new object being created. The String class is immutable. ✔ Mutable Strings Strings that can be modified without creating new objects. (Examples include StringBuilder and StringBuffer.) ⸻ 🔹 Ways to Create a String A String can be created in three common ways: 1️⃣ Using string literal Example: Creating a string directly with double quotes. 2️⃣ Using the new keyword Example: Creating a string object explicitly using new String(). 3️⃣ Using a character array Example: Creating a character array and converting it into a String. ⸻ 🔹 Memory Allocation of Strings in Heap Heap memory is divided into two important parts: ✔ String Constant Pool (SCP) When a string is created without the new keyword, memory is allocated inside the String Constant Pool. • It does not allow duplicate values. • If the same string already exists, it reuses the existing object. ✔ Non-Constant Pool (Heap Area) When a string is created using the new keyword, memory is allocated in the normal heap (non-constant pool). • It allows duplicate objects, even if the content is the same. ⸻ 🔎 Key Insight: Using the String Constant Pool helps Java optimize memory by avoiding duplicate objects, making string handling more efficient. Understanding how Strings are stored in memory is essential for writing optimized and performance-efficient Java applications. Excited to keep strengthening my Core Java fundamentals! 🚀 🔹 Suggested Hashtags #CoreJava #JavaProgramming #StringsInJava #JavaMemory #StringPool #ProgrammingFundamentals #JavaDeveloper #LearningJourney
To view or add a comment, sign in
-
-
𝗜𝗻𝘀𝘁𝗮𝗻𝗰𝗲 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀 𝗮𝗻𝗱 𝘁𝗵𝗲 𝗡𝗲𝘄 𝗞𝗲𝘆𝘄𝗼𝗿𝗱 𝗶𝗻 𝗝𝗮 v𝗮 When you learn Java, you need to understand two key concepts: instance variables and the new keyword. These concepts are related because instance variables store data for objects, and the new keyword creates those objects. Here's what you need to know about instance variables: - They are declared inside a class but outside any method, constructor, or block. - Each object created from a class gets its own copy of the instance variables. - This means different objects can store different values in the same variable. The new keyword in Java is used to create objects. When you use new, Java allocates memory for the object and returns a reference to it. This helps create an instance of a class. To use the new keyword, you follow this format: ClassName objectName = new ClassName(); For example: Student s = new Student(); When you use the new keyword, here's what happens: - Memory is allocated in heap memory. - Instance variables are initialized with default values. - The constructor of the class is called. - A reference to the object is returned. Instance variables only exist when an object is created using the new keyword. Without creating an object, you cannot use instance variables. Understanding instance variables and the new keyword is crucial for building object-oriented applications in Java. Mastering these basics helps you learn advanced Java concepts. Source: https://lnkd.in/gYsmuJx4
To view or add a comment, sign in
-
Day 21 For Java Journey- 📘 Scanner Class The Scanner class in Java is used to take input from the user while the program is running. It helps make programs interactive instead of fixed. 🔹 Scanner is present in the java.util package 🔹 It is mainly used to read input from the keyboard (System.in) 🔹 We can read different data types like int, float, double, string, boolean 🔹 Steps to Use Scanner Class 1️⃣ Import Scanner import java.util.Scanner; 2️⃣ Create Scanner object Scanner sc = new Scanner(System.in); 3️⃣ Read input using methods int num = sc.nextInt(); String name = sc.nextLine(); 🔹 Common Scanner Methods (Easy) nextInt() → reads integer nextFloat() → reads float nextDouble() → reads double next() → reads one word nextLine() → reads full line 🔹 Simple Example Scanner sc = new Scanner(System.in); System.out.print("Enter your name: "); String name = sc.nextLine(); System.out.print("Enter your age: "); int age = sc.nextInt(); System.out.println("Name: " + name); System.out.println("Age: " + age); 🔹 Advantages of Scanner ✔ Easy to use ✔ Beginner-friendly ✔ Supports multiple data types 🔹 Disadvantages ❌ Slower than BufferedReader ❌ Not suitable for high-performance input #Day21 #Java #ScannerClass #CoreJava #LearningJourney #StudentDeveloper #77RJava 10000 Coders Raviteja T
To view or add a comment, sign in
-
📘 Core Java – Day 10 Topic: Types of Methods in Java In Java, a method is a block of code that performs a specific task and is defined inside a class. Methods help achieve code reusability, modularity, and readability. 🔹 Method Signature Syntax: returnType methodName(parameters) { // method body } Explanation: methodName: Name of the method (can be any valid identifier) parameters: Inputs passed to the method method body: Code that performs the task returnType: Type of value returned after execution 🔸 Types of Methods in Java Java methods are classified based on input (parameters) and output (return value). 1️⃣ No Input and No Output Method Does not take any parameters Does not return any value Used mainly for displaying messages or simple tasks Example: void greet() { System.out.println("Welcome to Core Java"); } 2️⃣ No Input and Output Method Does not take any parameters Returns a value Used when the result is generated internally Example: int getNumber() { return 100; } 3️⃣ Input and No Output Method Takes parameters as input Does not return any value Used to perform operations like printing results Example: void printSquare(int num) { System.out.println(num * num); } 4️⃣ Input and Output Method Takes parameters as input Returns a value Most commonly used in real-world applications Example: int add(int a, int b) { return a + b; } 📌 Learning Core Java step by step — Day 10 completed! #CoreJava #JavaProgramming #LearningJourney #Day10 #ProgrammingBasics #StudentDeveloper
To view or add a comment, sign in
-
Today I explored ArrayList in Java 🚀 Understanding how dynamic arrays work internally helped me improve my problem-solving skills in Collections. 👉ArrayList is a dynamic array class in the Java Collections Framework. 👉It is part of the java.util package and implements the List interface. 👉 Unlike normal arrays, ArrayList can grow and shrink automatically. 👉 It allows duplicate elements. 👉 It maintains insertion order. 👉 It is not synchronized (faster than Vector). ✅ Uses of ArrayList 🔹 When size of data is dynamic (not fixed) 🔹 When we need frequent data retrieval 🔹 To store duplicate elements 🔹 When insertion order must be maintained 🔹 Used in real-time applications like student lists, product lists, search history, etc. 🌟 Advantages of ArrayList ✔ Dynamic Resizing – Automatically increases capacity when full ✔ Fast Random Access – get(index) is very fast (O(1)) ✔ Maintains Insertion Order ✔ Supports Generics – Type safety ✔ Many Built-in Methods – add(), remove(), contains(), size() ❌ Disadvantages of ArrayList ✖ Slow Insertion/Deletion in Middle – Because elements shift (O(n)) ✖ Not Synchronized – Not thread-safe by default ✖ Memory Wastage – Extra capacity reserved internally ✖ Slower than LinkedList for frequent insertions/deletions. 🎯 When to Choose ArrayList? 👉 Choose ArrayList when: Searching is more frequent than inserting You need fast access using index Data size changes dynamically. Thank you Anand Kumar Buddarapu Sir for your guidance and motivation. Learning from you was really helpful! 🙏 Thank you Uppugundla Sairam Sir and Saketh Kallepu Sir for your guidance and inspiration. #Java #JavaProgramming #JavaDeveloper #CoreJava #JavaCoding #LearnJava #JavaFullStack #JavaLearner #JavaCommunity #JavaLife
To view or add a comment, sign in
-
-
☕ Java Generics – Bounded Type Parameters Explained Generics in Java provide type safety and flexibility. But sometimes, we need to restrict the type of objects that can be passed to a generic method or class. That’s where Bounded Type Parameters come into play. 🔹 What Are Bounded Type Parameters? There may be situations where a method should only accept specific types. For example: A method that works with numbers should only accept instances of Number or its subclasses. To restrict types, we use: <T extends SomeClass> The extends keyword specifies the upper bound of the type parameter. 👉 In generics, extends means: “extends” for classes “implements” for interfaces 🔹 Example – Generic Method to Find Maximum of Three Values public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; if (y.compareTo(max) > 0) { max = y; } if (z.compareTo(max) > 0) { max = z; } return max; } 📌 Explanation: ✔ <T extends Comparable<T>> ensures only comparable types are allowed ✔ Uses compareTo() method ✔ Returns the largest of three objects 🔹 Sample Output Max of 3, 4 and 5 is 5 Max of 6.6, 8.8 and 7.7 is 8.8 Max of pear, apple and orange is pear This works for: ✔ Integers ✔ Doubles ✔ Strings Because all of them implement the Comparable interface. 💡 Bounded type parameters improve type safety, enforce constraints at compile time, and make generic methods more powerful and reliable. Mastering Generics is essential for writing reusable and scalable Java applications. #Java #Generics #BoundedTypeParameters #JavaProgramming #OOP #FullStackJava #Developers #AshokIT
To view or add a comment, sign in
-
Learn how to use Java Records to simplify data modeling with immutable data, automatic method generation, and concise syntax in your apps.
To view or add a comment, sign in
-
Learn how to use Java Records to simplify data modeling with immutable data, automatic method generation, and concise syntax in your apps.
To view or add a comment, sign in
-
📌 Instance Variable vs Local Variable in Java – In Java, variables are classified based on where they are declared and how long they exist in memory. Two important types are Instance Variables and Local Variables. ✅ 1️⃣ Instance Variable in Java 👉 An instance variable is a variable declared inside a class but outside all methods. It belongs to an object (instance) of the class. 👉 Key Features: 🔹Declared inside class but outside methods 🔹Each object gets separate memory 🔹Scope is entire class 🔹Lifetime is as long as the object exists 🔹Stored in Heap memory... ✅ 2️⃣ Local Variable in Java 👉 A local variable is declared inside a method, constructor, or block. It is used only within that method or block. 👉 Key Features: 🔹Declared inside a method or block 🔹Scope is limited to that method 🔹Lifetime is only while method executes 🔹Must be initialized before use 🔹Stored in Stack memory 🔹Used for temporary calculations 🔹Used to store object properties.. Learning Java variables step by step makes OOP concepts crystal clear! Instance variables store object data, while local variables help in temporary calculations. 🙏 Special thanks to Anand Kumar Buddarapu sir for continuous guidance and support. 🙏A heartfelt thank you to Uppugundla Sairam Sir and Saketh Kallepu Sir for building such an inspiring learning environment , guidance and opportunities you provide make a huge difference in shaping our technical and professional journey. #Java #Variables #InstanceVariable #LocalVariable #JavaBasics #CodingJourney
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