💡 Understanding the Difference Between import and static import in Java In Java, we often use the import statement to access classes from other packages — but did you know there’s also a static import that works a bit differently? Let’s break it down 👇 🔹 import Used to access classes or interfaces from another package. You still need to reference static members (like methods or variables) with the class name. 🔹 static import Introduced in Java 5, it allows you to access static members directly — without prefixing the class name every time. --- 🧩 Example: // File: Demo.java import java.lang.Math; // Regular import import static java.lang.Math.*; // Static import public class Demo { public static void main(String[] args) { // Using regular import double value1 = Math.sqrt(25); // Using static import double value2 = sqrt(25); // No need for Math prefix System.out.println("Using import: " + value1); System.out.println("Using static import: " + value2); } } --- 🚀 Key Takeaways: ✅ import → Brings classes or interfaces into scope. ✅ static import → Brings static members (methods/fields) into scope directly. ✅ Use static import sparingly — it can make code cleaner, but overusing it may reduce readability. --- 💬 Do you often use static import in your projects, or do you prefer the explicit ClassName.method() style? #Java #Programming #CleanCode #StaticImport #ImportStatement #SoftwareDevelopment #JavaLearning
"Java: Understanding import and static import"
More Relevant Posts
-
public static void main(String[] args) This line is the main method in Java — the entry point of every Java program. 1. public - It is an access modifier. - It means this method is accessible from anywhere. - The Java Virtual Machine (JVM) must be able to call this method from outside the class — that’s why it must be public. Example : If it’s not public, JVM cannot access it → program won’t run. 2. static - It means the method belongs to the class and not to any specific object. - JVM can call this method without creating an object of the class. Example : ClassName.main(args); // called directly without creating object 3. void - It is the return type. - It means this method does not return any value to the program. Example : If we write int instead of void, we’d have to return an integer value — but main() doesn’t return anything. 4. main This is the method name recognized by JVM as the starting point of every program. Execution always begins from this method. Example : public static void main(String[] args) { System.out.println("Hello, World!"); } Here, execution starts at main(). 5. (String[] args) - This is a parameter (an array of strings). - It stores command-line arguments that you can pass when running the program. Example : If you run: java Test Hello World Then: args[0] = "Hello" args[1] = "World" -- Here we have simple way to understand Part Meaning Purpose public Access Modifier JVM can access it static Belongs to class Called without object void Return Type Doesn’t return anything main Method Name Program entry point String[] args Parameter Stores command-line inputs #Java #Programming #Core java #Codegnan Anand Kumar Buddarapu Uppugundla Sairam Saketh Kallepu
To view or add a comment, sign in
-
-
☕ 33 Core Technical Rules of Java 1. Everything in Java lives inside a class or interface. 2. One public class per file, and the file name must match it. 3. Main entry point: public static void main(String[] args). 4. Primitives (int, boolean, etc.) are not objects. 5. References hold addresses, not the actual values. 6. Strings are immutable and stored in the string pool. 7. Methods must always belong to a class or interface. 8. Constructors have no return type and share the class name. 9. this → current instance; super → parent class. 10. Static members belong to the class, not instances. 11. Overloading → compile-time; Overriding → runtime. 12. Every object extends java.lang.Object. 13. Garbage Collection is automatic — no manual freeing. 14. Access modifiers control visibility (public, private, etc.). 15. final means no modification (variable, method, class). 16. Interfaces can’t hold mutable state. 17. Abstract classes can’t be instantiated. 18. Generics are type-erased at runtime. 19. Arrays are covariant and know their length. 20. Exceptions are divided into checked and unchecked. 21. Checked exceptions must be declared with throws. 22. Threads must start via start(), not run(). 23. synchronized locks on the object monitor. 24. Enums are full classes with fields and methods. 25. Autoboxing handles primitive ↔ wrapper conversions. 26. Annotations can exist at source, class, or runtime. 27. Reflection gives runtime access to class metadata. 28. instanceof checks type; casting may throw exceptions. 29. Fields have default values; locals don’t. 30. Java is pass-by-value only (references are copied by value). 31. switch supports String, enum, and primitives. 32. Modules (module-info.java) define explicit dependencies. 33. The JVM verifies bytecode integrity before execution. #Java #ProgrammingLanguages #SoftwareEngineering #BackendDevelopment #CodeTips #Developers #SystemProgramming #TechPost
To view or add a comment, sign in
-
⚙️ Day 13: StringBuffer & StringBuilder in Java Today I explored how to handle mutable (changeable) strings using StringBuffer and StringBuilder — ideal for performance and frequent text updates. 💡 What I Learned Today StringBuffer → Thread-safe (synchronized), slower but safe for multithreading. StringBuilder → Not thread-safe, faster and used in single-threaded programs. Both can modify string content without creating new objects. Common methods: append() → adds text insert() → inserts at a specific position replace() → replaces text delete() → removes text reverse() → reverses the sequence 🧩 Example Code public class BufferBuilderExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Java"); sb.append(" Programming"); System.out.println("StringBuffer: " + sb); StringBuilder sb2 = new StringBuilder("Hello"); sb2.append(" World"); sb2.reverse(); System.out.println("StringBuilder: " + sb2); } } 🗣️ Caption for LinkedIn 🧠 Day 13 – StringBuffer & StringBuilder in Java Today I learned how to make strings mutable! StringBuffer and StringBuilder allow you to modify strings efficiently without creating new objects. ⚙️ StringBuffer = thread-safe ⚡ StringBuilder = faster in single-threaded programs Choosing the right one improves both performance and reliability! #Java #CoreJava #LearnJava #Programming #CodingJourney
To view or add a comment, sign in
-
-
⚙️ Day 13: StringBuffer & StringBuilder in Java Today I explored how to handle mutable (changeable) strings using StringBuffer and StringBuilder — ideal for performance and frequent text updates. 💡 What I Learned Today StringBuffer → Thread-safe (synchronized), slower but safe for multithreading. StringBuilder → Not thread-safe, faster and used in single-threaded programs. Both can modify string content without creating new objects. Common methods: append() → adds text insert() → inserts at a specific position replace() → replaces text delete() → removes text reverse() → reverses the sequence 🧩 Example Code public class BufferBuilderExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Java"); sb.append(" Programming"); System.out.println("StringBuffer: " + sb); StringBuilder sb2 = new StringBuilder("Hello"); sb2.append(" World"); sb2.reverse(); System.out.println("StringBuilder: " + sb2); } } 🗣️ Caption for LinkedIn 🧠 Day 13 – StringBuffer & StringBuilder in Java Today I learned how to make strings mutable! StringBuffer and StringBuilder allow you to modify strings efficiently without creating new objects. ⚙️ StringBuffer = thread-safe ⚡ StringBuilder = faster in single-threaded programs Choosing the right one improves both performance and reliability! #Java #CoreJava #LearnJava #Programming #CodingJourney
To view or add a comment, sign in
-
-
Why static methods can’t be overridden in Java? 🤔 You make one static method in parent, then try to override it in child... Java like — “No bro, I don’t allow that 😎” Example 👇 class Parent { static void show() { System.out.println("From Parent"); } } class Child extends Parent { static void show() { System.out.println("From Child"); } } public class Test { public static void main(String[] args) { Parent obj = new Child(); obj.show(); // From Parent ❗ } } Here’s the truth 👇 static methods belong to the class, not the object. So they are resolved at compile time, not runtime. 👉 This is called method hiding, not overriding. That’s why even if your object is Child, Java checks the reference type (Parent) and runs that static method. 🧠 Takeaway: // static → belongs to class // Resolved at compile time // It’s method hiding, not overriding // Only instance methods can be overridden
To view or add a comment, sign in
-
-
Strings:- String comparison techniques in Java 1️⃣ == Operator Definition: Compares the memory references of two strings — checks if both variables point to the same object in memory, not the content. 2️⃣ equals() Method Definition: Compares the actual content (value) of two strings — returns true if both strings contain the same sequence of characters (case-sensitive). 3️⃣ equalsIgnoreCase() Method Definition: Compares the content of two strings while ignoring case differences (uppercase or lowercase letters). 4️⃣ compareTo() Method Definition: Compares two strings lexicographically (alphabetical order) and returns: 0 → if both strings are equal Positive value → if the first string is greater Negative value → if the first string is smaller 5️⃣ compareToIgnoreCase() Method Definition: Works like compareTo() but ignores case differences during comparison. 6️⃣ contentEquals() Method Definition: Checks if a string has the exact same sequence of characters as another String or StringBuffer. 7️⃣ matches() Method Definition: Tests whether a string matches a given regular expression pattern, often used for validation (like checking email format). String Memory Handling: Strings created using literals go to the String Constant Pool (SCP). Strings created using new keyword are stored in heap memory. This helps Java save memory by reusing identical strings from the SCP. Real-World Example: Imagine you’re building an e-commerce website — Strings are used for: Product names (String productName = "Smartphone";) Order IDs (String orderId = "ORD1234";) Customer names, addresses, and messages Efficient use of StringBuilder can optimize the performance of your backend services while generating dynamic data (like invoices or receipts). Takeaway: Strings are the backbone of data handling in Java — They represent text, manage input/output, and connect nearly every part of an application. Choose wisely: String → when immutability is needed StringBuilder → for fast, single-threaded modification StringBuffer → for thread-safe operations #Java #CoreJava #StringInJava #JavaProgramming #LearnJava #CodingJourney #TechLearning #SoftwareDevelopment
To view or add a comment, sign in
-
"Is a String stored as a Character Array in Java?" 🚀 Java Trivia for Developers: Have you ever wondered how a String is actually stored in memory? 🤔 Most developers would say — “as a char[].” ✅ That used to be true… but not anymore! Let’s break it down 👇 --- 🕹️ Java 8 and Earlier In older versions, a String was internally represented like this: public final class String { private final char[] value; private final int hash; } Each character occupied 2 bytes (UTF-16) — simple, but memory-heavy for ASCII text. --- ⚡ Java 9 and Later – Compact Strings (JEP 254) Starting with Java 9, the internal representation changed to: public final class String { private final byte[] value; private final byte coder; // 0 = LATIN1, 1 = UTF16 private int hash; } Now, Java stores String data as a byte array, using LATIN-1 or UTF-16 encoding based on the content. This saves up to 50% memory for text that fits in 1 byte per character! 💡 --- 🧠 Takeaway So, is a String stored as a char[] in Java? ➡️ Not since Java 9! It’s now backed by a byte[] for better performance and memory efficiency. --- 💬 What do you think about this change? Have you ever noticed memory improvements in your applications after Java 9? #Java #String #MemoryOptimization #JEP254 #JavaDeveloper #CodingTrivia #Performance
To view or add a comment, sign in
-
-
Method overloading in Java is when a class has multiple methods with the same name but different parameters (either in number or type). This allows you to perform similar but slightly different tasks using the same method name, improving code readability and reducing redundancy. java example : class Calculator { // Adds two integers public int add(int a, int b) { return a + b; } // Adds three integers public int add(int a, int b, int c) { return a + b + c; } // Adds two double values public double add(double a, double b) { return a + b; } } public class Test { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(5, 10)); // calls add(int, int) System.out.println(calc.add(5, 10, 15)); // calls add(int, int, int) System.out.println(calc.add(5.5, 3.2)); // calls add(double, double) } } Here, the add method name is overloaded with different parameter lists. The compiler decides which method to call based on arguments given. Summary: Method overloading means same method name, different parameters.Improves code clarity; no need for different method names for similar actions.Compiler selects correct method based on argument types/count. #Java #MethodOverloading #ProgrammingConcepts #CodingTips #JavaBasics #JavaDevelopment #100DaysOfCode #Day6ofcoding
To view or add a comment, sign in
-
☕ Understanding final, finally, and finalize() in Java These three keywords may sound similar, but they serve completely different purposes in Java! Let’s clear the confusion 👇 🔹 final (Keyword) Used for declaring constants, preventing inheritance, or stopping method overriding. final variable → value can’t be changed final method → can’t be overridden final class → can’t be inherited 👉 Example: final int MAX = 100; 🔹 finally (Block) Used in exception handling to execute important code whether or not an exception occurs. Perfect for closing files, releasing resources, or cleaning up memory. 👉 Example: try { int a = 10 / 0; } catch (Exception e) { System.out.println("Error"); } finally { System.out.println("This will always execute"); } 🔹 finalize() (Method) It’s a method called by the Garbage Collector before an object is destroyed. Used to perform cleanup operations before object removal (though it’s deprecated in newer Java versions). 👉 Example: protected void finalize() { System.out.println("Object destroyed"); } --- 💡 Quick Summary: Keyword Used For Level final Restriction (variable, method, class) Compile-time finally Cleanup code block Runtime finalize() Object cleanup (GC) Runtime --- #Java #Programming #FinalFinallyFinalize #JavaDeveloper #ExceptionHandling #TechLearning #Coding
To view or add a comment, sign in
-
-
🚀 Methods vs. Constructors: Unpacking Key Differences in Java 🚀 New to Java or looking for a quick refresher? Understanding the distinction between Methods and Constructors is fundamental! While both contain blocks of code, they serve very different purposes. Let's break it down with a simple comparison: Constructors: The Blueprint Initializers 🏗️ Purpose: Primarily used to initialize new objects. Think of them as setting up the initial state when an object is first created. Name: Must have the same name as the class itself. Return Type: No return type (not even void). Invocation: Called automatically when you use the new keyword to create an object. Example: new Employee(101, "Alice"); Methods: The Action Performers ⚙️ Purpose: Used to perform actions or operations on an object, or to retrieve information from it. Name: Can have any valid name (following Java naming conventions). Return Type: Must have a return type (e.g., void, int, String, Employee, etc.). Invocation: Called explicitly using the object reference, like object.methodName(). Example: employee.getDetails(); or employee.calculateBonus(); In essence: Constructors build and set up your object. Methods make your object do things. Understanding this distinction is crucial for writing clean, efficient, and object-oriented Java code! Thanks Anand Kumar Buddarapu #Java #Programming #SoftwareDevelopment #OOP #Constructors #Methods #CodingTips
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