Java function return null

Зачем return null в конце?

Здравствуйте. Подскажете почему в конце метода пишется return null? Написал, потому что IDEA предложила. Сам не понимаю для чего оно там.

public String toString()  if (mother == null && father == null) return "Cat name is " + name + ", no mother, no father "; else if (mother != null && father == null) return "Cat name is " + name + ", mother is " + mother.name + ", no father"; else if (mother == null && father != null) return "Cat name is " + name + ", no mother, father is " + father.name; else if (mother != null && father != null) return "Cat name is " + name + ", mother is " + mother.name + ", father is " + father.name; return null; >

JavaRush — это интерактивный онлайн-курс по изучению Java-программирования c нуля. Он содержит 1200 практических задач с проверкой решения в один клик, необходимый минимум теории по основам Java и мотивирующие фишки, которые помогут пройти курс до конца: игры, опросы, интересные проекты и статьи об эффективном обучении и карьере Java‑девелопера.

Источник

Зачем return null в конце?

Здравствуйте. Подскажете почему в конце метода пишется return null? Написал, потому что IDEA предложила. Сам не понимаю для чего оно там.

public String toString()  if (mother == null && father == null) return "Cat name is " + name + ", no mother, no father "; else if (mother != null && father == null) return "Cat name is " + name + ", mother is " + mother.name + ", no father"; else if (mother == null && father != null) return "Cat name is " + name + ", no mother, father is " + father.name; else if (mother != null && father != null) return "Cat name is " + name + ", mother is " + mother.name + ", father is " + father.name; return null; >

JavaRush — это интерактивный онлайн-курс по изучению Java-программирования c нуля. Он содержит 1200 практических задач с проверкой решения в один клик, необходимый минимум теории по основам Java и мотивирующие фишки, которые помогут пройти курс до конца: игры, опросы, интересные проекты и статьи об эффективном обучении и карьере Java‑девелопера.

Источник

Return Nothing From a Function in Java

Return Nothing From a Function in Java

  1. Return Nothing in an Integer Function in Java
  2. Return Nothing in a String Function in Java
  3. Return Nothing in Any Object Function in Java

This tutorial introduces how to return nothing in function in Java.

Every function that has a return type in its signature must return a value of the same type, else the compile will generate an error, and the code will not execute. It means a return value is a value that is returned to the caller function, and if we wish to return nothing, then we will have to return some default value.

For example, we can return null for String type and 0 for the integer value to handle such a situation. Let’s understand with some examples.

Return Nothing in an Integer Function in Java

In this example, we have a static method that returns an integer, but we want to return nothing in a special case, then we return 0 only. Although there is nothing in integer to return, we can do this to achieve our objective.

public class SimpleTesting  public static void main(String[] args)  int result = getMax(12, 12);  System.out.println(result);  >   public static int getMax(int a, int b)   if(a>b)   return a;  >  else if (b>a)   return b;  >  return 0; // similar to nothing in int  > > 

Return Nothing in a String Function in Java

In this example, we have a static method that returns a String, but we want to return nothing in a special case, then we return null only. Although there is nothing like nothing in String to return, we can achieve our objective.

public class SimpleTesting  public static void main(String[] args)  String result = getMax("rohan", "sohan");  System.out.println("result "+result);  result = getMax("sohan", "sohan");  System.out.println("result "+result);  >   public static String getMax(String a, String b)   if(a.compareTo(b)>0)   return a;  >  else if (a.compareTo(b)0)   return b;  >  return null; // similar to nothing in String  > > 

Return Nothing in Any Object Function in Java

In this example, we have a static method that returns an integer object, but we want to return nothing in a special case, then we return null only as null is a default value for objects in Java. Although there is nothing like nothing in objects to return, we can achieve our objective.

We can use this for any other object as well. See the example below.

import java.util.ArrayList; import java.util.Collections; import java.util.List;  public class SimpleTesting  public static void main(String[] args)  ListInteger> list = new ArrayList<>();  list.add(23);  list.add(32);  list.add(33);  System.out.println(list);  Integer result = getMax(list);  System.out.println("result "+result);  >   public static Integer getMax(ListInteger> list)   if(Collections.max(list)>100)   return 100;  >  else if (Collections.max(list)50)   return Collections.max(list);  >  return null; // similar to nothing in Integer object  > > 

Related Article — Java Function

Источник

Stop Returning Null in Java

“ I call it my billion-dollar mistake.

