From a9f8fa7ea48fdb4ac73a4218cacfc44732ee9554 Mon Sep 17 00:00:00 2001 From: Suraj Sadhula Date: Sun, 6 Apr 2025 19:50:47 +0530 Subject: [PATCH] [Suraj] Few Java tips that I found useful/helpful in day-to-day work. --- tips/javaTips.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 tips/javaTips.md diff --git a/tips/javaTips.md b/tips/javaTips.md new file mode 100644 index 0000000..5f42979 --- /dev/null +++ b/tips/javaTips.md @@ -0,0 +1,35 @@ +Useful Java Tips + +1. String.join() +When you need to concatenate collections or arrays with a delimiter, 'String.join()' makes the task simple and clean—similar to '.join' in Python. +Example: + +List words = Arrays.asList("Java", "Spring", "React"); +String result = String.join(", ", words); +System.out.println(result); // Output: Java, Spring, React + +Great for handling strings without manual loops or conditional checks. + +---------------------------- + +2. 'var' in Java +Java 10 introduced 'var' for compile-time type inference. Unlike Python’s dynamic typing, 'var' relies on the compiler to infer the type from the assignment. +Example: +var name = "Leetcode"; // inferred as a String + +In Python, +x = 10 //int +x = "Hello" //now str +But Java’s 'var' is not like this— it’s type-safe. + +**Best Practices**: +-> We can use 'var' when the type is obvious from the right hand side. + Example: + for (var entry : map.entrySet()) { + System.out.println(entry.getKey() + " -> " + entry.getValue()); + } + +-> Avoid using 'var' when the type is ambiguous, as it may hurt readability. + +Not recommended +var data = getData(); //what kind of data type?