null and NullPointerexception in Java stream [duplicate]





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-1
















This question already has an answer here:




  • What is a NullPointerException, and how do I fix it?

    12 answers




Here is my example:



import java.util.ArrayList;
import java.util.stream.IntStream;


public class Example {

public static void main( String args ) {

ArrayList<Integer> list = new ArrayList<>();
list.add(0);list.add(1);list.add(2);

SomeObject a = IntStream.range(0,list.size())
.filter(i->list.get(i)==3 || list.get(i)==4)
.mapToObj(i->new SomeObject(i,list.get(i)))
.findFirst()
.orElse(null);
System.out.println(a);
}
}

class SomeObject{
int index;
int value;
SomeObject(int index,int value){
this.index=index;
this.value=value;
}

@Override
public String toString() {
return this.index+" "+this.value;
}
}


Why when we are calling System.out.println(a); we don't get a NullPointerException?



As the orElse(null) returns an object pointing to null. If not what is the difference between the null in the orElse method and an object pointing to null?










share|improve this question















marked as duplicate by Seelenvirtuose, Naman java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 22 '18 at 13:15


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 3





    System.out.println can print a null reference.

    – Eran
    Nov 22 '18 at 11:49











  • why it is not the case for an optional pointing to null. for that i was confused.if i put .get(); in place of orElse(null), i will get an exception.

    – zak zak
    Nov 22 '18 at 11:53













  • for that sake SomeObject b =null; System.out.println(b); would not throw an NPE either. Strongly believe that this is a duplicate. Voting to close as duplicate. There are answer stating, what causes NPE as well in the linked question.

    – Naman
    Nov 22 '18 at 13:15




















-1
















This question already has an answer here:




  • What is a NullPointerException, and how do I fix it?

    12 answers




Here is my example:



import java.util.ArrayList;
import java.util.stream.IntStream;


public class Example {

public static void main( String args ) {

ArrayList<Integer> list = new ArrayList<>();
list.add(0);list.add(1);list.add(2);

SomeObject a = IntStream.range(0,list.size())
.filter(i->list.get(i)==3 || list.get(i)==4)
.mapToObj(i->new SomeObject(i,list.get(i)))
.findFirst()
.orElse(null);
System.out.println(a);
}
}

class SomeObject{
int index;
int value;
SomeObject(int index,int value){
this.index=index;
this.value=value;
}

@Override
public String toString() {
return this.index+" "+this.value;
}
}


Why when we are calling System.out.println(a); we don't get a NullPointerException?



As the orElse(null) returns an object pointing to null. If not what is the difference between the null in the orElse method and an object pointing to null?










share|improve this question















marked as duplicate by Seelenvirtuose, Naman java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 22 '18 at 13:15


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 3





    System.out.println can print a null reference.

    – Eran
    Nov 22 '18 at 11:49











  • why it is not the case for an optional pointing to null. for that i was confused.if i put .get(); in place of orElse(null), i will get an exception.

    – zak zak
    Nov 22 '18 at 11:53













  • for that sake SomeObject b =null; System.out.println(b); would not throw an NPE either. Strongly believe that this is a duplicate. Voting to close as duplicate. There are answer stating, what causes NPE as well in the linked question.

    – Naman
    Nov 22 '18 at 13:15
















-1












-1








-1









This question already has an answer here:




  • What is a NullPointerException, and how do I fix it?

    12 answers




Here is my example:



import java.util.ArrayList;
import java.util.stream.IntStream;


public class Example {

public static void main( String args ) {

ArrayList<Integer> list = new ArrayList<>();
list.add(0);list.add(1);list.add(2);

SomeObject a = IntStream.range(0,list.size())
.filter(i->list.get(i)==3 || list.get(i)==4)
.mapToObj(i->new SomeObject(i,list.get(i)))
.findFirst()
.orElse(null);
System.out.println(a);
}
}

