Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Java equals() selection*

  1. #1
    Junior Member
    Join Date
    Sep 2021
    Location
    India
    Posts
    20
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Java equals() selection*

    In Java, if I try to do.equals() on a null string, a null pointer error is issued. I知 wondering whether I can perform the following if I知 attempting to compare if a string is equal to a constant string:
    MY CONSTANT STRING.equals(aStringVariable)
    I知 sure it値l work, but is this simply extremely bad code?
    This is a common Java idiom known colloquially as a Yoda condition. Personally, I prefer to handle the null situation directly, but the Yoda method is widely used, and any competent Java programmer should quickly grasp what is going on. How should I proceed?

  2. #2
    Junior Member
    Join Date
    Nov 2022
    Location
    Williamsburg Va
    Posts
    1
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Java equals() selection*

    One of the primary tenets of any good programmer is to program defensively.

    To than end, we should avoid NullPointerException and using the equals method on a constant is a excellent way to achieve that. There is no shame in using it. After all, it is just a string whose value doesn't change.

    The Duke!

  3. The Following User Says Thank You to The Duke of Ino For This Useful Post:

    codingkeera (November 14th, 2022)

Similar Threads

  1. Java selection sort
    By maple1100 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 29th, 2013, 09:13 PM
  2. create an equals() method that overrides the object equals() method
    By slinky29 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 3rd, 2013, 11:11 PM
  3. What are HashCode and equals in Java and thay are implement in java?
    By diyaots in forum Java Theory & Questions
    Replies: 2
    Last Post: September 9th, 2011, 08:38 AM
  4. Basic Java Sorting Algorithm (Selection/Insertion) help
    By Arte7 in forum Algorithms & Recursion
    Replies: 5
    Last Post: August 22nd, 2011, 01:38 PM
  5. Java printer selection
    By pnvsgupta in forum Java SE APIs
    Replies: 4
    Last Post: July 23rd, 2011, 11:31 AM