What is a Java Object?

What is a Java object?

An object can be defined as a collection of variables, which when viewed collectively represents a single, complex entity, and a collection of methods providing
operations relevant to that entity.  Concisely, objects encapsulate state and behavior.

After primitive types, all other variables in the Java programming language are reference types, better known as objects. Objects differ from primitives in many ways, but one of the most important distinctions is that there is a notation for the absence of an object, null. Variables can be set to null, and methods can return null too. Attempting to call a method on a null reference throws a NullPointerException.  

Dealing with NullPointerExceptions:

@Test(expected =
NullPointerException.class)
public void
expectNullPointerExceptionToBeThrown()
{
final String s =
null;
final int
stringLength =
s.length();
}

Objects are reference types. What  exactly does this mean? With primitive types, when declaring a variable, int i = 42, this is being assigned to a location in memory, with the value 42. If, later in the program, another variable is assigned to hold the value currently represented by i, say, int j = i, then another location in memory has been assigned to that same value. Subsequent changes to i do not affect the value of j, and vice versa.

In Java, a statement such as new ArrayList(20), requests an area in memory to store that data. When that created object is assigned to a variable, List myList = new ArrayList(20), then it can be said that myList points to that memory location. On the surface, this appears to act the same as a primitive type assignment, but it is not. If several variables are assigned to that same created object, known as an instance, then they are pointing to the same memory location. Making any changes to one instance will be reflected when accessing the other.

Several variables referencing the same instance in memory:

@Test
public void
objectMemoryAssignment()
{
List<String> list1 =
new ArrayList<>(20);
list1.add(“entry in
list1”);
assertTrue(list1.size()
== 1);
List list2 = list1;
list2.add(“entry in
list2”);
assertTrue(list1.size()
== 2);
}

Java Tips

See also
Assertion in Java

Do you have a Java Problem?
Ask It in The Java Forum

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.