☕ Day 13 of my “Java from Scratch” Series – “Unary Operators in Java” Unary operators are the ones that work on a single operand (variable). They’re used to change the sign, increase/decrease a value, or reverse a boolean condition. 1️⃣ +a 2️⃣ -a → if a = 5, -a will be -5 3️⃣ ! → if a = true, !a will be false 4️⃣ Increment operator (++) → increases the value by 1. a. Post increment: first the operation will be performed and then the value will be increased. 📘 Example: int a = 20; int b = a++; ✅ Result: b = 20, a = 21 b. Pre increment: first the value will be increased and then the operation will be performed. 📘 Example: int a = 20; int b = ++a; ✅ Result: a = 21, b = 21 5️⃣ Decrement operator (--) → decreases the value by 1. a. Post decrement: first the operation will be performed and then the value will be decremented. 📘 Example: int a = 20; int b = a--; ✅ Result: b = 20, a = 19 b. Pre decrement: first the value will be decremented and then the operation will be performed. 📘 Example: int a = 20; int b = --a; ✅ Result: a = 19, b = 19 💡 In short: Unary operators act on one operand to either change its value or its sign. 👉 Which one do you find tricky — pre or post increment? Comment below 👇 #Java #Programming #Coding #Tech #JavaDeveloper #SoftwareEngineering #Learning #Developers #UnaryOperatorsInJava #JavaFromScratch #NeverGiveUp
"Unary Operators in Java: Understanding the Basics"
More Relevant Posts
-
💥 Java Gotcha Alert! 💥 Ever tried removing items from an ArrayList while looping... and BOOM – ConcurrentModificationException? 😱 You're not alone – it's a classic trap! Let's fix it forever. 🚀 #Code List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c")); for (String s : list) { if (s.equals("b")) { list.remove(s); // 💥 CRASH! } } Why? For-each loops use a fail-fast iterator. It detects changes (like remove()) and throws an exception to prevent bugs. 🛠️ EASY FIXES (Pick your favorite!) : 1️⃣ Super Simple: removeIf() (Java 8+) ⭐ list.removeIf(s -> s.equals("b")); // ✅ [a, c] 2️⃣ Iterator Magic Iterator<String> it = list.iterator(); while (it.hasNext()) { if (it.next().equals("b")) { it.remove(); // ✅ Safe! } } **🎯 PRO TIPS** ✅ **Always** use these over direct `remove()` in loops. 🔒 Multi-threaded? Switch to `CopyOnWriteArrayList`. 💡 Collect to-remove items → `removeAll()` for complex cases. #Java #Programming #CodingTips #SoftwareDevelopment #Tech #JavaProgramming #SoftwareEngineering #Coding #Developer #TechTips #ProgrammingLife #CodeNewbie #LearnToCode #JavaDeveloper #BackendDevelopment #CodingCommunity #TechTutorials #SoftwareDev #ProgrammingTutorials #CodeLife #TechCareer #DeveloperLife #JavaCode #LearnProgramming
To view or add a comment, sign in
-
☕ Day 11 of my “Java from Scratch” Series – "Assignment Operators in Java". In Java, Assignment Operators are used to assign values to variables. We can assign values directly or perform operations and assign them in short form. 1. 🔹 = (Simple Assignment) Assigns a value to a variable. 📘 Example: int a = 5; int b = a; Here, the value 5 is assigned to a, and the value of a is assigned to b. 2. 🔹 += (Add and Assign) Short way to write a = a + value 📘 Example: int a = 3; a += 3; ✅ Result: a = 3 + 3 => a = 6 3. 🔹 -= (Subtract and Assign) Short way to write a = a - value 📘 Example: int a = 10; a -= 3; ✅ Result: a = 10 - 3 => a = 7 4. 🔹 *= (Multiply and Assign) Short way to write a = a * value 📘 Example: int a = 10; a *= 3; ✅ Result: a = 10 * 3 => a = 30 5. 🔹 /= (Divide and Assign) Short way to write a = a / value 📘 Example: int a = 10; a /= 5; ✅ Result: a = 10 / 5 => a = 2 (Quotient) 6. 🔹 %= (Modulo and Assign) Short way to write a = a % value 📘 Example: int a = 10; a %= 5; ✅ Result: a = 10 % 5 => a = 0 (Remainder) 💡 In short: Assignment operators make your code cleaner, shorter, and easier to read. 👉 Which assignment operator do you use most often in your code? Comment below! 👇 #Java #Programming #Coding #JavaDeveloper #Learning #SoftwareEngineering #JavaFromScratch #InterviewQuestions #Developers #AssignmentOperatorsInJava #Tech #NeverGiveUp
To view or add a comment, sign in
-
I am sharing about Java Exception and Error I hope it's help full to everyone 😊 Mastering Java means mastering its Exception hierarchy In Java, everything starts from Object → Throwable. From there, Java divides problems into two types: Exceptions – things you can handle in your code. Errors – things you can’t control, like JVM crashes or memory overflow. Understanding this hierarchy helps in writing robust, error-free, and debug-friendly code 💻 #Java #Coding #Exceptions #Developers 🚀 “Before you debug, understand what can go wrong — Java Exception Hierarchy explained!” 🧠 “Understanding Throwable: The root of all Exceptions & Errors in Java!” The entire Throwable family explained — from Exception to Error, including RuntimeException types like: ArithmeticException NullPointerException IndexOutOfBoundException #JavaLearning #CSStudent #ProgrammingBasics #ScalerTopics ⚙️ “Code smart, handle errors smarter — Java’s Exception System simplified!” 👨💻 “From Throwable to Runtime — every Java developer should know this tree!” A clear understanding of Java’s Exception hierarchy helps you write cleaner and more reliable code. Exception → recoverable Error → unrecoverable #Java #Coding #ExceptionHandling #Developers #TechLearning
To view or add a comment, sign in
-
-
🚀 String Concatenation: + operator vs. StringBuilder (Java) While the `+` operator can be used for string concatenation in Java, using `StringBuilder` is generally more efficient, especially when performing multiple concatenations. The `+` operator creates a new String object for each concatenation, which can lead to performance overhead. `StringBuilder`, on the other hand, modifies the string in place, avoiding the creation of unnecessary objects. For complex string manipulations, `StringBuilder` provides methods like `append()`, `insert()`, and `delete()`. 💪 Build skills, build wealth, build your future! 📖 Learn at your own pace — 10,000+ concepts, 4,000+ articles, 12,000+ quizzes. AI-guided learning! 🎓 Get started: https://lnkd.in/gefySfsc 🔗 Check it out: https://techielearn.in #Java #JavaDev #OOP #Backend #professional #career #development
To view or add a comment, sign in
-
-
🚀 Are you ready to elevate your Java skills? Let’s dive into a tricky question that often stumps even seasoned developers: What’s the difference between `==` and `.equals()` in Java? 🤔 While `==` checks for reference equality (are they the same object in memory?), `.equals()` checks for value equality (do they represent the same value?). Here’s why this matters: Reference vs. Value : Using `==` on objects can lead to unexpected results. For instance, two different instances of a class with the same data will return `false` with `==`, but `true` with `.equals()`. Custom Implementations: When you create your own classes, overriding `.equals()` is crucial for collections like `HashSet` and `HashMap` to function correctly. Understanding these nuances can significantly improve your code quality and debugging skills. 💡 Now it’s your turn! Share your experiences with `==` vs. `.equals()` in the comments below. Have you encountered any pitfalls? Let’s learn together! #Java #Programming #Developers #TechCommunity
To view or add a comment, sign in
-
🚀 Constructors (Java) A constructor is a special method in a class that is automatically called when an object of that class is created. Its purpose is to initialize the object's state, setting initial values for its attributes. Constructors have the same name as the class and do not have a return type. If you don't define a constructor, Java provides a default constructor with no arguments. Constructors ensure that objects are properly initialized before they are used. #Java #JavaDev #OOP #Backend #professional #career #development
To view or add a comment, sign in
-
-
“NullPointerExceptions are the silent killers in Java apps and Optional is your shield!” In Java, trying to access a method or property of a null object leads to the dreaded NullPointerException (NPE) , one of the most common runtime errors developers face. Traditionally, we handle this with endless if-null checks scattered across our codebase which quickly makes it messy and hard to maintain. That’s where Optional comes in. It’s a container object that may or may not hold a non null value, encouraging explicit handling of nulls and making code cleaner and safer. Here are some key methods worth knowing 👇 Optional.of(value) → value must not be null, or it throws an exception Optional.ofNullable(value) → value can be null Optional.isPresent() → checks if value exists Optional.ifPresent(consumer) → executes action if value exists Optional.orElse(defaultValue) → provides a default if value is null Optional .map () → transforms the value if present 🧩 Example without Optional: User user = userService.findUserById(1); if (user != null && user.getEmail() != null) { System.out.println(user.getEmail().toLowerCase()); } else { System.out.println("Email not available"); } Too many null checks , not elegant, right? ✅ Example with Optional: Optional<User> optionalUser = Optional.ofNullable(userService.findUserById(1)); String email = optionalUser .map(User::getEmail) .map(String::toLowerCase) .orElse("Email not available"); System.out.println(email); Much cleaner, more readable, and no NPEs! Do you use Optional in your projects? How do you handle nulls in Java? #Java #JavaDeveloper #SpringBoot #BackendDevelopment #CleanCode #CodingTips #SoftwareDevelopment #Programming #TechLearning #JavaTips #CodeBetter #DevCommunity #ProgrammingLife
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