At that time, I was designing the first comprehensive type system for references in an object-oriented language.

My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement.

This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years. ”

Overview

In this article, we’ll explain why using null to represent the absence of a return value is a bad approach. We’ll propose some better alternatives to make our code cleaner and less error-prone.

Pitfalls of Null

In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing.

Blog blog = null; long // NullPointerException

The compiler assigns null to any uninitialized static and instance members of reference type.

To illustrate this point, let’s take a look at a class:

public class Blog < private long id; // 0 private String name; // null private Listarticles; // null public long getId() < return id; >public String getName() < return name; >public List getArticles() < return articles; >>

In the absence of a constructor, the getArticles() and getName() methods will return a null reference.

Writing methods that return null forces the calling code to be littered with guard clauses like this:

if (blog.getName() != null) < int nameLength = blog.getName().count(); >if (blog.getArticles() != null)

This is annoying, difficult to read, and susceptible to run-time exceptions if anyone misses a null check anywhere.

Return an Empty Collection

If the method returns a collection type, then we can simply substitute an empty collection.

Java 5+

The Collections class has a static method for this purpose:

return Collections.emptyList();

Java 9

Java 9 introduced a new factory method for this:

Both of these return an immutable list so the calling code should make no attempt to modify it.

Return an Optional object

Java 8 introduced a class called java.util.Optional that’s designed to address the pain points associated with null values.

An Optional is a container that can either be empty or contain a non-null value.

Brian Goetz, Java Language Architect at Oracle, explained the reasoning behind adding its inclusion:

“ Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent “no result”, and using null for such was overwhelmingly likely to cause errors. ”

We can use Optional.empty() to represent empty container and Optional.of(value) to represent an actual value.

public Optional getBlog(long id) < // Blog not found if (!found) < return Optional.empty(); >// Blog found return Optional.of(blog); >

We can use the ifPresent() method to retrieve the value if it exists:

Optional blog = getBlog(100); blog.ifPresent(System.out::println);

The null check has been abstracted away and enforced by the type system. If the Optional object were empty above, then nothing would be printed.

Return a Null Object

The Null Object Pattern is described in the Gang of Four’s Design Patterns book. The intent of the pattern is to identify behavior that should occur when a null is encountered and encapsulate it using a static constant.

Let’s expand on the previous Blog class example:

public class Blog < public static Blog NOT_FOUND = new Blog(0, "Blog Not Found", Collections.emptyList()); private long id; private String name; private Listarticles; public Blog (long id, String name, List articles) < this.id = id; this.name = name; this.articles = articles; >public long getId() < return id; >public List getArticles() < return articles; >>

On line 2, we’ve declared a constant to represent our null object. It’s a Blog object with some sensible values for a non-existent blog.

Throw an Exception

Exceptions should be reserved for exceptional conditions. If we always expect to find a value then throwing an exception makes sense.

For example, we could throw an unchecked exception if an ID passed to our method isn’t found in the database.

throw new IllegalArgumentException("Invalid Blog ID");

The decision to use an exception when there is nothing to return is highly dependent on the nature of the application.

Источник

can we return null?

send pies

posted 14 years ago

  • Report post to moderator
  • I am reviewing the code and found that method returns null in the below code.
    Please think as per code review.
    Is it valid to return null as it may lead others to take care of Nullpointer Exception?

    public Image getImage(Object item) try if (item instanceof IMarker) return getBreakpointImage((IBreakpoint) bp);
    >

    if(item instanceof IUDTThread) return getUDTThreadImage((IUDTThread)item);
    >
    > catch (CoreException e) UDTDebugUIPlugin.logError(e);
    >
    return null;
    >

    Sheriff

    Chrome

    send pies

    posted 14 years ago

  • Report post to moderator
  • Whether it is valid to return null is up to your business logic. Sometimes you want to return null indicating something is wrong, sometimes you want to throw an exception.

    For instance, java.util.Map’s get method returns null if there is no key-value mapping for the specified key. java.util.List’s get method on the other hand throws an IndexOutOfBoundsException if the index is invalid.

    Should you choose to allow a null return value, you should document that this is a valid return value. Then programmers that call your method know that they should check if the return value is null:

    SCJP 1.4 — SCJP 6 — SCWCD 5 — OCEEJBD 6 — OCEJPAD 6
    How To Ask Questions How To Answer Questions

    Источник

    Читайте также:  Javascript как вывести символ
    Оцените статью