Java Bytes #5 What will be the output of the following code? class Main { private static int getNum012(int num) { try { if(num == 1) { return 1; } if(num == 0) { num = num / 0; return 0; } } catch(ArithmeticException e) { return 0; } finally { return 2; } } public static void main(String[] args) { System.out.println(getNum012(0)); System.out.println(getNum012(1)); System.out.println(getNum012(2)); } } ---------------------------------------------------------------- Java is like my girlfriend. I have misunderstood her many times. Still I try to understand her a lot. Please feel free to correct me if I have misunderstood her. #javaBytes #javaIsLove #javaInterviewPrep
Java Exception Handling with getNum012 Method
More Relevant Posts
-
🤯 Java's Hidden Cache War: Integer vs String - Which One Bites Developers More?♨️ Java caches small Integers (-128 to 127) but Strings work differently. Knowing why saves you from bugs AND improves performance. Quick breakdown: 👇 1. INTEGER CACHE (Reference-Based) Integer a = 100; Integer b = 100; System.out.println(a == b); Why: Integer.valueOf() reuses cached objects Range: -128 to 127 (configurable) Purpose: Performance for common numbers Gotcha: == works only within cache range! 2. STRING POOL (Value-Based) String s1 = "hello"; String s2 = "hello"; System.out.println(s1 == s2); Why: JVM pools string literals Manual control: String.intern() Purpose: Memory optimization Warning: Don't overuse intern()! THE CRITICAL DIFFERENCE: Integer cache: Fixed size, performance-focused String pool: Dynamic, memory-focused GOLDEN RULE: // ❌ Never do this: if (intObj1 == intObj2) // ✅ Always do this: if (intObj1.equals(intObj2) PRACTICAL IMPACT: Loops with autoboxing → Cache helps! Repeated strings → Pool helps! == comparisons → Will bite you! TEST YOURSELF: java Integer x = 200; Integer y = 200; System.out.println(x == y); // ??? Answer below! First 5 correct answers get a Java Memory cheatsheet. Like if you learned something! Save for your next interview prep! Follow for more Java insights! #Java #Programming #Caching #Developer #Coding #Java #JVM #MemoryManagement #PerformanceOptimization #SoftwareEngineering #Programming #Coding #BackendDevelopment #SystemDesign #JavaDeveloper #TechInterview #CleanCode #DeveloperTips #Caching
To view or add a comment, sign in
-
-
🧵 Java String Pool vs String Object — What You Need to Know ━━━━━━━━━━━━━━━━━━━━━━ 💡 String literals in Java are treated specially. JVM stores them in a String Pool, making memory usage efficient and comparison fast. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 String Pool (Literal Strings) Memory area inside the Heap for string literals. JVM reuses literals to save memory. Immutable, so safe to share references. String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); // true → same reference ✅ Multiple references point to the same object in the pool. 🔹 String Objects (new keyword) Created outside the pool in Heap memory. Even if the same content exists in the pool, new always creates a new object. String s3 = new String("Java"); System.out.println(s1 == s3); // false → different object System.out.println(s1.equals(s3)); // true → content matches ✅ Use s3.intern() to add it to the String Pool explicitly. ⚡ Why JVM treats string literals specially Immutable → safe to share references. Memory optimization → only one copy stored. Fast comparison → == works for literals. Key Takeaway: Always prefer string literals for repeated values. Use new String() only when necessary. .intern() can explicitly add objects to the pool. #Java #StringPool #MemoryOptimization #Backend #TechExplained #ProgrammingTips #JVM #Immutable
To view or add a comment, sign in
-
Day 1 of #DSAChallenge 🚀 📌 Problem: Longest Common Prefix 📍 Platform: LeetCode 🔹 Problem Statement: Given an array of strings, find the longest common prefix among them. If no common prefix exists, return an empty string. ━━━━━━━━━━━━━━━━━━ 🔹 Approach: ✔ Took the first string as the initial prefix ✔ Compared it with every other string ✔ Reduced the prefix step-by-step using character comparison ✔ Stopped comparison as soon as mismatch occurs ━━━━━━━━━━━━━━━━━━ 🔹 Java Implementation: class Solution { public String common(String s1, String s2) { int n = Math.min(s1.length(), s2.length()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { if (s1.charAt(i) == s2.charAt(i)) sb.append(s1.charAt(i)); else break; } return sb.toString(); } public String longestCommonPrefix(String[] strs) { String res = strs[0]; for (int i = 0; i < strs.length; i++) { res = common(res, strs[i]); } return res; } }
To view or add a comment, sign in
-
-
let's see how strong your core java is : write the answer in comments: class Parent { Parent() { show(); } void show() { System.out.println("Parent show"); } } class Child extends Parent { int x = 10; void show() { System.out.println(x); } public static void main(String[] args) { new Child(); } } Questions 1. Which show() is called? 2. Output? 3. Why is this considered dangerous design?
To view or add a comment, sign in
-
This question is a good example to understand concepts of constructor and inheritance. For the First question: Child class show() method will be called because child class object is created and it overrides the parent class show() method. For the Second question: The output might be 0 because when child class object is created it will first call parent class constructor which then call the overridden show method and print the value of x i.e. 0(Because JVM will first assign default values to the variables after creating the child class object and calls parent constructor first). For the Third question: This can cause security flaws in the code and can result in Null Pointer Exception. You should never call the overridden methods from the constructor, and if you have to call a method from constructor make the method final first.
let's see how strong your core java is : write the answer in comments: class Parent { Parent() { show(); } void show() { System.out.println("Parent show"); } } class Child extends Parent { int x = 10; void show() { System.out.println(x); } public static void main(String[] args) { new Child(); } } Questions 1. Which show() is called? 2. Output? 3. Why is this considered dangerous design?
To view or add a comment, sign in
-
Why String is a immutable in Java? First, What is string, String ? string -> A string is a sequence of characters placed inside double quotes (" "). Technically, it is called a String literal. e.g -> String s1="Om"; -> "Om" is a string literal. String -> A String is a predefined class in Java. It is used to storing a sequence of characters. e.g. -> String s1="om"; -> it is String declaration Now, the main point: Why is String Immutable?-> In Java, String objects are stored in the String Constant Pool (SCP), which resides inside the Heap memory of the JVM. e.g. -> String s1 = "Om"; String s2 = s1.concat("Shelke"); "Om" is stored in the String Constant Pool. When we try to modify or concatenate the string, a new String object is created. The existing String object is never modified. Every modification creates a new object. This behavior is called immutability. String immutable is made for security, memory optimization, and thread safety purposes. #corejava #javadeveloper
To view or add a comment, sign in
-
-
📌 new String() vs String Literal in Java In Java, Strings can be created in two different ways. Although they may look similar, they behave differently in memory. 1️⃣ String Literal When a String is created using a literal: • The value is stored in the String Pool • JVM checks if the value already exists • Existing reference is reused if available Example: String s1 = "java"; String s2 = "java"; Both references point to the same object. 2️⃣ new String() When a String is created using the `new` keyword: • A new String object is created in heap memory • It does not reuse the String Pool object by default Example: String s3 = new String("java"); `s3` points to a different object even if the value is the same. 3️⃣ Memory Impact • String literals reduce memory usage through reuse • `new String()` always creates an additional object • Using `new` unnecessarily can increase memory consumption 4️⃣ When to Use • Prefer String literals for most use cases • Use `new String()` only when a distinct object is explicitly required 💡 Key Takeaways: - String literals use the String Pool - `new String()` creates a separate heap object - Understanding this helps write memory-efficient code #Java #CoreJava #String #JVM #BackendDevelopment
To view or add a comment, sign in
-
🟢 How to Count Characters in a String using Java 8 Stream API Input type: String = "Welocometoprogrammming" Output Type : Map<Character, Long> ✅ Code Example import java.util.*; import java.util.stream.*; import java.util.function.Function; public class Main { public static void main(String[] args) { String str = "Welocometoprogrammming"; Map<Character, Long> chCount = str.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), Collectors.counting() )); System.out.println(chCount); } } Output: {a=1, c=1, e=2, g=2, i=1, l=1, m=4, n=1, o=4, p=1, r=2, t=1, W=1} 🧠 Let’s Understand the Approach 🔹 Do we need a filter? ➡️ No, because we want to count all characters. 🔹 Do we need transformation? ➡️ No logical transformation, only type conversion. 🔹 Why chars()? ➡️ chars() converts the String into an IntStream of character ASCII values. 🔹 Why mapToObj()? ➡️ Because char is a primitive type, and Stream operations work on objects. So we convert each int to Character. 🔹 Why collect()? ➡️ Because the final result needs to be stored in Map<Character, Long>. ❓ What is Function.identity()? Function.identity() is a static method from java.util.function.Function. ✔️ It returns the same input as output ✔️ It is a replacement for this lambda: c -> c ✔️ Used when key and value are the same object Example: Collectors.groupingBy(Function.identity(), Collectors.counting()) Means: 👉 Group characters by themselves and count occurrences. #Java #Java8 #StreamAPI #Coding #InterviewPreparation #JavaStream #Multithreading
To view or add a comment, sign in
-
-
#day16 #FunctionalInterfaces A functional interface in Java is an interface that has only one abstract method, making it suitable for use with lambda expressions and method references (introduced in Java 8). a. Use @FunctionalInterface to ensure only one abstract method (annotation is optional). b. Enable clean, concise code using lambdas and method references. #@FunctionalInterface Annotation @FunctionalInterface annotation ensures that an interface cannot have more than one abstract method. If multiple abstract methods are present, the compiler throws an “Unexpected @FunctionalInterface annotation” error. #Types of Functional Interfaces in Java Java 8 introduced four main functional interface types under the package java.util.function. These are widely used in Stream API, collections and lambda-based operations. 1. Consumer -: Consumer interface of the functional interface is the one that accepts only one argument. It is used for performing an action, such as printing or logging. There are also functional variants of the Consumer DoubleConsumer, IntConsumer and LongConsumer. 2. Predicate :- Predicate interface represents a boolean-valued function of one argument. It is commonly used for filtering operations in streams. There are also functional variants of the Predicate IntPredicate, DoublePredicate and LongPredicate. 3. Function:- The function interface takes one argument and returns a result. It is commonly used for transforming data. Several variations exist: Bi-Function: Takes two arguments and returns a result. Unary Operator: Input and output are of the same type. Binary Operator: Like BiFunction but with same input/output type. 4. Supplier:- Supplier functional interface is also a type of functional interface that does not take any input or argument and yet returns a single output. The different extensions of the Supplier functional interface hold many other suppliers functions like BooleanSupplier, DoubleSupplier, LongSupplier and IntSupplier. #leetcode #gfg #interviewbit #Consistency #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Hello connections I was revising Strings concept in java today. 😁 I have been hit with a question which I am posting below along with my logic 🤑 : Coding question: String Transformation, Convert input string to output string and print the output string. Input String: "91-044 56 9877 2976545" Output String: "910-445-698-772-976-545" My logic: String input = "91-044 56 9877 2976545"; input = input.replaceAll("-","").replaceAll(" ",""); String output =""; for(int i= 0; input.length()-i>=3 ;i+=3){ output = output + input.substring(i,i+3)+"-"; } output = output.substring(0,output.length()-1); return output; I am excited to know if there is any other way to solve it even if it's another language. 😀 (I solved it in java.) #HappyLearning
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
Output: 2 2 2 Everytime 2 is returned because the finally block's return statement overwrites the return statement from try or catch block