While solving a competitive programming problem, I revisited an interesting concept in Java’s BigInteger class — especially the meaning of certainty in isProbablePrime(). 🔹 Problem Statement Given a number n (which can be very large), determine whether it is prime or not prime. 📌 Note: The number may contain hundreds of digits, so primitive data types (int, long) are not sufficient. 🔹 Why normal prime checking fails ❌ Traditional logic like: using for loop and finding the primenumber for (int i = 2; i <= sqrt(n); i++) does not work because: 1. int / long overflow for large inputs 2. sqrt() cannot be calculated for huge numbers 3. Time complexity becomes impractical 🔹 Correct Approach using BigInteger Java provides a built-in method:-- isProbablePrime(int certainty)--- Here, certainty means: The level of confidence that the number is prime (The probability of error is less than 1 / 2^certainty) 🔹 Java Program (Competitive-ready) import java.io.*; import java.math.BigInteger; public class Solution { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); String n = br.readLine().trim(); BigInteger number = new BigInteger(n); if (number.isProbablePrime(1)) { System.out.println("prime"); } else { System.out.println("not prime"); } } } ✔️ Handles very large numbers ✔️ Passes hidden test cases ✔️ Fast and reliable 🔹 Key Learning 💡 certainty is not the number to test It controls how confident Java should be Even certainty = 1 is sufficient for most competitive platforms 📚 Takeaway: When dealing with very large numbers, rely on BigInteger’s probabilistic algorithms instead of manual prime-checking logic. #Java #BigInteger #CompetitiveProgramming #ProblemSolving #LearningEveryDay #CodingTips
Java BigInteger for Large Number Primality Testing
More Relevant Posts
-
Day8 🚀: Variables & Memory Structure in Java Today’s learning was about what is variable and Types of variables and how Java uses RAM when a program executes. and how program execution works in java This helped me understand what happens behind the scenes when we run a Java program. A variable is a container that stores data values. In Java, every variable must be declared with a specific data type. 🔹 Syntax: data Type variable Name = value; 🔹 Example: int age = 21; double salary = 25000.50; char grade = 'A'; String name = "Theja"; 🔹 Types of Variables Covered 1️⃣ Local Variables *Declared inside methods *Stored in Stack memory *Created when method starts and destroyed when method ends 2️⃣ Instance Variables *Declared inside a class but outside methods *Stored in Heap memory *Each object has its own separate copy 🔹 How Java Uses RAM During Execution When we run a Java program, memory is divided into different segments: 🧠 1. Code Segment °Stores the compiled bytecode °Contains the program instructions 🧠 2. Static Segment °Stores static variables °Memory is allocated only once 🧠 3. Stack Segment °Stores local variables °Stores method calls °Works in LIFO (Last In First Out) order 🧠 4. Heap Segment °Stores objects and instance variables °Managed by Garbage Collector 🔹 How Program Execution Works in Java 1️⃣ Code is written and compiled into bytecode 2️⃣ JVM loads the class into memory 3️⃣ main() method is pushed into Stack 4️⃣ Objects are created in Heap 5️⃣ Variables are allocated memory 6️⃣ After execution, unused objects are removed by Garbage Collector 🔹 What I Understood Today Understanding variables is not enough. Knowing where they are stored in memory and how Java manages RAM gives deeper clarity about performance and program behavior. Learning how Java works internally is making my foundation stronger 💻🔥 #Java #MemoryManagement #JVM #Programming #LearningJourney #Day8
To view or add a comment, sign in
-
-
The Magic of @SneakyThrows in Java: How Does It Break the Rules? Lombok’s @SneakyThrows often raises questions in code reviews. It allows us to throw a checked exception (like IOException) without adding a throws clause - something Java normally forbids. The Problem: Java forces you to catch checked exceptions or declare them. This is especially frustrating with lambdas, where adding a throws declaration isn't an option. How does this work? Lombok uses bytecode manipulation. It replaces your checked exception with a generic throw that bypasses the compiler's checks. At runtime, the exception is thrown normally, but the compiler never sees the violation. It’s a clean solution for edge cases - just use it intentionally. While @SneakyThrows makes the code look cleaner, it breaks the method signature contract. Consumers of your method won't know they need to handle that exception, which can lead to unexpected application crashes. It also violates the Principle of Least Astonishment - other developers reading the code won't expect a checked exception to appear out of nowhere, making debugging and maintenance more difficult. But despite these risks, it's hard to deny how pleasant @SneakyThrows feels to use. The code becomes so clean and readable - no more wrapping everything in try-catch blocks just to satisfy the compiler. When you're working with streams or quick scripts, that single annotation removes the noise and lets the business logic shine. Do you use @SneakyThrows in your projects? Let’s discuss below! 👇 #Java #Programming #Lombok #SoftwareDevelopment #CodingTips
To view or add a comment, sign in
-
-
Day 9 | Full Stack Development with Java Today’s learning helped me understand how Java actually manages memory and variables behind the scenes. JRE (Java Runtime Environment) JRE provides the runtime environment required to execute Java programs. When a Java program runs, memory is divided into segments: Code Segment Static Segment Heap Segment Stack Segment Understanding this made it easier to connect variables with memory allocation. What is a Variable? A variable is a named memory location used to store data. Each variable: Has a data type Stores a specific type of value Must be declared before use data_type variable_name; Example: Java Copy code int a; Types of Variables in Java Instance Variables Declared inside a class but outside methods Stored in Heap memory Created when an object is created Assigned default values by JVM Default primitive values: int, byte, short, long → 0 float, double → 0.0 boolean → false char → empty character Objects → null Local Variables Declared inside a method Stored in Stack memory Exist only during method execution Must be initialized before use No default values provided Pass by Value (Java Concept) In Java, arguments are passed by value. This means: A copy of the value is passed. Changes inside the method do not affect the original variable. Reference Behavior When objects are assigned: Java Car a = new Car(); Car b = a; Both a and b refer to the same object in heap memory. Modifying object data using b will reflect when accessed using a, because both point to the same memory address. Key Takeaway Understanding variables is not just about syntax — it’s about understanding: Memory allocation (Stack vs Heap) Object references Data flow inside programs This is helping me build strong backend fundamentals step by step. #Day9 #Java #Variables #JRE #FullStackDevelopment #LearningInPublic #ProgrammingJourney
To view or add a comment, sign in
-
-
🔹 Understanding Java Streams in Simple Words Java Streams (introduced in Java 8) help process collections in a clean and functional way — without writing complex loops. Instead of writing lengthy code, streams allow us to filter, transform, and process data efficiently. ✅ Example: List numbers = Arrays.asList(1,2,3,4,5,6); List even = numbers.stream() .filter(n -> n % 2 == 0) .toList(); System.out.println(even); ✅ Common Stream Operations with Examples: ✔ filter() → select data List even = numbers.stream() .filter(n -> n % 2 == 0) .toList(); ✔ map() → transform data List doubled = numbers.stream() .map(n -> n * 2) .toList(); ✔ count() → count elements long count = numbers.stream() .filter(n -> n > 3) .count(); ✔ sorted() → sort values List sortedList = numbers.stream() .sorted() .toList(); ✔ reduce() → combine values int sum = numbers.stream() .reduce(0, (a, b) -> a + b); Streams make code more readable, modern, and efficient. If you're learning Java, mastering Streams is a must! #Java #JavaStreams #Programming #Coding #Developers #Learning
To view or add a comment, sign in
-
📘 Day 7 | Core Java – Concept Check🌱 Revising Core Java concepts and validating my understanding with answers 👇 1️⃣ Why does Java not support multiple inheritance with classes? -->To avoid ambiguity and complexity (diamond problem). Java achieves multiple inheritance using interfaces instead. 2️⃣ What happens if we override equals() but not hashCode()? -->It breaks the contract between equals() and hashCode(), causing incorrect behavior in hash-based collections like HashMap. 3️⃣ Can an abstract class have a constructor? Why? --> Yes, an abstract class can have a constructor to initialize common data when a subclass object is created. 4️⃣ Why is method overloading decided at compile time? --> Because it is resolved based on method signature (method name + parameters) at compile time, not at runtime. 5️⃣ What is the difference between method overriding and method hiding? --> Overriding happens with non-static methods at runtime, while hiding happens with static methods at compile time. 6️⃣ Why can’t we create an object of an abstract class? -->Because abstract classes may contain abstract methods without implementation, and objects must have complete behavior. 7️⃣ How does polymorphism help in reducing code dependency? --> It allows programming to interfaces or parent classes, making code flexible and easy to extend without modification. 8️⃣ What is the use of the instanceof operator in Java? --> It checks whether an object belongs to a specific class or interface at runtime. Learning concepts deeply by questioning and validating answers 📚💻 #CoreJava #JavaLearning #ProgrammingConcepts #LearningJourney #MCAGraduate
To view or add a comment, sign in
-
Day 40 – Java 2026: Smart, Stable & Still the Future Topic: Object in Java (Core of OOP) What is an Object? An object is a runtime instance of a class that represents a real-world entity. It contains: • State (variables) • Behavior (methods) • Identity (unique memory location) Steps to Create an Object Declare a reference variable Create an object using the new keyword Assign object to reference Student s1 = new Student(); Reference Variable A reference variable stores the memory address of an object, not the actual object. It is used to access the object. Example: s1 → reference variable new Student() → object Declaration and Initialization Declaration only Student s1; Initialization only s1 = new Student(); Declaration + Initialization Student s1 = new Student(); Object vs Reference Variable FeatureObjectReference VariableMemory LocationHeapStackStoresActual dataAddress of objectCreated Usingnew keywordClass typeExamplenew Student()s1Key Points • One class can create multiple objects • Each object has separate memory • Reference variable points to object • Objects are created at runtime • Java programs work using objects Simple Example class Student { String name; } public class Main { public static void main(String[] args) { Student s1 = new Student(); s1.name = "Sneha"; System.out.println(s1.name); } } Key Takeaway: Object = Real entity Reference = Way to access that entity #Java #40 #OOP #LearnJava #JavaDeveloper #Programming #100DaysOfCode #CareerGrowth
To view or add a comment, sign in
-
-
I wrote a blog post about "Functional Composition Patterns." If you're interested in learning how to implement them in pure Java, it's good material. You could also check out the rest of the documentation for the `dmx-fun` library. https://lnkd.in/eR5uvmHE
To view or add a comment, sign in
-
🌟 Day 7 of 10 – Core Java Recap: Encapsulation, Inheritance & Access Modifiers 🌟 Continuing my 10-day Core Java revision journey 🚀 Today I revised very important OOP concepts used in real-world applications. 🔐 1️⃣ Encapsulation in Java Encapsulation is the process of wrapping data (variables) and code (methods) into a single unit (class). It is mainly used for data hiding and security. In encapsulation: Variables are declared as private Access is provided using public getter and setter methods Key Benefits: ✔ Data hiding ✔ Controlled access to data ✔ Better code security ✔ Improved maintainability Example concept: Private variables + Public getters/setters = Encapsulation ⚙ 2️⃣ Implementation of Encapsulation Key points: Use private data members Provide public getter() and setter() methods Prevent direct access from outside the class Example: private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } 🧬 3️⃣ Inheritance in Java Inheritance is a mechanism in which one class acquires the properties and behaviors of another class. Real-time relation: Parent Class → Child Class Superclass → Subclass Advantages: ✔ Code reusability ✔ Readability ✔ Maintainability 📚 4️⃣ Types of Inheritance Single Inheritance Multilevel Inheritance Hierarchical Inheritance Hybrid Inheritance (supported using interfaces in Java) Note: Java does not support multiple inheritance using classes to avoid ambiguity (Diamond Problem). 🔓 5️⃣ Access Modifiers in Java Access modifiers define the accessibility (scope) of classes, variables, and methods. Types of Access Modifiers: Public Private Protected Default (No modifier) 📊 6️⃣ Scope of Access Modifiers 🔹 Private Accessible only within the same class Provides maximum data security 🔹 Default Accessible within the same package No keyword is used 🔹 Protected Accessible within the same package Also accessible in subclasses (even in different packages) 🔹 Public Accessible from anywhere in the program Access Level Order: Private < Default < Protected < Public 💡 Key Learnings Today: Understood encapsulation and data hiding Learned how getters and setters control data access Revised inheritance and its types Clearly understood access modifiers and their scope Strengthening my OOP concepts step by step for interviews and real-world development 💻🔥 #Java #CoreJava #OOP #Encapsulation #Inheritance #AccessModifiers #JavaLearning #CodingJourney
To view or add a comment, sign in
-
🚀 Learning Core Java – Immutable Strings & String Comparison Today, I learned more about Immutable Strings in Java and the different ways to compare them. In Java, the String class is immutable, which means once a string object is created, its value cannot be changed. Any modification results in a new object being created in memory. Because strings are objects, Java provides multiple built-in methods to compare them in different ways. ⸻ 🔹 1️⃣ == (Reference Comparison) The == operator compares references (memory addresses), not actual content. If two string variables point to the same object, it returns true. Otherwise, false — even if the content is the same. ⸻ 🔹 2️⃣ equals() (Value Comparison) The equals() method compares actual string values (content). It checks whether the characters inside both strings are the same. ⸻ 🔹 3️⃣ compareTo() (Character-by-Character Comparison) The compareTo() method compares strings lexicographically (character by character). • Returns 0 → if both strings are equal • Returns positive value → if first string is greater • Returns negative value → if first string is smaller ⸻ 🔹 4️⃣ equalsIgnoreCase() This method compares string values while ignoring uppercase and lowercase differences. ⸻ 🔹 5️⃣ compareToIgnoreCase() This compares strings character by character, ignoring case differences. ⸻ 🔎 Key Takeaway: • Use == for reference comparison • Use equals() for content comparison • Use compareTo() for sorting or lexicographical comparison • Use ignore-case methods when case sensitivity doesn’t matter Understanding these differences helps avoid common bugs and write more predictable Java programs. Excited to keep strengthening my Java fundamentals! 🚀 #CoreJava #JavaProgramming #ImmutableString #JavaDeveloper #StringComparison #ProgrammingFundamentals #LearningJourney #StudentDeveloper
To view or add a comment, sign in
-
-
Day 22 – Reference Variables in Java Today I explored an important concept in Object-Oriented Programming — Reference Variables. Unlike primitive variables, reference variables store the address of an object, not the actual value. 🔹 What is a Reference Variable? A reference variable is a non-primitive variable that refers to an object created from a class. It is declared using the class name. Syntax: ClassName referenceVariable; Initialization- referenceVariable = new ClassName(); Or both together: ClassName referenceVariable = new ClassName(); Here: ClassName → Name of the class referenceVariable → Object reference new → Keyword used to create an object ClassName() → Constructor 🔹 Example class Demo5 { int x = 100; int y = 200; } class MainClass3 { public static void main(String[] args) { Demo5 d1 = new Demo5(); System.out.println("x = " + d1.x); System.out.println("y = " + d1.y); System.out.println("modifying x & y"); d1.x = 300; d1.y = 400; System.out.println("x = " + d1.x); System.out.println("y = " + d1.y); } } Output: x = 100 y = 200 modifying x & y x = 300 y = 400 🔹 Important Observation When we write: Demo5 d1 = new Demo5(); Java performs three things: 1️⃣ Creates a reference variable (d1) 2️⃣ Creates a new object in memory 3️⃣ Stores the object reference in the variable #Java #CoreJava #JavaFullStack #OOP #Programming #BackendDevelopment #LearningInPublic #SoftwareDevelopment
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