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
Rakshitha R’s Post
More Relevant Posts
-
hardcore Java internals! 🔥 --- Post 1: Java ka "Class Object" creation ka hidden process!🤯 ```java public class ObjectCreation { public static void main(String[] args) throws Exception { // Ye 3 steps mein hota hai: // 1. Class loading (ClassLoader) Class<?> clazz = Class.forName("java.lang.String"); // 2. Memory allocation (JVM) // 3. Constructor call (<init> method in bytecode) Object obj = clazz.newInstance(); System.out.println(obj.getClass()); // class java.lang.String } } ``` Secret: Har object creation 3 hidden steps mein hoti hai: 1. Loading → 2. Memory allocation → 3. Initialization 💀 --- Post 2: Java ka "Method Signature" internal encoding!🔥 ```java public class MethodSignature { public void show(int a, String b) { } public void show(String a, int b) { } // ✅ Valid - different signature } // Bytecode level par methods ka signature aisa dikhta hai: // show(I Ljava/lang/String;)V // show(Ljava/lang/String; I)V ``` Internal Encoding: · I = int · Ljava/lang/String; = String · V = void return type · Z = boolean · J = long 💡 --- Post 3: Java ka "Type Erasure" ka compiler magic!🚀 ```java import java.util.*; public class TypeErasure { public static void main(String[] args) { List<String> stringList = new ArrayList<>(); List<Integer> intList = new ArrayList<>(); System.out.println(stringList.getClass() == intList.getClass()); // true ✅ } } ``` Output: true Kyun? Compile time pe generics remove ho jate hain! Runtime pe donoArrayList hi hain! 💪 --- Post 4: Java ka "String Concatenation" internal optimization!🔮 ```java public class StringConcat { public static void main(String[] args) { String a = "Hello"; String b = "World"; String result1 = a + b; // StringBuilder use karta hai String result2 = a.concat(b); // Direct concat String result3 = "Hello" + "World"; // Compile time pe "HelloWorld" ban jata hai } } ``` Bytecode Analysis: · a + b → new StringBuilder().append(a).append(b).toString() · a.concat(b) → Direct string manipulation · Constant strings → Compile time pe resolve 💀
To view or add a comment, sign in
-
🚀 𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗝𝗮𝘃𝗮 𝗠𝗮𝗽 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲: 𝗛𝗮𝘀𝗵𝗠𝗮𝗽 𝘃𝘀 𝗟𝗶𝗻𝗸𝗲𝗱𝗛𝗮𝘀𝗵𝗠𝗮𝗽 𝘃𝘀 𝗧𝗿𝗲𝗲𝗠𝗮𝗽 𝘃𝘀 𝗛𝗮𝘀𝗵𝘁𝗮𝗯𝗹𝗲 If you’ve ever worked with key-value data in Java, the Map Interface is your go-to toolkit. It maps unique keys to specific values — just like storing names and phone numbers in your contacts list 📱. 𝗛𝗲𝗿𝗲’𝘀 𝗮 𝗾𝘂𝗶𝗰𝗸 𝗯𝗿𝗲𝗮𝗸𝗱𝗼𝘄𝗻: 🔹 𝗛𝗮𝘀𝗵𝗠𝗮𝗽: 𝘍𝘢𝘴𝘵𝘦𝘴𝘵, 𝘶𝘯𝘰𝘳𝘥𝘦𝘳𝘦𝘥, 𝘢𝘭𝘭𝘰𝘸𝘴 𝘰𝘯𝘦 𝘯𝘶𝘭𝘭 𝘬𝘦𝘺 — 𝘱𝘦𝘳𝘧𝘦𝘤𝘵 𝘧𝘰𝘳 𝘯𝘰𝘯-𝘵𝘩𝘳𝘦𝘢𝘥𝘦𝘥 𝘢𝘱𝘱𝘭𝘪𝘤𝘢𝘵𝘪𝘰𝘯𝘴. 🔹 𝗟𝗶𝗻𝗸𝗲𝗱𝗛𝗮𝘀𝗵𝗠𝗮𝗽: 𝘔𝘢𝘪𝘯𝘵𝘢𝘪𝘯𝘴 𝘪𝘯𝘴𝘦𝘳𝘵𝘪𝘰𝘯 𝘰𝘳𝘥𝘦𝘳 — 𝘨𝘳𝘦𝘢𝘵 𝘸𝘩𝘦𝘯 𝘰𝘳𝘥𝘦𝘳 𝘮𝘢𝘵𝘵𝘦𝘳𝘴. 🔹 𝗧𝗿𝗲𝗲𝗠𝗮𝗽: 𝘚𝘵𝘰𝘳𝘦𝘴 𝘬𝘦𝘺𝘴 𝘪𝘯 𝘴𝘰𝘳𝘵𝘦𝘥 (𝘢𝘴𝘤𝘦𝘯𝘥𝘪𝘯𝘨) 𝘰𝘳𝘥𝘦𝘳 — 𝘪𝘥𝘦𝘢𝘭 𝘧𝘰𝘳 𝘰𝘳𝘥𝘦𝘳𝘦𝘥 𝘥𝘢𝘵𝘢 𝘰𝘳 𝘳𝘢𝘯𝘨𝘦 𝘲𝘶𝘦𝘳𝘪𝘦𝘴. 🔹 𝗛𝗮𝘀𝗵𝘁𝗮𝗯𝗹𝗲: 𝘛𝘩𝘳𝘦𝘢𝘥-𝘴𝘢𝘧𝘦 𝘣𝘶𝘵 𝘰𝘭𝘥-𝘴𝘤𝘩𝘰𝘰𝘭 — 𝘳𝘦𝘱𝘭𝘢𝘤𝘦𝘥 𝘮𝘰𝘴𝘵𝘭𝘺 𝘣𝘺 𝘊𝘰𝘯𝘤𝘶𝘳𝘳𝘦𝘯𝘵𝘏𝘢𝘴𝘩𝘔𝘢𝘱. 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: import java.util.*; public class MapExample { public static void main(String[] args) { // 𝟭️⃣ 𝗛𝗮𝘀𝗵𝗠𝗮𝗽 - 𝗨𝗻𝗼𝗿𝗱𝗲𝗿𝗲𝗱, 𝗮𝗹𝗹𝗼𝘄𝘀 𝗼𝗻𝗲 𝗻𝘂𝗹𝗹 𝗸𝗲𝘆 Map<Integer, String> hashMap = new HashMap<>(); hashMap.put(3, "Sachin"); hashMap.put(1, "Amit"); hashMap.put(2, "Ravi"); hashMap.put(null, "Unknown"); // Allowed System.out.println("HashMap: " + hashMap); // 𝟮️⃣ 𝗟𝗶𝗻𝗸𝗲𝗱𝗛𝗮𝘀𝗵𝗠𝗮𝗽 - 𝗠𝗮𝗶𝗻𝘁𝗮𝗶𝗻𝘀 𝗶𝗻𝘀𝗲𝗿𝘁𝗶𝗼𝗻 𝗼𝗿𝗱𝗲𝗿 Map<Integer, String> linkedHashMap = new LinkedHashMap<>(); linkedHashMap.put(3, "Sachin"); linkedHashMap.put(1, "Amit"); linkedHashMap.put(2, "Ravi"); System.out.println("LinkedHashMap: " + linkedHashMap); // 𝟯️⃣ 𝗧𝗿𝗲𝗲𝗠𝗮𝗽 - 𝗦𝗼𝗿𝘁𝗲𝗱 𝗯𝘆 𝗸𝗲𝘆, 𝗻𝗼 𝗻𝘂𝗹𝗹 𝗮𝗹𝗹𝗼𝘄𝗲𝗱 Map<Integer, String> treeMap = new TreeMap<>(); treeMap.put(3, "Sachin"); treeMap.put(1, "Amit"); treeMap.put(2, "Ravi"); System.out.println("TreeMap: " + treeMap); // 𝟰️⃣ 𝗛𝗮𝘀𝗵𝘁𝗮𝗯𝗹𝗲 - 𝗧𝗵𝗿𝗲𝗮𝗱-𝘀𝗮𝗳𝗲 𝗯𝘂𝘁 𝗻𝗼 𝗻𝘂𝗹𝗹 𝗮𝗹𝗹𝗼𝘄𝗲𝗱 Map<Integer, String> hashtable = new Hashtable<>(); hashtable.put(3, "Sachin"); hashtable.put(1, "Amit"); hashtable.put(2, "Ravi"); System.out.println("Hashtable: " + hashtable); // 🔍 𝗜𝘁𝗲𝗿𝗮𝘁𝗶𝗻𝗴 𝗼𝘃𝗲𝗿 𝗮 𝗠𝗮𝗽 for (Map.Entry<Integer, String> entry : hashMap.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } } } 💡 𝗧𝗶𝗽: When you hear “𝗳𝗮𝘀𝘁 𝗹𝗼𝗼𝗸𝘂𝗽”, think HashMap. When you need 𝗼𝗿𝗱𝗲𝗿, think LinkedHashMap or TreeMap. When you need 𝘁𝗵𝗿𝗲𝗮𝗱 𝘀𝗮𝗳𝗲𝘁𝘆, go for ConcurrentHashMap. Understanding these differences helps you write cleaner, faster, and more scalable code 💪 #Java #HashMap #CollectionsFramework #LinkedHashMap #TreeMap #JavaInterviewPrep
To view or add a comment, sign in
-
🚀 Today I Deepened My Understanding of Strings in Java Today, I explored the differences between String, StringBuffer, and StringBuilder classes in Java — focusing on mutability, performance, and thread safety. 🔹 1️⃣ String (Immutable) Strings in Java are immutable — once created, they cannot be modified. Every modification creates a new String object. Thread-safe: Yes (due to immutability) Performance: Slower for frequent modifications Common Methods: length(), charAt(), substring(), toUpperCase(), toLowerCase(), equals(), equalsIgnoreCase(), indexOf(), startsWith(), endsWith(), replace(), split() 🔹 2️⃣ StringBuffer (Mutable & Thread-Safe) Used when frequent string modifications are required. Mutable: Can be modified without creating new objects. Thread-safe: Yes (methods are synchronized) Performance: Slower compared to StringBuilder due to synchronization overhead. Common Methods: append(), insert(), replace(), delete(), reverse(), capacity(), ensureCapacity(), setCharAt() 🔹 3️⃣ StringBuilder (Mutable & Non-Thread-Safe) Similar to StringBuffer, but not synchronized, hence faster. Thread-safe: No Best for: Single-threaded environments. Performance: Faster than StringBuffer Methods: Same as StringBuffer 🔹 4️⃣ Conversion Between Types Immutable → Mutable: StringBuffer sb = new StringBuffer(str); StringBuilder sbl = new StringBuilder(str); Mutable → Immutable: String str = sb.toString(); 🔹 5️⃣ String Tokenization I also explored string splitting techniques in Java: split() Method: Modern and efficient; uses regex. StringTokenizer Class: Older and slower; uses more memory. Example: String s = "Java is powerful"; String[] parts = s.split(" "); // Preferred modern approach import java.util.StringTokenizer; // StringTokenizer StringTokenizer st = new StringTokenizer("Java is powerful"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } 💡 Final Insight Understanding how Java handles string operations — from immutability to synchronization — is crucial for writing efficient and thread-safe code. #Java #LearningJourney #SoftwareDevelopment #StringHandling #CodingInJava #JavaDeveloper
To view or add a comment, sign in
-
-
Java ke atomic level ke secrets! 🔥 --- Post 1: Java ka "Class Loading" ka hidden hierarchy!🤯 ```java public class ClassLoaderSecrets { public static void main(String[] args) { ClassLoader loader = String.class.getClassLoader(); System.out.println(loader); // null ✅ // Kyun? Bootstrap ClassLoader C++ mein implemented hai // Java mein uska koi object nahi hota! } } ``` ClassLoader Hierarchy: 1. Bootstrap (C++ implementation) - null dikhata hai 2. Platform (Java 9+) - jdk.internal.loader.ClassLoaders$PlatformClassLoader 3. Application - sun.misc.Launcher$AppClassLoader Secret: Bootstrap ClassLoader Java mein visible nahi hota! 💀 --- Post 2: Java ka "Lambda Metafactory" internal magic!🔥 ```java public class LambdaSecrets { public static void main(String[] args) { Runnable r = () -> System.out.println("Lambda"); // Internally ye invokeDynamic instruction banata hai // LambdaMetafactory lambda class runtime pe generate karta hai! } } ``` Bytecode Level: ``` invokedynamic #2, 0 // LambdaMetafactory.metafactory() call ``` Internal Process: 1. invokedynamic instruction 2. LambdaMetafactory call 3. Runtime pe synthetic class generation 4. Method handle return 💡 --- Post 3: Java ka "String Deduplication" G1GC feature!🚀 ```java public class StringDedup { public static void main(String[] args) { // G1GC automatically duplicate strings ko same memory point kar deta hai char[] data = {'J', 'a', 'v', 'a'}; String s1 = new String(data); String s2 = new String(data); // G1GC intern() ki tarah same char[] point kar sakta hai! } } ``` JVM Option: ``` -XX:+UseG1GC -XX:+UseStringDeduplication ``` Secret: G1GC duplicate strings ko automatically optimize karta hai! 💪 --- Post 4: Java ka "Stack Walking" internal API!🔮 ```java public class StackWalkSecrets { public static void main(String[] args) { StackWalker walker = StackWalker.getInstance(); walker.forEach(frame -> { System.out.println(frame.getClassName() + "." + frame.getMethodName()); }); } } ``` Internal Stack Frame Structure: · Method name · Class name · Line number · Bytecode index Performance: StackWalker traditionalStackTrace se 10x faster hai! 💀
To view or add a comment, sign in
-
In Java, there are several ways to create and run threads, Spring Boot also have @Async annotation to run method code as thread. 1. Extending the Thread class You can create a subclass of Thread and override the run() method. ✅ Example: class MyThread extends Thread { @Override public void run() { System.out.println("Thread running " + Thread.currentThread().getName()); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); } } 🧩 2. Implementing the Runnable interface ✅ Example: class MyRunnable implements Runnable { @Override public void run() { System.out.println("Thread running using Runnable interface: " + Thread.currentThread().getName()); } } public class Main { public static void main(String[] args) { Thread t1 = new Thread(new MyRunnable()); t1.start(); } } 🟢 Why preferred: Allows you to extend another class (since Java supports only single inheritance). ⚡ 3. Using Anonymous Class You can create and start a thread in one line using an anonymous inner class. ✅ Example: public class Main { public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { @Override public void run() { System.out.println("Thread running using Anonymous class"); } }); t1.start(); } } 💡 4. Using Lambda Expression (Java 8+) ✅ Example: public class Main { public static void main(String[] args) { Thread t1 = new Thread(() -> { System.out.println("Thread running using Lambda expression"); }); t1.start(); } } ⚙️ 5. Using ExecutorService (Thread Pool) For multiple or managed threads, use an Executor Service. ✅ Example: import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> System.out.println("Thread 1 using ExecutorService")); executor.submit(() -> System.out.println("Thread 2 using ExecutorService")); executor.shutdown(); } } 🟢 Advantages: Reuses threads (avoids overhead of creating new threads repeatedly) Supports async tasks and better error handling 🧠 6. Using Callable and Future (for return values) Callable is like Runnable, but can return a value and throw exceptions. ✅ Example: import java.util.concurrent.*; public class Main { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<String> task = () -> { return "Result from thread: " + Thread.currentThread().getName(); }; Future<String> future = executor.submit(task); System.out.println(future.get()); executor.shutdown(); } }
To view or add a comment, sign in
-
Strings in Java Concept: A String in Java is a sequence of characters enclosed within double quotes (" "). It’s not a primitive data type, but a class in the java.lang package — meaning every string in Java is actually an object. Example: String name = "Rakshitha"; Java provides three main classes to handle string-related operations: 1. String – Immutable (cannot be changed after creation). 2. StringBuilder – Mutable and faster (not thread-safe). 3. StringBuffer – Mutable and thread-safe (used in multithreaded programs). 💡 Why it matters: Strings are everywhere in Java programs — from user input and file handling to API calls and database operations. They are used in: 📱 User interfaces (displaying messages) 🌐 Web development (handling form data, URLs) 🧩 Backend systems (storing names, IDs, JSON) 🧠 Data processing (parsing text, logs) Efficient string handling improves memory performance and speed of your applications. Example / Snippet: 1️⃣ String (Immutable) public class StringExample { public static void main(String[] args) { String s1 = "Java"; String s2 = s1.concat(" Programming"); System.out.println(s1); // Output: Java System.out.println(s2); // Output: Java Programming } } Here, s1 remains unchanged. Instead, a new String object (s2) is created — this is called immutability. 2️⃣ StringBuilder (Mutable and Fast) public class StringBuilderExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Java"); sb.append(" Developer"); System.out.println(sb); // Output: Java Developer } } Use StringBuilder when you need to modify strings frequently, such as building dynamic SQL queries or large text outputs. 3️⃣ StringBuffer (Mutable and Thread-safe) public class StringBufferExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Core"); sb.append(" Java"); System.out.println(sb); // Output: Core Java } } StringBuffer is synchronized, making it safe to use in multi-threaded environments. #Java #CoreJava #StringInJava #JavaProgramming #LearnJava #StringBuilder #StringBuffer #JavaDeveloper #CodingInJava #TechLearning #SoftwareDevelopment #ProgrammingBasics #CodingJourney
To view or add a comment, sign in
-
ArrayList(C)(1.2V): ============ Java Array List class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package. ArrayList is dynamic data structure in which you can add or remove any number of elements. The important points about Java ArrayList class are: ================================== 1. Java ArrayList class can contain duplicate elements. 2. Java ArrayList class maintains insertion order. 3. Not Synchronized: Array-List is not thread-safe. Multiple thread can be access. 4. Java ArrayList allows random access because array works at the index basis. 5. In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list. 6. We can not create an array list of the primitive types, such as int, float, char, etc. It is required to use the wrapper class in such cases. For example: ArrayList<int> al = ArrayList<int>(); // does not work ArrayList<Integer> al = new ArrayList<Integer>(); // works fine Note: Java new generic collection allows you to have only one type of object in a collection. Now it is type safe so typecasting is not required at runtime. Advantages of ArrayList: ================ 1. Dynamic Sizing: You don't need to specify the size in advance, and it can grow or shrink dynamically. 2. Indexed Access: Fast access to elements by index, making it ideal for situations where you need to access or modify elements frequently. 3. Supports Duplicates: Can store duplicate elements, unlike Set. 4. Flexibility: It is part of the Collections Framework, so you can easily use it with other collections and utilities (like sorting, searching, etc.). 5. ArrayList is the best choice if our frequent operation is retrieval. Disadvantages of ArrayList: ================= 1. Not Synchronized: ArrayList is not thread-safe by default, so it's not suitable for concurrent modifications by multiple threads. 2. Performance: Inserting or removing elements in the middle or beginning of an ArrayList is slow because it involves shifting elements. 3. Memory Consumption: It may consume more memory than other collections, especially when there are fewer elements than the allocated capacity. 4. ArrayList is the worst choice if our frequent operation is insertion (or) deletion in the middle because it requires several internal shift operations. #InterviewExperience #Java #SpringBoot #BackendDevelopment #Core Java #Basic Concept
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
-
Java ke atomic level ke secrets! 🔥 --- Post 1: Java ka "Multi-Release JAR" ka hidden feature!🤯 ```java // Java 8 version - base code public class TimeUtils { public static String getTime() { return "Legacy time: " + new Date(); } } // Java 11 version - META-INF/versions/11/TimeUtils.java public class TimeUtils { public static String getTime() { return "Modern time: " + Instant.now(); } } ``` Secret: Ek hi JAR mein multiple Java versions ke liye alag-alag class files ho sakti hain!💀 --- Post 2: Java ka "ConstantDynamic" - invokedynamic for constants!🔥 ```java public class ConstantDynamic { // Java 11+ mein constants bhi dynamically resolve ho sakte hain public static final String DYNAMIC_CONSTANT = ConstantDescs.of("Dynamically resolved constant"); // Bytecode level par invokedynamic use karta hai // instead of constant pool entry! } ``` Internal Magic: · Traditional: Constant Pool → LDC instruction · New: ConstantDynamic → invokedynamic instruction · Dynamic constant resolution at runtime! 💡 --- Post 3: Java ka "Vector API" - SIMD operations ka raaz!🚀 ```java import jdk.incubator.vector.*; public class VectorMagic { public static void main(String[] args) { IntVector a = IntVector.fromArray(IntVector.SPECIES_256, new int[]{1,2,3,4,5,6,7,8}, 0); IntVector b = IntVector.fromArray(IntVector.SPECIES_256, new int[]{8,7,6,5,4,3,2,1}, 0); IntVector result = a.add(b); // ✅ 8 operations ek saath! // CPU level par SIMD instructions use karta hai } } ``` Performance: 10x faster for mathematical operations!💪 --- Post 4: Java ka "Heap Allocation" ka hidden alternative!🔮 ```java import java.lang.foreign.*; public class OffHeapMagic { public static void main(String[] args) { // Heap se bahar memory allocate karo! try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(100); // Direct OS memory access - no GC overhead! segment.set(ValueLayout.JAVA_INT, 0, 42); int value = segment.get(ValueLayout.JAVA_INT, 0); } } } ``` Benefits: · Zero GC pressure · Direct memory access · C-like performance 💀 --- Bhai, yeh features toh aane wali Java generations ke liye hain! 😎
To view or add a comment, sign in
-
#Java #java8 1) Intermediate operation. Stream API methods in Java 1. Filtering & Slicing filter(Predicate) – Keeps only elements matching a condition. list.stream().filter(n -> n % 2 == 0).collect(Collectors.toList()); distinct() – Removes duplicates. limit(long maxSize) – Limits the stream to first n elements. skip(long n) – Skips first n elements. --- 2. Mapping & Transforming map(Function) – Transforms each element. list.stream().map(String::toUpperCase).collect(Collectors.toList()); mapToInt, mapToDouble, mapToLong – Maps to primitive streams. flatMap(Function) – Flattens nested structures. listOfLists.stream().flatMap(List::stream).collect(Collectors.toList()); --- 3. Sorting sorted() – Sorts in natural order. list.stream().sorted().collect(Collectors.toList()); sorted(Comparator) – Sorts with custom comparator. list.stream().sorted((a, b) -> b - a).collect(Collectors.toList()); --- 4. Matching & Finding anyMatch(Predicate) – True if any element matches. allMatch(Predicate) – True if all elements match. noneMatch(Predicate) – True if no element matches. findFirst() – Returns first element (optional). findAny() – Returns any element (optional, useful in parallel streams). --- 5. Peeking & Iterating peek(Consumer) – Performs an action on each element (mostly for debugging). list.stream().peek(System.out::println).collect(Collectors.toList()); forEach(Consumer) – Terminal operation to process elements. --- 6. Reducing & Collecting reduce(BinaryOperator) – Combines elements into one. int sum = list.stream().reduce(0, Integer::sum); collect(Collectors.toList()) – Converts stream to list. collect(Collectors.toSet()) – Converts stream to set. collect(Collectors.joining(", ")) – Concatenates strings. collect(Collectors.groupingBy(Function)) – Groups elements by a key. collect(Collectors.partitioningBy(Predicate)) – Splits stream into two groups. --- 7. Other Useful Methods count() – Returns number of elements. min(Comparator) / max(Comparator) – Finds min/max element. toArray() – Converts stream to array. --- ✅ Tips for Intermediate Usage Combine methods for complex queries: list.stream() .filter(n -> n % 2 == 0) .sorted() .map(n -> n * 2) .collect(Collectors.toList()); Use parallelStream() for large datasets. Use peek() for debugging pipelines without altering the stream.
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