class SomeObject{
int index;
int value;
SomeObject(int index,int value){
this.index=index;
this.value=value;
}

@Override
public String toString() {
return this.index+" "+this.value;
}
}


Why when we are calling System.out.println(a); we don't get a NullPointerException?



As the orElse(null) returns an object pointing to null. If not what is the difference between the null in the orElse method and an object pointing to null?










share|improve this question

















This question already has an answer here:




  • What is a NullPointerException, and how do I fix it?

    12 answers




Here is my example:



import java.util.ArrayList;
import java.util.stream.IntStream;


public class Example {

public static void main( String args ) {

ArrayList<Integer> list = new ArrayList<>();
list.add(0);list.add(1);list.add(2);

SomeObject a = IntStream.range(0,list.size())
.filter(i->list.get(i)==3 || list.get(i)==4)
.mapToObj(i->new SomeObject(i,list.get(i)))
.findFirst()
.orElse(null);
System.out.println(a);
}
}

class SomeObject{
int index;
int value;
SomeObject(int index,int value){
this.index=index;
this.value=value;
}

@Override
public String toString() {
return this.index+" "+this.value;
}
}


Why when we are calling System.out.println(a); we don't get a NullPointerException?



As the orElse(null) returns an object pointing to null. If not what is the difference between the null in the orElse method and an object pointing to null?





This question already has an answer here:




  • What is a NullPointerException, and how do I fix it?

    12 answers








java nullpointerexception java-stream






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 12:19









Stefan Zobel

2,51031931




2,51031931










asked Nov 22 '18 at 11:48









zak zakzak zak

525317




525317




marked as duplicate by Seelenvirtuose, Naman java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 22 '18 at 13:15


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Seelenvirtuose, Naman java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 22 '18 at 13:15


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 3





    System.out.println can print a null reference.

    – Eran
    Nov 22 '18 at 11:49











  • why it is not the case for an optional pointing to null. for that i was confused.if i put .get(); in place of orElse(null), i will get an exception.

    – zak zak
    Nov 22 '18 at 11:53













  • for that sake SomeObject b =null; System.out.println(b); would not throw an NPE either. Strongly believe that this is a duplicate. Voting to close as duplicate. There are answer stating, what causes NPE as well in the linked question.

    – Naman
    Nov 22 '18 at 13:15
















  • 3





    System.out.println can print a null reference.

    – Eran
    Nov 22 '18 at 11:49











  • why it is not the case for an optional pointing to null. for that i was confused.if i put .get(); in place of orElse(null), i will get an exception.

    – zak zak
    Nov 22 '18 at 11:53













  • for that sake SomeObject b =null; System.out.println(b); would not throw an NPE either. Strongly believe that this is a duplicate. Voting to close as duplicate. There are answer stating, what causes NPE as well in the linked question.

    – Naman
    Nov 22 '18 at 13:15










3




3





System.out.println can print a null reference.

– Eran
Nov 22 '18 at 11:49





System.out.println can print a null reference.

– Eran
Nov 22 '18 at 11:49













why it is not the case for an optional pointing to null. for that i was confused.if i put .get(); in place of orElse(null), i will get an exception.

– zak zak
Nov 22 '18 at 11:53







why it is not the case for an optional pointing to null. for that i was confused.if i put .get(); in place of orElse(null), i will get an exception.

– zak zak
Nov 22 '18 at 11:53















for that sake SomeObject b =null; System.out.println(b); would not throw an NPE either. Strongly believe that this is a duplicate. Voting to close as duplicate. There are answer stating, what causes NPE as well in the linked question.

– Naman
Nov 22 '18 at 13:15







for that sake SomeObject b =null; System.out.println(b); would not throw an NPE either. Strongly believe that this is a duplicate. Voting to close as duplicate. There are answer stating, what causes NPE as well in the linked question.

– Naman
Nov 22 '18 at 13:15














2 Answers
2






active

oldest

votes


















