1. What is an object in Java?
An object is an instance of a class. It has state and behavior. The state is stored in fields and the behavior is stored in methods.
Full lesson: Java basic syntax
44 questions about Java with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.
An object is an instance of a class. It has state and behavior. The state is stored in fields and the behavior is stored in methods.
Full lesson: Java basic syntax
A class is a template for objects. It describes the state and behavior of its objects. Java code creates objects from the class.
Full lesson: Java basic syntax
Import the ArrayList class from java.util first. Then declare the type and the object name. The generic type must be a reference data type.
import java.util.ArrayList;
ArrayList<String> sites = new ArrayList<>();
Full lesson: Java arraylist
The Object class is the parent of all classes. Every class inherits from Object. A class without an explicit parent inherits Object automatically.
public class Example extends Object { }
Full lesson: Java object class
The add() method inserts an element into the list. Without an index, it appends the element to the end. With an index, it inserts the element at that position.
sites.add("Google");
sites.add(1, "Wiki");
Full lesson: Java arraylist add
The get() method returns the element at the given index. The index starts at zero. An index out of range throws an IndexOutOfBoundsException.
String name = sites.get(0);
Full lesson: Java arraylist get
The set() method replaces the element at the given index. It returns the element that was at that index before. An index out of range throws an IndexOutOfBoundsException.
String old = sites.set(0, "Bing");
Full lesson: Java arraylist set
The size() method returns the number of elements in the list. The count includes all current elements. The count does not include empty slots.
int count = sites.size();
Full lesson: Java arraylist size
The indexOf() method returns the index of the first match. It returns -1 when the element is absent. The search uses the equals() method.
int i = sites.indexOf("Google");
Full lesson: Java arraylist indexof
The lastIndexOf() method returns the index of the last match. It returns -1 when the element is absent. Use it to find a repeated element from the end.
int i = sites.lastIndexOf("Google");
Full lesson: Java arraylist lastindexof
Call the toString() method on the list. It returns the elements in square brackets. The elements are separated by a comma and a space.
System.out.println(sites.toString());
Full lesson: Java arraylist tostring
Use the removeIf() method with a predicate. The method removes every element that matches the predicate. It returns true when it removes at least one element.
sites.removeIf(s -> s.startsWith("G"));
Full lesson: Java arraylist removeif
Create a list from the first array with Arrays.asList(). Then call addAll() with the second array. Convert the list back to an array with toArray().
List list = new ArrayList(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
Full lesson: Arrays merge
Call the list() method on a File object for the directory. It returns a String array of names. It returns null when the path is not a directory.
File dir = new File("C:/temp");
String[] names = dir.list();
Full lesson: Java file list
The add() method needs a valid index. A list of size 3 accepts index 0 to 3 only. Index 5 is out of range and throws IndexOutOfBoundsException.
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add(5, "X"); // IndexOutOfBoundsException
Full lesson: Java arraylist add
A class starts with the class keyword and a name. The class body goes between two braces.
public class Car {
// fields and methods
}
Full lesson: Java basic syntax
You write the type first, then the name. You can add an equal sign and a value to initialize it.
int count = 10;
String name = "Java";
Full lesson: Java variable types
The eight types are byte, short, int, long, float, double, char, and boolean. Each type has a fixed size and range.
Full lesson: Java basic datatypes
A public class is visible to all other classes. A private method is visible only inside its own class.
public class Demo {
private void helper() { }
}
Full lesson: Java modifier types
You use the new keyword with the class name. This calls the class constructor.
Car myCar = new Car();
Full lesson: Java object classes
The clear() method removes all elements from the list. The list becomes empty but still exists.
list.clear();
Full lesson: Java arraylist clear
The addAll() method adds all elements from another collection to the list. It returns true if the list changes.
list.addAll(otherList);
Full lesson: Java arraylist addall
The remove() method deletes one element at a given index. It returns the removed element.
String removed = list.remove(2);
Full lesson: Java arraylist remove
You call the sort() method with a comparator. Use Comparator.naturalOrder() for ascending order.
list.sort(Comparator.naturalOrder());
Full lesson: Java arraylist sort
The toString() method returns the path string used to create the File object. It does not check if the file exists.
File f = new File("C:/test.txt");
System.out.println(f.toString());
Full lesson: Java file tostring
You call the listFiles() method on a File object that points to a directory. It returns an array of File objects.
File dir = new File("C:/temp");
File[] files = dir.listFiles();
Full lesson: Java file listfiles
The notify() method wakes up one thread that waits on the object monitor. The choice of thread is arbitrary.
synchronized (lock) {
lock.notify();
}
Full lesson: Java object notify
The notifyAll() method wakes up all threads that wait on the object monitor. They then compete for the lock.
synchronized (lock) {
lock.notifyAll();
}
Full lesson: Java object notifyall
The get() method throws an IndexOutOfBoundsException. Valid indices start at 0 and end at size minus 1.
list.get(list.size()); // throws exception
Full lesson: Java arraylist get
The clone() method makes a shallow copy. Changes to mutable elements in the copy also affect the original list.
ArrayList<String> copy = (ArrayList<String>) list.clone();
Full lesson: Java arraylist clone
The method returns the index of the first occurrence of a character or substring. It returns -1 if the character or substring is not found.
String s = "hello";
int i = s.indexOf('l');
System.out.println(i);
Full lesson: Java string indexof
You declare a local variable inside a method with a type and a name. You can also assign a value when you declare it.
public void exampleMethod() {
int localVar = 10;
System.out.println(localVar);
}
Full lesson: Java variable types
The default toString() method returns the class name, then an @ sign, then the hexadecimal hash code. This format is not easy to read.
Object obj = new Object();
System.out.println(obj.toString());
Full lesson: Java object tostring
You call the getClass() method on the object. The method returns a Class object that represents the runtime class.
String s = "hello";
System.out.println(s.getClass());
Full lesson: Java object getclass
The clone() method copies an ArrayList. It makes a shallow copy, so the new list shares element references with the old list.
ArrayList<String> a = new ArrayList<>();
a.add("A");
ArrayList<String> b = (ArrayList<String>) a.clone();
Full lesson: Java arraylist clone
The Hashtable class stores key/value pairs in a hash table. It supports synchronization, unlike HashMap.
Hashtable<String, Integer> h = new Hashtable<>();
h.put("one", 1);
System.out.println(h.get("one"));
Full lesson: Java hashtable class
The Dictionary class stores key/value pairs, similar to a Map. It is an abstract class, so you cannot create a Dictionary object directly.
// Dictionary is abstract, so use a subclass like Hashtable
Dictionary<String, String> d = new Hashtable<>();
d.put("key", "value");
Full lesson: Java dictionary class
The addAll() method throws a NullPointerException if the given collection is null. You must pass a non-null collection.
ArrayList<String> list = new ArrayList<>();
list.addAll(null); // throws NullPointerException
Full lesson: Java arraylist addall
The remove() method throws an IndexOutOfBoundsException if the index is out of range. Check the list size before you call remove().
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.remove(5); // throws IndexOutOfBoundsException
Full lesson: Java arraylist remove
A common mistake is to forget that indexOf() returns -1 when the character is not found. Always check for -1 before you use the result as an index.
String s = "hello";
int i = s.indexOf('z');
if (i != -1) {
System.out.println(s.charAt(i));
}
Full lesson: Java string indexof
A common mistake is to use a local variable before you assign a value to it. The compiler reports an error for an uninitialized local variable.
public void test() {
int x;
System.out.println(x); // compile error
}
Full lesson: Java variable types
A common mistake is to expect a useful string from the default toString() method. The default returns class name and hash code, so override toString() for readable output.
class Point {
int x = 1, y = 2;
public String toString() { return "(" + x + "," + y + ")"; }
}
Full lesson: Java object tostring
A common mistake is to call getClass() on a null reference. This throws a NullPointerException because there is no object.
Object obj = null;
System.out.println(obj.getClass()); // throws NullPointerException
Full lesson: Java object getclass
A common mistake is to store null keys or null values. Hashtable does not permit null keys or null values and throws a NullPointerException.
Hashtable<String, String> h = new Hashtable<>();
h.put(null, "value"); // throws NullPointerException
Full lesson: Java hashtable class