this may be a simple problem, but I've looked for an answer and I'm just not finding it anywhere. I'm trying to use a method to check if an inputted answer is correct compared to the actual answer. The actual answer is defined by a setter, and the getter works also. But in the method where it's compared it becomes null. This isn't a question about why comparing them returns null, but why correctAnswer is null in the first place. I'm confused because getCorrectAnswer() works as intended.   Here is the code:  public class MultipleChoiceQuestion implements Question {  String question; String correctAnswer;  public String getQuestion()  {     return question; }  public boolean isCorrectAnswer(String answer)  {     if (answer != correctAnswer)     {         return false;     }     return true; }  public String getCorrectAnswer()  {     return correctAnswer; }  public void setQuestion(String questionText){     question = questionText; }  public void setAnswer(String answer){     correctAnswer = answer; }   }  "answer != correctAnswer" doesn't work because correctAnswer is null in that method.
93
I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.  Is == bad? When should it and should it not be used? What's the difference?
112290
This code throws a NullReferenceException when it calls ExecuteScalar:  selectedPassengerID = 0;  //SqlCommand command = GenericDataAccess.CreateCommand();   // 2nd test string connectionString = ""; SqlConnection conn;  connectionString = ConfigurationManager.     ConnectionStrings["ConnST-MHM"].ConnectionString; conn = new SqlConnection(connectionString); SqlCommand command = new SqlCommand(); command.CommandType = CommandType.StoredProcedure ; command.Connection = conn; command.CommandText = "SearchForPassenger";  SqlParameter param;  param = command.CreateParameter(); param.ParameterName = "@name"; param.Value = pName; // Session[""]; param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@flightDate"; param.Value = date;  param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@ticketNo"; param.Value = ticketNumber;  param.DbType = DbType.Int32; command.Parameters.Add(param);  int item;  command.Connection.Open(); item = (int)command.ExecuteScalar();
67060
I want to be able to have LinkedList.contains() return true for a custom comparator.  Suppose that I have 1 LinkedList and 2 objects  LinkedList&lt;MyObject&gt; myList = new LinkedList&lt;MyObject&gt;();  MyObject a = new MyObject("HELLO"); MyObject b = new MyObject("HELLO");   Technicaly, both objects are identical in terms of comparison (MyObject implements Comparable)   ( a == b ) == true  however, when I do the following, myList does not return true for myList.contains(b)  myList.add(a) myList.contains(b) // == false   I think its because contains will check object reference and see that a and b are 2 distinct objects. Is there any way I can make it so I don't have to extend LinkedList to compare those objects?
111151
Can I simply use  if(myString == nil)   For some reason a string that I know is null, is failing this statement.
64620
How do I check if a given object is nullable in other words how to implement the following method... bool IsNullableValueType(object o) {     ... }  I am looking for nullable value types. I didn't have reference types in mind. //Note: This is just a sample. The code has been simplified  //to fit in a post.  public class BoolContainer {     bool? myBool = true; }  var bc = new BoolContainer();  const BindingFlags bindingFlags = BindingFlags.Public                         | BindingFlags.NonPublic                         | BindingFlags.Instance                         ;   object obj; object o = (object)bc;  foreach (var fieldInfo in o.GetType().GetFields(bindingFlags)) {     obj = (object)fieldInfo.GetValue(o); }  obj now refers to an object of type bool (System.Boolean) with value equal to true. What I really wanted was an object of type Nullable&lt;bool&gt; So now as a work around I decided to check if o is nullable and create a nullable wrapper around obj.
83401
I have a question about the meaning (evaluation) of Boolean variables in return statements in Java.  I know that:  if (var) { ... }   is the same as:  if (var==true) { ... }   In the second case we explicitly say var==true, but we don't need to do this, because Java evaluates var as true anyway. I hope I have understood this right.  My question is: is it the same when Boolean variables are returned? When we have a return statement?  For example, a task specifies: the method looksBetter() will return true only if b &lt; a. My solution was:  public boolean looksBetter() {      if (b &lt; a) {          return true;      } else {          return false;      } }   The simple answer was:  public boolean lookBetter() {       return b &lt; a; }   So, it seems that here we have again this implicit assumption that in case b &lt; a == true, the return of the method is true. I am sorry ... it seems very trivial, but I am somehow not comfortable with this, and I don't know why. Thank you.
112799
In JavaScript, there are two values which basically say 'I don't exist' - undefined and null.  A property to which a programmer has not assigned anything will be undefined, but in order for a property to become null, null must be explicitly assigned to it.  I once thought that there was a need for null because undefined is a primitive value and null an object. It's not, even if typeof null will yield 'object': Actually, both are primitive values - which means neither undefined nor null can be returned from a constructor function, as both will be converted to an empty object (one has to throw an error to proclaim failure in constructors).  They also both evaluate to false in boolean contexts. The only real difference I can think of is that one evaluates to NaN, the other to 0 in numeric contexts.  So why is there both undefined and null if this just confuses programmers who are incorrectly checking for null when trying to find out whether a property has been set or not?  What I'd like to know is if anyone has a reasonable example where it's necessary to use null which couldn't be expressed using undefined instead.  So the general consensus seems to be that undefined means 'there is no such property' while null means 'the property does exist, but holds no value'.  I could live with that if JavaScript implementations would actually enforce this behavior - but undefined is a perfectly valid primitive value, so it can easily be assigned to existing properties to break this contract. Therefore, if you want to make sure if a property exists, you have to use the in operator or hasOwnProperty() anyway. So once again: what's the practical use for separate values for undefined and null?  I actually use undefined when I want to unset the values of properties no longer in use but which I don't want to delete. Should I use null instead?
62317
In the early days of C++ when it was bolted on top of C, you could not use NULL as it was defined as (void*)0. You could not assign NULL to any pointer other than void*, which made it kind of useless. Back in those days, it was accepted that you used 0 (zero) for null pointers.  To this day, I have continued to use zero as a null pointer but those around me insist on using NULL. I personally do not see any benefit to giving a name (NULL) to an existing value - and since I also like to test pointers as truth values:  if (p &amp;&amp; !q)   do_something();   then using zero makes more sense (as in if you use NULL, you cannot logically use p &amp;&amp; !q - you need to explicitly compare against NULL, unless you assume NULL is zero, in which case why use NULL).  Is there any objective reason to prefer zero over NULL (or vice versa), or is all just personal preference?  Edit: I should add (and meant to originally say) that with RAII and exceptions, I rarely use zero/NULL pointers, but sometimes you do need them still.
86715
I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is  if you want to look at all of the code.  Here are the important parts:  private RpcMap map;  public &lt;X&gt; X get(String property) {   if (allowNestedValues &amp;&amp; NestedModelUtil.isNestedProperty(property)) {     return (X)NestedModelUtil.getNestedValue(this, property);   }   return map == null ? null : (X) map.get(property); }   X is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the &lt;X&gt; in the public method signature.  I've tried to call this method with the following two examples to see what happens:  public Date getExpiredate() {     return  get("expiredate"); }  public String getSubject() {     return  get("subject"); }   They compile and show no errors or warnings.  I would think at the very least I would have to do a cast to get this to work.  Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime?  This seems counter to what generics are supposed to do.  Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better?  I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in.
120685
It seems to me that a lot of my debugging time is spent chasing down null-reference exceptions in complex statements. For instance:  For Each game As IHomeGame in _GamesToOpen.GetIterator()   Why, when I get a NullReferenceException, can I get the line number in the stack trace, but not the name of the object that equals null. In other words, why:  Object reference not set to an instance of an object.   instead of  _GamesToOpen is not set to an instance of an object.   or  Anonymous object returned by _GamesToOpen.GetIterator() is null.   or  game was set to null.   Is this strictly a design choice, meant to protect the anonymity of the code or is there a compelling reason in compiler design not to include this information in the debug-time exception?
79610
an example code what I try to do will surely do better than my english:  public bool IsNumericValueInBounds (string value, Type numericType) {   double d = double.NaN;         bool inBounds = (bool)numericType.GetMethod ("TryParse").Invoke (null, new object[] { value, d });    return inBounds; }   Unfortunately the TryParse method needs an out parameter so this doesn't work. any ideas how to solve this?  (ps.: would'nt this be a nice example for duck typing? - because i know every numericType has an "TryParse" or I am mistaken?)
107240
Quite often, in programming we get situations where null checks show up in particularly large numbers. I'm talking about things like:  if (doc != null) {   if (doc.Element != null)   {     ... and so on   }   else     throw new Exception("Element cannot be null"); } else {   throw new Exception("document cannot be null"); }   Basically, the whole thing turns into an unreadable nightmare, so I'm wondering: is there an easier way to describe what I'm trying to do above? (In addition to null checks, I get things like string.IsNullOrEmpty from time to time.)  Accepted answer: I accepted the answer that has  because the approach described is innovative, and is precisely what I want. Thanks Shawn!
40162
Please demonstrate how the ternary operator works with a regular if/else block. Example:  Boolean isValueBig = value &gt; 100 ? true : false;     Exact Duplicate:
13332
I am trying to use a  as input and then creating a query with it - so I need a .    I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me.
37105
I am using java language,I have a method that is supposed to return an object if it is found. If it is not found, should I:  return null throw an exception other  Which is the best practise or idiom?
108596
I have a custom object that I want to set a unique key based on on lookup values. When I tried to create a workflow update I was blowing past the size limit so I developed it into a trigger and it seems to be working as intended.   I thought since I am already developing a field update trigger, I might as well add on a default name method so everything is contained into one file as opposed to having workflow and triggers updating the record.   When I introduced this method it returns "null null".   public static void setRecordName(List&lt;Responsible_Party__c&gt; newList) {     for(Responsible_Party__c r : newList)     {         r.Name = r.Practice__r.Name + ' ' + r.User__r.Name;     } }   Where practice is a lookup to another custom object and user is a lookup to the user object.   If I change the values to just use the field:  public static void setRecordName(List&lt;Responsible_Party__c&gt; newList) {     for(Responsible_Party__c r : newList)     {         r.Name = r.Practice__c + ' ' + r.User__c;     } }   I get "a1Gg00000049v9xEAA 005A0000006ykwnIAA". How can I get the names to display and not null?
37382
I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:  String s = new String("silly");   Because it creates unnecessary String objects. But instead it should be written like this:  String s = "No longer silly";   Ok fine so far...However, given this class:  public final class CaseInsensitiveString {     private String s;     public CaseInsensitiveString(String s) {         if (s == null) {             throw new NullPointerException();         }         this.s = s;     }     :     : }  CaseInsensitiveString cis = new CaseInsensitiveString("Polish"); String s = "polish";    Why is the first statement ok? Shouldn't it be   CaseInsensitiveString cis = "Polish"; How do I make CaseInsensitiveString behave like String so the above statement is OK (with and without extending String)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?