1














Let's go a little bit in detail...



System.out.println(a); calls this overload of println:



public void println(Object x)


which states:




Prints an Object and then terminate the line. This method calls at
first String.valueOf(x) to get the printed object's string value, then
behaves as though it invokes print(String) and then println().




Given the above let's go to the String.valueOf method:



public static String valueOf(Object obj)


which states:




Returns: if the argument is null, then a string equal to "null";
otherwise, the value of obj.toString() is returned.




Since obj is null a "null" is returned and obj.toString() is never invoked hence no exception.





As for your following comment:




why it is not the case for an optional pointing to null. for that i
was confused.if i put .get(); in place of orElse(null), i will get an
exception.




an Optional<T> doesn't "point to null" (wrong terminology being used, usually we say an Optional either has a present state or absent state).



Invoking .get() carelessly from an Optional<T> should be avoided unless absolutely sure the Optional<T> is not empty.



You receive a NoSuchElementException in this case simply because there is no value present and this is documented in the Optional<T> API.






share|improve this answer

































    1















    why it is not the case for an optional pointing to null.




    To answer this comment as I think this is what you are trying to ask in the question, see this answer.



    An optional, introduced in Java 8, is a container object which is used to contain specifically, not-null objects. Instead, optional object is used to represent null with absent value.



    The fact that the findFirst() method returns Optional is a questionable design decision. But that's just how it is currently.






    share|improve this answer






























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Let's go a little bit in detail...



      System.out.println(a); calls this overload of println:



      public void println(Object x)


      which states:




      Prints an Object and then terminate the line. This method calls at
      first String.valueOf(x) to get the printed object's string value, then
      behaves as though it invokes print(String) and then println().




      Given the above let's go to the String.valueOf method:



      public static String valueOf(Object obj)


      which states:




      Returns: if the argument is null, then a string equal to "null";
      otherwise, the value of obj.toString() is returned.




      Since obj is null a "null" is returned and obj.toString() is never invoked hence no exception.





      As for your following comment:




      why it is not the case for an optional pointing to null. for that i
      was confused.if i put .get(); in place of orElse(null), i will get an
      exception.




      an Optional<T> doesn't "point to null" (wrong terminology being used, usually we say an Optional either has a present state or absent state).



      Invoking .get() carelessly from an Optional<T> should be avoided unless absolutely sure the Optional<T> is not empty.



      You receive a NoSuchElementException in this case simply because there is no value present and this is documented in the Optional<T> API.






      share|improve this answer






























        1














        Let's go a little bit in detail...



        System.out.println(a); calls this overload of println:



        public void println(Object x)


        which states:




        Prints an Object and then terminate the line. This method calls at
        first String.valueOf(x) to get the printed object's string value, then
        behaves as though it invokes print(String) and then println().




        Given the above let's go to the String.valueOf method:



        public static String valueOf(Object obj)


        which states:




        Returns: if the argument is null, then a string equal to "null";
        otherwise, the value of obj.toString() is returned.




        Since obj is null a "null" is returned and obj.toString() is never invoked hence no exception.





        As for your following comment:




        why it is not the case for an optional pointing to null. for that i
        was confused.if i put .get(); in place of orElse(null), i will get an
        exception.




        an Optional<T> doesn't "point to null" (wrong terminology being used, usually we say an Optional either has a present state or absent state).



        Invoking .get() carelessly from an Optional<T> should be avoided unless absolutely sure the Optional<T> is not empty.



        You receive a NoSuchElementException in this case simply because there is no value present and this is documented in the Optional<T> API.






        share|improve this answer




























          1












          1








          1







          Let's go a little bit in detail...



          System.out.println(a); calls this overload of println:



          public void println(Object x)


          which states:




          Prints an Object and then terminate the line. This method calls at
          first String.valueOf(x) to get the printed object's string value, then
          behaves as though it invokes print(String) and then println().




          Given the above let's go to the String.valueOf method:



          public static String valueOf(Object obj)


          which states:




          Returns: if the argument is null, then a string equal to "null";
          otherwise, the value of obj.toString() is returned.




          Since obj is null a "null" is returned and obj.toString() is never invoked hence no exception.





          As for your following comment:




          why it is not the case for an optional pointing to null. for that i
          was confused.if i put .get(); in place of orElse(null), i will get an
          exception.




          an Optional<T> doesn't "point to null" (wrong terminology being used, usually we say an Optional either has a present state or absent state).



          Invoking .get() carelessly from an Optional<T> should be avoided unless absolutely sure the Optional<T> is not empty.



          You receive a NoSuchElementException in this case simply because there is no value present and this is documented in the Optional<T> API.






          share|improve this answer















          Let's go a little bit in detail...



          System.out.println(a); calls this overload of println:



          public void println(Object x)


          which states:




          Prints an Object and then terminate the line. This method calls at
          first String.valueOf(x) to get the printed object's string value, then
          behaves as though it invokes print(String) and then println().




          Given the above let's go to the String.valueOf method:



          public static String valueOf(Object obj)


          which states:




          Returns: if the argument is null, then a string equal to "null";
          otherwise, the value of obj.toString() is returned.




          Since obj is null a "null" is returned and obj.toString() is never invoked hence no exception.





          As for your following comment:




          why it is not the case for an optional pointing to null. for that i
          was confused.if i put .get(); in place of orElse(null), i will get an
          exception.




          an Optional<T> doesn't "point to null" (wrong terminology being used, usually we say an Optional either has a present state or absent state).



          Invoking .get() carelessly from an Optional<T> should be avoided unless absolutely sure the Optional<T> is not empty.



          You receive a NoSuchElementException in this case simply because there is no value present and this is documented in the Optional<T> API.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 22 '18 at 12:12

























          answered Nov 22 '18 at 12:05









          AomineAomine

          42.8k74678




          42.8k74678

























              1















              why it is not the case for an optional pointing to null.




              To answer this comment as I think this is what you are trying to ask in the question, see this answer.



              An optional, introduced in Java 8, is a container object which is used to contain specifically, not-null objects. Instead, optional object is used to represent null with absent value.



              The fact that the findFirst() method returns Optional is a questionable design decision. But that's just how it is currently.






              share|improve this answer




























                1















                why it is not the case for an optional pointing to null.




                To answer this comment as I think this is what you are trying to ask in the question, see this answer.



                An optional, introduced in Java 8, is a container object which is used to contain specifically, not-null objects. Instead, optional object is used to represent null with absent value.



                The fact that the findFirst() method returns Optional is a questionable design decision. But that's just how it is currently.






                share|improve this answer


























                  1












                  1








                  1








                  why it is not the case for an optional pointing to null.




                  To answer this comment as I think this is what you are trying to ask in the question, see this answer.



                  An optional, introduced in Java 8, is a container object which is used to contain specifically, not-null objects. Instead, optional object is used to represent null with absent value.



                  The fact that the findFirst() method returns Optional is a questionable design decision. But that's just how it is currently.






                  share|improve this answer














                  why it is not the case for an optional pointing to null.




                  To answer this comment as I think this is what you are trying to ask in the question, see this answer.



                  An optional, introduced in Java 8, is a container object which is used to contain specifically, not-null objects. Instead, optional object is used to represent null with absent value.



                  The fact that the findFirst() method returns Optional is a questionable design decision. But that's just how it is currently.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 22 '18 at 12:15









                  John KimJohn Kim

                  413211




                  413211















                      Popular posts from this blog

                      鏡平學校

                      ꓛꓣだゔៀៅຸ໢ທຮ໕໒ ,ໂ'໥໓າ໼ឨឲ៵៭ៈゎゔit''䖳𥁄卿' ☨₤₨こゎもょの;ꜹꟚꞖꞵꟅꞛေၦေɯ,ɨɡ𛃵𛁹ޝ޳ޠ޾,ޤޒޯ޾𫝒𫠁သ𛅤チョ'サノބޘދ𛁐ᶿᶇᶀᶋᶠ㨑㽹⻮ꧬ꧹؍۩وَؠ㇕㇃㇪ ㇦㇋㇋ṜẰᵡᴠ 軌ᵕ搜۳ٰޗޮ޷ސޯ𫖾𫅀ल, ꙭ꙰ꚅꙁꚊꞻꝔ꟠Ꝭㄤﺟޱސꧨꧼ꧴ꧯꧽ꧲ꧯ'⽹⽭⾁⿞⼳⽋២៩ញណើꩯꩤ꩸ꩮᶻᶺᶧᶂ𫳲𫪭𬸄𫵰𬖩𬫣𬊉ၲ𛅬㕦䬺𫝌𫝼,,𫟖𫞽ហៅ஫㆔ాఆఅꙒꚞꙍ,Ꙟ꙱エ ,ポテ,フࢰࢯ𫟠𫞶 𫝤𫟠ﺕﹱﻜﻣ𪵕𪭸𪻆𪾩𫔷ġ,ŧآꞪ꟥,ꞔꝻ♚☹⛵𛀌ꬷꭞȄƁƪƬșƦǙǗdžƝǯǧⱦⱰꓕꓢႋ神 ဴ၀க௭எ௫ឫោ ' េㇷㇴㇼ神ㇸㇲㇽㇴㇼㇻㇸ'ㇸㇿㇸㇹㇰㆣꓚꓤ₡₧ ㄨㄟ㄂ㄖㄎ໗ツڒذ₶।ऩछएोञयूटक़कयँृी,冬'𛅢𛅥ㇱㇵㇶ𥄥𦒽𠣧𠊓𧢖𥞘𩔋цѰㄠſtʯʭɿʆʗʍʩɷɛ,əʏダヵㄐㄘR{gỚṖḺờṠṫảḙḭᴮᵏᴘᵀᵷᵕᴜᴏᵾq﮲ﲿﴽﭙ軌ﰬﶚﶧ﫲Ҝжюїкӈㇴffצּ﬘﭅﬈軌'ffistfflſtffतभफɳɰʊɲʎ𛁱𛁖𛁮𛀉 𛂯𛀞నఋŀŲ 𫟲𫠖𫞺ຆຆ ໹້໕໗ๆทԊꧢꧠ꧰ꓱ⿝⼑ŎḬẃẖỐẅ ,ờỰỈỗﮊDžȩꭏꭎꬻ꭮ꬿꭖꭥꭅ㇭神 ⾈ꓵꓑ⺄㄄ㄪㄙㄅㄇstA۵䞽ॶ𫞑𫝄㇉㇇゜軌𩜛𩳠Jﻺ‚Üမ႕ႌႊၐၸဓၞၞၡ៸wyvtᶎᶪᶹစဎ꣡꣰꣢꣤ٗ؋لㇳㇾㇻㇱ㆐㆔,,㆟Ⱶヤマފ޼ޝަݿݞݠݷݐ',ݘ,ݪݙݵ𬝉𬜁𫝨𫞘くせぉて¼óû×ó£…𛅑הㄙくԗԀ5606神45,神796'𪤻𫞧ꓐ㄁ㄘɥɺꓵꓲ3''7034׉ⱦⱠˆ“𫝋ȍ,ꩲ軌꩷ꩶꩧꩫఞ۔فڱێظペサ神ナᴦᵑ47 9238їﻂ䐊䔉㠸﬎ffiﬣ,לּᴷᴦᵛᵽ,ᴨᵤ ᵸᵥᴗᵈꚏꚉꚟ⻆rtǟƴ𬎎

                      Why https connections are so slow when debugging (stepping over) in Java?