🚀 Java Series – Day 4 📌 Control Statements in Java (if, switch, loops) 🔹 What is it? Control statements are used to control the flow of execution in a Java program. They allow the program to make decisions and repeat actions based on conditions. Java mainly provides three types of control statements: • if / else – used for decision making • switch – used to select one case from multiple options • loops – used to execute a block of code repeatedly (for, while, do-while) 🔹 Why do we use it? Control statements help programs behave dynamically based on conditions. For example: In a login system, an if statement can check whether the username and password are correct. In a menu-based application, a switch statement can handle different user choices. Loops are useful when we need to repeat tasks, like processing multiple records or displaying lists. 🔹 Example: public class Main { public static void main(String[] args) { int number = 5; // if statement if(number > 0){ System.out.println("Number is positive"); } // switch statement switch(number){ case 1: System.out.println("One"); break; case 5: System.out.println("Five"); break; default: System.out.println("Other number"); } // loop example for(int i = 1; i <= 3; i++){ System.out.println("Iteration: " + i); } } } 💡 Key Takeaway: Control statements allow Java programs to make decisions and execute code efficiently based on conditions. What do you think about this? 👇 #Java #CoreJava #JavaDeveloper #Programming #BackendDevelopment
Java Control Statements: if, switch, Loops
More Relevant Posts
-
🚀 Java Series – Day 22 📌 Collection Framework in Java (List, Set, Map) 🔹 What is it? The Collection Framework in Java is a set of classes and interfaces used to store and manipulate groups of objects efficiently. It provides ready-made data structures to simplify development. Main parts: • List • Set • Map 🔹 Why do we use it? It helps manage large amounts of data easily with built-in methods like sorting, searching, and iteration. For example: In an e-commerce app, we can store: • Product list → List • Unique categories → Set • Product ID & details → Map 🔹 List vs Set vs Map: • List - Ordered collection - Allows duplicates - Example: ArrayList, LinkedList • Set - Unordered collection - No duplicates allowed - Example: HashSet, TreeSet • Map - Stores key-value pairs - Keys are unique - Example: HashMap, TreeMap 🔹 Example: import java.util.*; public class Main { public static void main(String[] args) { // List List<String> list = new ArrayList<>(); list.add("Apple"); list.add("Apple"); // duplicates allowed // Set Set<String> set = new HashSet<>(); set.add("Apple"); set.add("Apple"); // ignored // Map Map<Integer, String> map = new HashMap<>(); map.put(1, "Apple"); map.put(2, "Banana"); System.out.println(list); System.out.println(set); System.out.println(map); } } 💡 Key Takeaway: Use List for ordered data, Set for unique data, and Map for key-value pairs. What do you think about this? 👇 #Java #Collections #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
📌 TOPIC: Optional Class in Java (Java 8) The Optional class (from java.util) is used to avoid NullPointerException and handle missing values safely. 👉 Instead of using null, we use Optional to represent a value that may or may not be present. 🔸 Why use Optional? 1️⃣ Prevents NullPointerException 2️⃣ Makes code more readable 3️⃣ Forces proper handling of missing values 🔸 Creating Optional Objects import java.util.Optional; Optional<String> opt1 = Optional.of("Hello"); // value must not be null Optional<String> opt2 = Optional.ofNullable(null); // can be null Optional<String> opt3 = Optional.empty(); // empty Optional 🔸 Common Methods ✔️ isPresent() & get() Optional<String> name = Optional.of("Java"); if(name.isPresent()) { System.out.println(name.get()); } ✔️ orElse() Optional<String> name = Optional.ofNullable(null); System.out.println(name.orElse("Default Value")); 👉 Output: Default Value ✔️ ifPresent() Optional<String> name = Optional.of("Java"); name.ifPresent(n -> System.out.println(n)); Key Insight: Optional helps write cleaner and safer code by reducing direct null checks and preventing runtime errors. #Java #Optional #Java8 #Programming #Codegnan #LearningJourney #Developers My gratitude towards my mentor #AnandKumarBuddarapu #SakethKallepu #UppugundlaSairam
To view or add a comment, sign in
-
-
🚀 Java Series – Day 15 📌 Exception Handling in Java (try-catch-finally & Checked vs Unchecked) 🔹 What is it? Exception Handling in Java is used to handle runtime errors so that the program can continue executing smoothly. Java provides keywords to handle exceptions: • try – Code that may cause an exception • catch – Handles the exception • finally – Always executes (used for cleanup) 🔹 Why do we use it? Exception handling helps prevent program crashes and ensures better user experience. For example: In a file upload system, if a file is not found or an error occurs, instead of crashing, the program can show a proper error message and continue execution. Also, Java classifies exceptions into: • Checked Exceptions – Checked at compile time (e.g., IOException) • Unchecked Exceptions – Occur at runtime (e.g., NullPointerException, ArithmeticException) 🔹 Example: public class Main { public static void main(String[] args) { try { int result = 10 / 0; // Exception } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Execution completed"); } } } 💡 Key Takeaway: Exception handling ensures robust and crash-free applications by managing errors effectively. What do you think about this? 👇 #Java #ExceptionHandling #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
Building Native Image for a Java application requires configuration of reflection, proxies, and other dynamic Java mechanisms. But why is this necessary if the JVM handles all of this automatically? To answer that, we need to look at the differences between static and dynamic compilation in Java. https://lnkd.in/eVyGYHZk
To view or add a comment, sign in
-
🚀 Java Series – Day 7 📌 Strings in Java (Immutable Concept & String vs StringBuilder) 🔹 What is it? A String in Java is a sequence of characters used to represent text. One important concept about Strings is that they are immutable, meaning once a String object is created, its value cannot be changed. If we modify a String, Java actually creates a new object in memory instead of changing the existing one. 🔹 Why do we use it? Strings are widely used to handle text data such as usernames, messages, file names, or product descriptions. However, when we perform many modifications, creating new String objects repeatedly can affect performance. In such cases, Java provides StringBuilder, which allows mutable strings (values can be modified without creating new objects). 🔹 Example: public class Main { public static void main(String[] args) { // String (Immutable) String text = "Hello"; text = text + " Java"; // Creates a new String object // StringBuilder (Mutable) StringBuilder builder = new StringBuilder("Hello"); builder.append(" Java"); // Modifies the same object System.out.println(text); System.out.println(builder); } } 💡 Key Takeaway: Use String for simple text handling, but prefer StringBuilder when performing multiple modifications for better performance. What do you think about this? 👇 #Java #CoreJava #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
Day - 28 : Set in Java In Java, the Set interface is a part of the Java Collection Framework, located in the java.util package. It represents a collection of unique elements, meaning it does not allow duplicate values. 1) The set interface does not allow duplicate elements. 2) It can contain at most one null value except TreeSet implementation which does not allow null. 3)The set interface provides efficient search, insertion, and deletion operations. ● Example : import java.util.HashSet; import java.util.Set; public class java { public static void main(String args[]) { Set<String> s = new HashSet<>( ); System.out.println("Set Elements: " + s); } } ● Classes that implement the Set interface a) HashSet: A set that stores unique elements without any specific order, using a hash table and allows one null element. b) EnumSet : A high-performance set designed specifically for enum types, where all elements must belong to the same enum. c) LinkedHashSet: A set that maintains the order of insertion while storing unique elements. d) TreeSet: A set that stores unique elements in sorted order, either by natural ordering or a specified comparator. #Java #JavaProgramming #TreeMap #JavaDeveloper #Programming #Coding #SoftwareDevelopment #LearnJava #JavaLearning #BackendDevelopment EchoBrains
To view or add a comment, sign in
-
-
☄️🎊Day 67 of 90 – Java Backend Development 🎆 🧨 In Java, immutability means that once a String object is created, its value cannot be changed. If you try to "modify" a string—for example, by appending text—Java actually creates a brand-new string object in memory rather than altering the original one. This design choice wasn't accidental; it’s a foundational pillar of how Java handles memory, security, and performance. 👉 Core Reasons for Immutability 👉 1. The String Constant Pool Java uses a special memory area called the String Pool. When you create a string literal, the JVM checks if that value already exists in the pool. If it does, it returns a reference to the existing object instead of creating a new one. If strings were mutable, changing the value of one variable would secretly change the value for every other variable pointing to that same literal, leading to unpredictable bugs. 👉 2. Security Strings are used heavily in sensitive areas of Java programming, such as: Database URLs and credentials. Network connections. File paths. Class loading. If a string were mutable, an untrusted piece of code could receive a reference to a file path, verify it has permission, and then sneakily change the path before the file is actually opened. Immutability ensures that once a value is validated, it stays that way. 👉 3. Thread Safety Because a String cannot change, it is inherently thread-safe. You can share a single string across multiple threads without worrying about synchronization or data corruption. This significantly simplifies concurrent programming in Java. 👉 4. Caching HashCodes In Java, strings are frequently used as keys in HashMap or elements in HashSet. The hashCode() of a string is calculated and cached the first time it's called. Since the string is immutable, the hash code will never change. This makes lookups in collections incredibly fast, as the JVM doesn't have to re-calculate the hash every time the string is accessed. #String #Immutability #HashCodes
To view or add a comment, sign in
-
-
🚀 Java Series – Day 19 📌 Multithreading in Java (Thread vs Runnable) 🔹 What is it? Multithreading is a process of executing multiple threads simultaneously to perform tasks efficiently. A thread is a lightweight unit of execution within a program. Java provides two main ways to create threads: • Extending the Thread class • Implementing the Runnable interface 🔹 Why do we use it? Multithreading helps improve performance and responsiveness. For example: In a web application, one thread can handle user requests while another processes background tasks like data saving or logging. 🔹 Thread vs Runnable: • Thread Class - Extend "Thread" - Less flexible (Java doesn’t support multiple inheritance) • Runnable Interface - Implement "Runnable" - More flexible (can extend another class) - Preferred approach in real-world applications 🔹 Example: // Using Thread class MyThread extends Thread { public void run() { System.out.println("Thread using Thread class"); } } // Using Runnable class MyRunnable implements Runnable { public void run() { System.out.println("Thread using Runnable"); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); Thread t2 = new Thread(new MyRunnable()); t2.start(); } } 💡 Key Takeaway: Use Runnable for better flexibility and scalability in multithreaded applications. What do you think about this? 👇 #Java #Multithreading #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
🚀Java Tip Java Tip: Use Optional to avoid NullPointerException One of the most common issues developers face in Java applications is the NullPointerException. Java 8 introduced the Optional class to help handle null values more safely and clearly. Instead of directly working with possible null values, Optional provides a container that may or may not contain a value. 🔹 Example without Optional User user = getUser(); String name = user.getName(); // May throw NullPointerException 🔹 Example using Optional Optional<User> user = getUser(); String name = user.map(User::getName).orElse("Default User"); 💡 Benefits of using Optional: Reduces chances of NullPointerException Makes code more readable and expressive Encourages better null handling practices Using Optional in modern Java applications helps developers write safer and more maintainable code. #Java #JavaTips #SoftwareDevelopment #JavaDeveloper #Programming
To view or add a comment, sign in
-
🚀 Java Series – Day 23 📌 ArrayList vs LinkedList in Java 🔹 What is it? Both ArrayList and LinkedList are part of the Java Collection Framework and implement the List interface. They are used to store ordered data, but their internal working is different. 🔹 Why do we use it? Choosing the right list improves performance and efficiency. For example: • Frequent searching → ArrayList • Frequent insertion/deletion → LinkedList 🔹 ArrayList vs LinkedList: • ArrayList - Uses dynamic array - Fast for accessing elements (O(1)) - Slow insertion/deletion (shifting needed) • LinkedList - Uses doubly linked list - Slow access (O(n)) - Fast insertion/deletion 🔹 Example: import java.util.*; public class Main { public static void main(String[] args) { List<String> arrayList = new ArrayList<>(); arrayList.add("A"); arrayList.add("B"); List<String> linkedList = new LinkedList<>(); linkedList.add("X"); linkedList.add("Y"); System.out.println(arrayList); System.out.println(linkedList); } } 💡 Key Takeaway: Use ArrayList for fast access and LinkedList for frequent modifications. What do you think about this? 👇 #Java #Collections #ArrayList #LinkedList #JavaDeveloper #Programming
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
https://github.com/raushansingh7033/core-java