Tuesday, March 26, 2019

Java Basics - Instantiation of objects

I was learning Java and came across this code snippet. Have an answer for that but I am not exactly understanding how it works.



I have a class Books



class Books {
String author;
String title;
}



Then I have test class



class TestForBook {

Books[] myBooks = new Books[3]; // doubt : 1
System.out.println('myBooks length is ::' + myBooks.length);//prints 3. Its correct.

myBooks[0].title = 'Book1 title'; // This throws null pointer exception


myBooks[0] = new Books();
myBooks[0].title = 'Book1 title'; //works fine after above line
}


I want to understand why even after declaring array of type Books, array values have null(doubt : 1 in comments, I am referring to that line).



I do not know what concept of Java I am missing. And how/from where I can learn these kind of topics. Any resource or books suggestion also would be appreciable. Thanks.




It is not duplicate of question id : 1922677. Solution is available there(I have also given the solution) but I wanted to know why it is like that. I mean even after declaring, why it has null was my question.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...