Java101
Java101
Java is a statically-typed language, which means that the type of a variable is known at compile-time.
Assigning a value to a name is referred to as defining a variable. A variable is defined by explicitly
specifying its type.
Updating a variable's value is done through the = operator. Here, = does not represent mathematical
equality. It simply assigns a value to a variable. Once defined, a variable's type can never change.
// count = false;
Java is an object-oriented language and requires all functions to be defined in a class. The class keyword
is used to define a class.
class Calculator {
// ...
A function within a class is referred to as a method. Each method can have zero or more parameters. All
parameters must be explicitly typed, there is no type inference for parameters. Similarly, the return type
must also be made explicit. Values are returned from methods using the return keyword. To allow a
method to be called by other classes, the public access modifier must be added.
class Calculator {
return x + y;
Invoking/calling a method is done by specifying its class and method name and passing arguments for
each of the method's parameters.
int sum = new Calculator().add(1, 2); // here the "add" method has been called to perform the task of
addition
Booleans
Booleans in Java are represented by the boolean type, which values can be either true or false.
&& (AND): takes two booleans and results in true if they're both true
Examples
Arrays
In Java, data structures that can hold zero or more elements are known as collections. An array is a
collection that has a fixed size and whose elements must all be of the same type. Elements can be
assigned to an array or retrieved from it using an index. Java arrays use zero-based indexing: the first
element's index is 0, the second element's index is 1, etc.
The type is the type of elements in the array which may be a primitive type (e.g. int) or a class
(e.g. String).
The size is the number of elements this array will hold (which cannot be changed later). After array
creation, the elements are initialized to their default values (typically 0, false or null).
Arrays can also be defined using a shortcut notation that allows you to both create the array and set its
value:
// Two equivalent ways to declare and initialize an array (size is 3)
int[] threeIntsV2 = { 4, 9, 7 };
As the compiler can now tell how many elements the array will have, the length can be omitted.
Array elements may be assigned and accessed using a bracketed index notation:
twoInts[1] = 8;
// Retrieve the second element by index and assign to the int element
Accessing an index that is outside of the valid indexes for the array results in
an IndexOutOfBoundsException.
Arrays can be manipulated by either calling an array instance's methods or properties, or by using the
static methods defined in the Arrays class (typically only used in generic code). The most commonly used
property for arrays is its length which can be accessed like this:
Java also provides a helpful utility class java.util.Arrays that has lots of useful array-related methods
(eg. Arrays.equals).
Java also supports multi-dimensional arrays like int[][] arr = new int[3][4]; which can be very useful.
The fact that an array is also a collection means that, besides accessing values by index, you can iterate
over all its values using a for-each loop:
System.out.print(vowel);
// => aeiou
If you want more control over which values to iterate over, a for loop can be used:
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
System.out.print(vowels[i]);
// => aei
Introduction
Generic Types
A generic type is a generic class or interface that is parameterized over types. This allows the compiler to
enforce type safety on the class or interface.
class Container {
Since it accepts and returns Object types, it works with any non-primitive type. However, this comes at a
cost because some code may call get expecting Integers while other code calls set adding Strings
resulting in a runtime exception.
The type parameter section, delimited by angle brackets (<>), following the class or interface name
specifies the type parameters (also called type variables) T1, T2, ..., and Tn. These can be used inside the
body of the class or interface to get generic type safety.
private E object;
When created, now we have to declare what type it holds and the compiler will enforce that constraint:
stringContainer.set("Some string");
stringContainer.set(42);
Lists
Lists are the ordered sequence collection in Java. Unlike arrays, a List can grow in size to accommodate
any number of items. One standard implementation is the ArrayList which is backed by a re-sizable array.
Another standard implementation is the LinkedList class which is backed by a doubly-linked list.
Lists may be empty or hold any number of items (including duplicates). Lists are a generic interface typed
to indicate which type of objects they can contain. For example:
Lists have various helpful methods to add, remove, get, and check for an element to be present:
List<Character> vowels = new ArrayList<>(List.of('a', 'e', 'i', 'o', 'i', 'e', 'a'));
vowels.add('u'); // vowels is now ['a', 'e', 'i', 'o', 'i', 'e', 'a', 'u']
The primary object-oriented construct in Java is the class, which is a combination of data (fields) and
behavior (methods). The fields and methods of a class are known as its members.
Access to members can be controlled through access modifiers, the two most common ones being:
private: the member can only be accessed by code in the same class.
You can think of a class as a template for creating instances of that class. To create an instance of a class
(also known as an object), the new keyword is used:
class Car {
Fields have a type and a name (defined in camelCase) and can be defined anywhere in a class (by
convention cased in PascalCase):
class Car {
// Accessible by anyone
One can optionally assign an initial value to a field. If a field does not specify an initial value, it will be set
to its type's default value. An instance's field values can be accessed and updated using dot notation.
class Car {
newCar.year; // => 0
newCar.year = 2018;
Private fields are usually updated as a side effect of calling a method. Such methods usually don't return
any value, in which case the return type should be void:
class CarImporter {
Instructions
In this exercise you'll be playing around with a remote controlled car, which you've finally saved enough
money for to buy.
Cars start with full (100%) batteries. Each time you drive the car using the remote control, it covers 20
meters and drains one percent of the battery.
The remote controlled car has a fancy LED display that shows two bits of information:
The total distance it has driven, displayed as: "Driven <METERS> meters".
You have six tasks, each of which will work with remote controlled car instances.
Task 1
Implement the (static) ElonsToyCar.buy() method to return a brand-new remote controlled car instance: