EzDevInfo.com

null interview questions

Top null frequently asked interview questions

Remove empty array elements

Some elements in my array are an empty string. I need to remove those elements.

Code:

foreach($linksArray as $link)
{
    if($link == '')
    {
        unset($link);
    }
}
print_r($linksArray);

But it doesn't work, $linksArray still has empty elements. I have also tried doing it with the empty() function but the outcome is the same.


Source: (StackOverflow)

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null? I've got this code, but I'm not sure if it covers all cases:

function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}

Source: (StackOverflow)

Advertisements

What is the difference between null and undefined in JavaScript?

I want to know what the difference is between null and undefined in JavaScript.


Source: (StackOverflow)

null object in Python?

How do I refer to the null object in Python?


Source: (StackOverflow)

How do you check for an empty string in JavaScript?

I saw this thread, but I didn't see a JavaScript specific example. Is there a simple string.Empty available in JavaScript, or is it just a case of checking for ""?


Source: (StackOverflow)

Avoiding != null statements

The idiom I use the most when programming in Java is to test if object != null before I use it. This is to avoid a NullPointerException. I find the code very ugly, and it becomes unreadable.

Is there a good alternative to this?

I want to address the necessity to test every object if you want to access a field or method of this object. For example:

if (someobject != null) {
    someobject.doCalc();
}

In this case I will avoid a NullPointerException, and I don't know exactly if the object is null or not. These tests appear throughout my code as a consequence.


Source: (StackOverflow)

How to check for an undefined or null variable in JavaScript?

We are frequently using the following code pattern in our JavaScript code

if (typeof(some_variable) != 'undefined' && some_variable != null)
{
    // Do something with some_variable
}

Is there a less verbose way of checking that has the same effect?

According to some forums and literature saying simply the following should have the same effect.

if (some_variable)
{
    // Do something with some_variable
}

Unfortunately, Firebug evaluates such a statement as error on runtime when some_variable is undefined, whereas the first one is just fine for it. Is this only an (unwanted) behavior of Firebug or is there really some difference between those two ways?


Source: (StackOverflow)

Best explanation for languages without null

Every so often when programmers are complaining about null errors/exceptions someone asks what we do without null.

I have some basic idea of the coolness of option types, but I don't have the knowledge or languages skill to best express it. What is a great explanation of the following written in a way approachable to the average programmer that we could point that person towards?

  • The undesirability of having having references/pointers be nullable by default
  • How option types work including strategies to ease checking null cases such as
    • pattern matching and
    • monadic comprehensions
  • Alternative solution such as message eating nil
  • (other aspects I missed)

Source: (StackOverflow)

Which @NotNull Java annotation should I use?

I'm looking to make my code more readable as well as use tooling like IDE code inspection and/or static code analysis (FindBugs and Sonar) to avoid NullPointerExceptions. Many of the tools seem incompatible with each others' @NotNull/@NonNull/@Nonnull annotation and listing all of them in my code would be terrible to read. Any suggestions of which one is the 'best'? Here is the list of equivalent annotations I've found:

  • javax.validation.constraints.NotNull
    Created for runtime validation, not static analysis.
    documentation

  • edu.umd.cs.findbugs.annotations.NonNull
    Used by Findbugs static analysis and therefore Sonar
    documentation

  • javax.annotation.Nonnull
    This might work with Findbugs too, but JSR-305 is inactive.
    source

  • org.jetbrains.annotations.NotNull
    Used by IntelliJ IDEA IDE for static analysis.
    documentation

  • lombok.NonNull
    Used to control code generation in Project Lombok.
    Placeholder annotation since there is no standard.
    source, documentation

  • android.support.annotation.NonNull
    Marker annotation available in Android, provided by support-annotations package
    documentation


Source: (StackOverflow)

Cleaner way to do a null check in C#? [duplicate]

This question already has an answer here:

Suppose, I have this interface,

interface IContact
{
    IAddress address { get; set; }
}

interface IAddress
{
    string city { get; set; }
}

class Person : IPerson
{
    public IContact contact { get; set; }
}

class test
{
    private test()
    {
        var person = new Person();
        if (person.contact.address.city != null)
        {
            //this will never work if contact is itself null?
        }
    }
}

Person.Contact.Address.City != null (This works to check if City is null or not.)

However, this check fails if Address or Contact or Person itself is null.

Currently, one solution I could think of was this:

if (Person != null && Person.Contact!=null && Person.Contact.Address!= null && Person.Contact.Address.City != null)

{ 
    // Do some stuff here..
}

Is there a cleaner way of doing this?

I really don't like the null check being done as (something == null). Instead, is there another nice way to do something like the something.IsNull() method?


Source: (StackOverflow)

In Objective-C why should I check if self = [super init] is not nil?

I have a general question about writing init methods in Objective-C.

I see it everywhere (Apple's code, books, open source code, etc.) that an init method should check if self = [super init] is not nil before continuing with initialisation.

The default Apple template for an init method is:

- (id) init
{
    self = [super init];

    if (self != nil)
    {
        // your code here
    }

    return self;
}

Why?

I mean when is init ever going to return nil? If I called init on NSObject and got nil back, then something must be really screwed, right? And in that case, you might as well not even write a program...

Is it really that common that a class' init method may return nil? If so, in what case, and why?


Source: (StackOverflow)

Why is my Spring @Autowired field null?

Note: This is intended to be a canonical answer for a common problem.

I have a Spring @Service class (MileageFeeCalculator) that has an @Autowired field (rateService), but the field is null when I try to use it. The logs show that both the MileageFeeCalculator bean and the MileageRateService bean are being created, but I get a NullPointerException whenever I try to call the mileageCharge method on my service bean. Why isn't Spring autowiring the field?

Controller class:

@Controller
public class MileageFeeController {    
    @RequestMapping("/mileage/{miles}")
    @ResponseBody
    public float mileageFee(@PathVariable int miles) {
        MileageFeeCalculator calc = new MileageFeeCalculator();
        return calc.mileageCharge(miles);
    }
}

Service class:

@Service
public class MileageFeeCalculator {

    @Autowired
    private MileageRateService rateService; // <--- should be autowired, is null

    public float mileageCharge(final int miles) {
        return (miles * rateService.ratePerMile()); // <--- throws NPE
    }
}

Service bean that should be autowired in MileageFeeCalculator but isn't:

@Service
public class MileageRateService {
    public float ratePerMile() {
        return 0.565f;
    }
}

When I try to GET /mileage/3, I get this exception:

java.lang.NullPointerException: null
    at com.chrylis.example.spring_autowired_npe.MileageFeeCalculator.mileageCharge(MileageFeeCalculator.java:13)
    at com.chrylis.example.spring_autowired_npe.MileageFeeController.mileageFee(MileageFeeController.java:14)
    ...

Source: (StackOverflow)

Do you use NULL or 0 (zero) for pointers in C++?

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 && !q)
  do_something();

then using zero makes more sense (as in if you use NULL, you cannot logically use p && !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.


Source: (StackOverflow)

Check if object exists in JavaScript

How do I verify the existence of an object in JavaScript?

The following works:

if (!null)
   alert("GOT HERE");

But this fails:

if (!maybeObject)
   alert("GOT HERE");

Error: maybeObject is not defined.


Source: (StackOverflow)

How to check null objects in jQuery

I'm using jQuery and I want to check the existence of an element in my page. I have written following code, but it's not working:

if($("#btext" + i) != null) {
    //alert($("#btext" + i).text());
    $("#btext" + i).text("Branch " + i);
}

How do I check the existence of the element?


Source: (StackOverflow)