Arrays in Java 🧠 Concept: An Array in Java is a container object that holds a fixed number of elements of the same data type. Each element can be accessed using an index number, starting from 0. Arrays are static in size, meaning once created, their length cannot be changed. They can store primitive data types (like int, double, char) or objects (like String, Student, etc.). Types of Arrays in Java: 1. Single-Dimensional Array – Stores elements in a single row. 2. Multi-Dimensional Array – Stores data in rows and columns (like a matrix). 3. Jagged Array – A multi-dimensional array with rows of different lengths. 💡 Why it matters: Arrays are widely used in real-world applications such as: Student result systems (storing marks of multiple subjects) E-commerce apps (storing product prices or stock quantities) Sensor data processing (reading multiple sensor values at once) Games (storing scores, levels, or positions) They make data handling simple, structured, and efficient. Example / Snippet: 1. Single-Dimensional Array public class SingleArrayExample { public static void main(String[] args) { int[] scores = {90, 85, 88, 95, 100}; // Access and display for (int i = 0; i < scores.length; i++) { System.out.println("Score " + (i+1) + ": " + scores[i]); } } } Here, the array scores stores 5 integer values, accessible using indices 0 to 4. 2. Multi-Dimensional Array public class MultiArrayExample { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Printing matrix elements for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } } This represents a 3x3 matrix — useful in mathematical or graphical applications. 3. Jagged Array (Irregular Rows) public class JaggedArrayExample { public static void main(String[] args) { int[][] numbers = { {1, 2, 3}, {4, 5}, {6, 7, 8, 9} }; for (int i = 0; i < numbers.length; i++) { for (int j = 0; j < numbers[i].length; j++) { System.out.print(numbers[i][j] + " "); } System.out.println(); } } } Jagged arrays are used when data rows have varying lengths — for example, storing monthly sales data for stores with different transaction counts. #Java #CoreJava #JavaProgramming #LearnJava #JavaDeveloper #CodingInJava #ArraysInJava #DataStructures #ProgrammingBasics #SoftwareDevelopment #TechLearning #CodingJourney
Rakshitha R’s Post
More Relevant Posts
-
Topic – The static Keyword in Java ⚙️ In Java, the static keyword means — 👉 “It belongs to the class, not to any specific object.” So instead of each object creating its own copy, everyone shares one common copy! 🧱 1️⃣ Static Variables (Class Variables) Belong to the class, not to individual objects One copy shared among all objects class Student { static String school = "ABC School"; // Shared by all students String name; Student(String name) { this.name = name; } } public class Main { public static void main(String[] args) { Student s1 = new Student("Shahil"); Student s2 = new Student("Ravi"); System.out.println(s1.school); // ABC School System.out.println(s2.school); // ABC School } } 💡 Like a school name — same for every student! ⚙️ 2️⃣ Static Methods Called using class name (no need to create an object) Cannot use this or access non-static members directly class MathUtils { static int add(int a, int b) { return a + b; } } public class Main { public static void main(String[] args) { int sum = MathUtils.add(5, 10); // No object needed System.out.println(sum); } } 💡 Like using a calculator’s “Add” button — it works without creating a calculator object! 🧩 3️⃣ Static Blocks Run once when the class loads Used to initialize static variables class Config { static int maxUsers; static { maxUsers = 100; System.out.println("Static block executed!"); } } public class Main { public static void main(String[] args) { System.out.println(Config.maxUsers); } } 💡 Like setting up a system before starting work — it runs only once. 🧱 4️⃣ Static Nested Classes A class inside another class Does not need an instance of the outer class class Outer { static class Inner { void show() { System.out.println("Inside static nested class"); } } } public class Main { public static void main(String[] args) { Outer.Inner obj = new Outer.Inner(); obj.show(); } } 💡 Like a department inside a company — it can work independently. 🧠 Key Takeaway: Use static when something should stay common, shared, or utility-based — not tied to any one object. #Day9 #JavaLearning #StaticKeyword #JavaDeveloper #SpringBoot #BackendDevelopment #CodingJourney #StaticKeyword
To view or add a comment, sign in
-
🔹 1. What Is a Variable? A variable in Java is a name given to a memory location that stores a value. In simple terms — 🔹 A variable acts like a container or box that holds some data (like a number, text, or true/false value) which can be used and changed in the program. Example: int age = 21; Here: - int → data type (tells Java that the variable stores an integer value) - age → variable name (label for the memory location) - 21 → value stored in memory So, in memory it looks like: age → [ 21 ] 🔹2. Why We Use Variables Variables are used to: 1. Store information (like marks, name, price, etc.) 2. Reuse data multiple times in the program. 3. Make programs dynamic — we can change values during execution. 4. Perform calculations or make decisions based on stored data. 🔹3. Syntax of Variable Declaration : dataType variableName = value; 🔹Example : int number = 10; String name = "Vimala"; double salary = 25000.75; boolean isPassed = true; You can also declare first, assign later: int x; x = 20; 🔹4. Types of Variables in Java Java provides three main types of variables depending on where they are declared and how they behave. They are 1. Local Variables 2. Instance Variables 3. Static Variables 🔸 1. Local Variables - Declared inside a method, constructor, or block. - Created when the method is called and destroyed when it ends. - No default value (you must assign a value before using it). - Stored in the stack memory. 🔹Example : class Example { void display() { int a = 10; // Local variable System.out.println(a); } } 🔸 2. Instance Variables - Declared inside a class, but outside any method. - Each object gets its own copy of the variable. - Stored in heap memory. - Have default values. 🔹Example : class Student { int id; // Instance variable String name; // Instance variable } 🔹 When you create two objects: Student s1 = new Student(); Student s2 = new Student(); s1.id = 101; s2.id = 102; Each object (s1, s2) has its own copy of id. 🔸 3. Static Variables - Declared using the static keyword inside the class. - Shared by all objects of that class (only one copy exists). - Stored in the method area (part of memory). - Have default values. - Can be accessed using the class name directly. 🔹Example : class Student { int id; String name; static String college = "Amrita Sai"; // Static variable } 🔹5. Memory Representation of Variables public class Example { // Instance variable (Heap Memory) int instanceVar = 10; // Static variable (Method Area) static int staticVar = 20; public void method() { // Local variable (Stack Memory) int localVar = 30; System.out.println("Local Var: " + localVar); System.out.println("Instance Var: " + instanceVar); System.out.println("Static Var: " + staticVar); } public static void main(String[] args) { Example obj = new Example(); obj.method(); } #Java #Core java #Codegnan Anand Kumar Buddarapu Uppugundla Sairam Saketh Kallepu }
To view or add a comment, sign in
-
-
💡 Shallow Copy vs Deep Copy in Java — A Must-Know Concept for Every Developer. When working with objects in Java, we often need to copy one object’s data into another. But here’s the twist — not all copies are created equal! That’s where Shallow Copy and Deep Copy come in. Let’s break it down 👇 🧩 1️⃣ What is a Shallow Copy? A Shallow Copy copies only the top-level structure of an object. If the object contains references to other objects, those references are shared, not duplicated. In simple terms: A shallow copy creates a new object, but it still points to the same referenced objects as the original. 🧠 Key point: Changes made to referenced objects in one copy will reflect in the other. ✅ Example: class Student implements Cloneable { String name; Address address; Student(String name, Address address) { this.name = name; this.address = address; } public Object clone() throws CloneNotSupportedException { return super.clone(); // Shallow copy } } class Address { String city; Address(String city) { this.city = city; } } public class Main { public static void main(String[] args) throws CloneNotSupportedException { Address addr = new Address("Chennai"); Student s1 = new Student("Akash", addr); Student s2 = (Student) s1.clone(); s2.address.city = "Bangalore"; System.out.println(s1.address.city); // Output: Bangalore 😮 } } 👉 Here, both s1 and s2 share the same Address object — that’s why changing one affects the other. ⚙️ 2️⃣ What is a Deep Copy? A Deep Copy creates a completely independent clone of the object — including copies of all referenced objects. This means changes in one object do not affect the other. ✅ Example: class Student implements Cloneable { String name; Address address; Student(String name, Address address) { this.name = name; this.address = address; } public Object clone() throws CloneNotSupportedException { Address newAddress = new Address(address.city); // Cloning nested object return new Student(name, newAddress); // Deep copy } } class Address { String city; Address(String city) { this.city = city; } } Now if you change s2.address.city, s1.address.city remains the same — both are completely separate. 🚀 When to Use What? 🧩 Use Shallow Copy when your object contains only primitive fields or immutable objects. 🧠 Use Deep Copy when your object has mutable, nested references that should not be shared. 💬 Final Thoughts: Understanding Shallow Copy vs Deep Copy helps you avoid bugs, data leaks, and unexpected behavior — and it’s one of the most important interview questions for Java developers. 💪 #Java #Programming #ShallowCopy #DeepCopy #JavaDeveloper #Coding #SoftwareEngineering
To view or add a comment, sign in
-
"🚀Day 43 of 50 – Java LeetCode Challenge" Today’s challenge was "20. Valid Parentheses" — a fundamental stack-based problem that strengthens your understanding of bracket matching and data structure usage. The goal is to determine whether a given string of parentheses is valid based on correct opening and closing order. ⏱ Today’s Task – Valid Parentheses 📝 Problem Statement: Given a string s containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid. ✅ A string is valid if: 1️⃣ Every open bracket has a corresponding closing bracket of the same type. 2️⃣ Brackets are closed in the correct order. 3️⃣ Every close bracket must have an open bracket before it. 🧪 Examples: Input: s = "()" Output: true ✅ Input: s = "()[]{}" Output: true ✅ Input: s = "(]" Output: false ❌ Input: s = "([])" Output: true ✅ Input: s = "([)]" Output: false ❌ 🔧 Constraints: 1 <= s.length <= 10⁴ s consists of parentheses only '()[]{}' 💻 My Java Solution: import java.util.*; class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); Map<Character, Character> map = new HashMap<>(); map.put(')', '('); map.put('}', '{'); map.put(']', '['); for (char c : s.toCharArray()) { if (map.containsKey(c)) { char top = stack.isEmpty() ? '#' : stack.pop(); if (top != map.get(c)) return false; } else { stack.push(c); } } return stack.isEmpty(); } } 🔍 Takeaways: ✅ Efficient use of a stack for bracket matching ✅ Clean implementation using a HashMap for bracket pairs ✅ Time complexity O(n) — single traversal through the string ✅ Space complexity O(n) — in worst case (all open brackets) 💡 Core Concepts: Stack data structure HashMap for mapping bracket pairs Iterative traversal and validation Balanced parenthesis logic 🎯 Day 43 completed — 7 more to go! 🚀 #Java #50DaysOfCode #LeetCode #ProblemSolving #Stack #DataStructures #Day43 #JavaProgramming #CodeNewbie #LearnInPublic
To view or add a comment, sign in
-
-
Strings methods in Java 1️⃣ length() Definition: Returns the number of characters in a string (including spaces). 💡 Why it matters: Useful for checking input length (like passwords, usernames) or controlling loops. Example: String name = "Rakshitha"; System.out.println(name.length()); // Output: 9 2️⃣ charAt() Definition: Returns the character at a given index (index starts from 0). 💡 Why it matters: Helps to access or check specific characters, like the first letter of a name. Example: String word = "Java"; System.out.println(word.charAt(2)); // Output: v 3️⃣ toUpperCase() / toLowerCase() Definition: Converts all letters in a string to uppercase or lowercase. 💡 Why it matters: Useful for ignoring case in comparisons or displaying consistent text. Example: String text = "Java"; System.out.println(text.toUpperCase()); // JAVA System.out.println(text.toLowerCase()); // java 4️⃣ equals() / equalsIgnoreCase() Definition: equals() compares two strings exactly, while equalsIgnoreCase() ignores case differences. 💡 Why it matters: Used to compare user inputs like login IDs or names, case-sensitive or not. Example: String a = "Java"; String b = "java"; System.out.println(a.equals(b)); // false System.out.println(a.equalsIgnoreCase(b)); // true 5️⃣ contains() Definition: Checks if a string contains a certain sequence of characters. 💡 Why it matters: Used to search or validate text (like checking if an email contains “@”). Example: String email = "rakshitha@gmail.com"; System.out.println(email.contains("@gmail.com")); // true Awesome 👍 Here are the next 5 common String methods in Java — explained simply with definition, why it matters, and example 👇 6️⃣ substring() Definition: Extracts a part of the string between given start and end indexes. 💡 Why it matters: Used to get a specific portion of text, like extracting username from an email. Example: String word = "JavaDeveloper"; System.out.println(word.substring(0, 4)); // Output: Java 7️⃣ replace() Definition: Replaces all occurrences of a character or substring with another value. 💡 Why it matters: Useful for correcting text, filtering data, or formatting user input. Example: String text = "I love Java"; System.out.println(text.replace("Java", "Python")); // Output: I love Python 8️⃣ split() Definition: Splits a string into multiple parts based on a given delimiter and returns an array. 💡 Why it matters: Used to break text into pieces, such as splitting CSV data or words in a sentence. Example: String data = "apple,banana,grape"; String[] fruits = data.split(","); System.out.println(fruits[1]); // Output: banana 9️⃣ trim() Definition: Removes all leading and trailing spaces from a string. 💡 Why it matters: Essential for cleaning user input before saving or comparing values. Example: String name = " Rakshitha "; System.out.println(name.trim()); // Output: Rakshitha #Java #CoreJava #JavaProgramming #LearnJava #JavaDeveloper
To view or add a comment, sign in
-
BINARY SEARCH IN JAVA Binary Search is an efficient algorithm for finding an element within a sorted list or array. It operates by repeatedly dividing the search interval in half. ⚠️ Prerequisite: Sorted Data The single most important fact about Binary Search is that the array or list must be sorted (either ascending or descending) before the search can be performed. If the data isn't sorted, the algorithm will not work correctly. 💡 Divide and Conquer Strategy The algorithm follows a "divide and conquer" approach: Start: Define a search range using two pointers: start (first index) and end (last index). Middle: Calculate the mid index of the current range. Compare: Compare the target value with the value at mid. If they match, the search is complete. If the target is less than the mid value, the new search range becomes the left half (move end to mid - 1). If the target is greater than the mid value, the new search range becomes the right half (move start to mid + 1). Repeat: Repeat the process until the target is found or the start pointer crosses the end pointer. Time and Space Complexity Binary Search is known for its incredible speed on large data sets. Time Complexity: $\text{O}(\log n)$ The search interval is halved in every step. This means the maximum number of comparisons needed is related to the base-2 logarithm of the array size ($n$). For an array of $1,000,000$ elements, Binary Search takes a maximum of only 20 comparisons ($\log_2 1,000,000 \approx 19.93$). Best Case: $\text{O}(1)$ (Target is found on the first check at the exact middle). Worst Case: $\text{O}(\log n)$ (Target is at the end of the search, or not present). Space Complexity: $\text{O}(1)$ or $\text{O}(\log n)$ Iterative: $\text{O}(1)$ (Constant space is used for variables like start, end, and mid). Recursive: $\text{O}(\log n)$ (Space is used on the call stack due to the recursive function calls, which grow logarithmically with $n$). Important Note: Like the custom implementations, these utility methods require the array or list to be sorted before calling the binarySearch method. Return Value of Java API Methods The standard Java API methods return The index of the search key, if it is contained in the array. Otherwise, it returns (-(insertion point) - 1). The insertion point is the index where the key would be inserted into the array (or list): the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. This negative return value is a clever way to indicate not found, while also providing information about where the key should be placed to maintain the sort order. #Java #JavaFullStack #Programming #Binary Search #Codegnan Anand Kumar Buddarapu Uppugundla Sairam Saketh Kallepu
To view or add a comment, sign in
-
-
Record class in Java A record in Java is a special kind of class introduced to reduce boilerplate code when you need an immutable data carriers. Automatically generates: private final fields A canonical constructor equals(), hashCode() toString() accessor methods (getters without get prefix) --- Example: Traditional Employee Class (Before Java 14) public class Employee { private int id; private String name; private double salary; public Employee(int id, String name, double salary) { this.id = id; this.name = name; this.salary = salary; } public int getId() { return id; } public String getName() { return name; } public double getSalary() { return salary; } @Override public String toString() { return "Employee{id=" + id + ", name='" + name + "', salary=" + salary + "}"; } @Override public boolean equals(Object o) { // } @Override public int hashCode() { // } } . Too much boilerplate (getters, constructor, toString, equals, hashCode). --- Example: Employee Record (After Java 16) public record Employee(int id, String name, double salary) { } That’s it! Java automatically generates: Constructor Getters (id(), name(), salary()) equals(), hashCode() toString() --- Example usage: public class Main { public static void main(String[] args) { Employee emp = new Employee(101, "Sreenu", 55000); System.out.println(emp.name()); // Output: Sreenu System.out.println(emp); // Output: Employee[id=101, name=Sreenu, salary=55000.0] } } --- Canonical Constructor (Full Constructor) Records provide a canonical constructor automatically, but you can define it manually if you need validation: public record Employee(int id, String name, double salary) { public Employee { if (salary < 0) throw new IllegalArgumentException("Salary must be positive"); } } --- Compact Constructor Example public record Employee(int id, String name, double salary) { public Employee { if (name == null || name.isBlank()) { throw new IllegalArgumentException("Name cannot be blank"); } } } -- Entity Example (JPA) Usually, JPA entities are mutable, so records are not recommended for entities that Hibernate modifies. But you can use them as read-only projections: public record EmployeeEntity(Long id, String name, Double salary) { } Or use a traditional entity and record DTO for response. Example: @Entity @Table(name = "employees") public class EmployeeEntity { @Id private Long id; private String name; private Double salary; // getters, setters, constructors } Then convert it into DTO using record: public record EmployeeDTO(Long id, String name, Double salary) { } EmployeeDTO dto = new EmployeeDTO(entity.getId(), entity.getName(), entity.getSalary());
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