Tech With Tim Logo
Go back

Introduction to Objects

What is an Object?

In previous tutorials you may have heard me mention the word object and have probably wondered what the heck that means. Well, without knowing it we have been using and creating objects in all of the previous tutorials. Actually almost everything in Java is an object! When we do something like create a new String or a Scanner or even a Map we are creating an object.

An object is said to be of a certain type and each type of object has different properties associated with it.

For example when we used a Scanner called sc we could do something like sc.next(). However, if we tried to do that on something like a String that would not be valid...

In the next tutorial we will learn how to create our own objects.

Methods

Another word that was mentioned quite often is method. You can think of a method like a function that can only be used on certain objects. We can call methods on objects by putting a "." and then the method name.

Take for example the method .next(). .next() can only be used on objects of type Scanner, so if we create a scanner we can use the .next() method by typing the scanner name followed by .next().

Scanner sc = new Scanner(); // A new object of type Scanner

String input = sc.next();  // A new String object that is = to whatever sc.next() gives us
// we called the .next() method on the Scanner object sc.

Other methods we've used include .toString(), .parseInt(), .append(), .add().

Notice that these methods only worked on objects of a certain type.

Examples of Objects

All of the following lines of code create a new object of a certain type.

import java.util.HashMap; 
import java.util.Map;

String x = "hello";

Scanner sc = new Scanner(System.in);

HashMap<String, Integer> map = new HashMap<>();

Primitive vs Reference Types

I will not talk about this too much but in Java there is something called a primitive data type. These data types are immutable and cannot be changed. To see a list of primitive types click here. Any other type is known as a reference type and is mutable. This is because it makes reference to an object.

Design & Development by Ibezio Logo