0% found this document useful (0 votes)
3 views

Java101

The document provides an overview of Java programming concepts, including variable declaration, object-oriented principles, method definition, and data structures like arrays and lists. It explains the use of generics for type safety and the importance of access modifiers in class design. Additionally, it introduces a practical exercise involving a remote-controlled car to apply the learned concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java101

The document provides an overview of Java programming concepts, including variable declaration, object-oriented principles, method definition, and data structures like arrays and lists. It explains the use of generics for type safety and the importance of access modifiers in class design. Additionally, it introduces a practical exercise involving a remote-controlled car to apply the learned concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Basics

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.

int explicitVar = 10;

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.

int count = 1; // Assign initial value

count = 2; // Update to new value

// Compiler error when assigning a different type

// 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 {

public int add(int x, int y) {

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

Scope in Java is defined between the { and } characters.


Java supports two types of comments. Single line comments are preceded by // and multiline comments
are inserted between /* and */.

Booleans

Booleans in Java are represented by the boolean type, which values can be either true or false.

Java supports three boolean operators:

 ! (NOT): negates the boolean

 && (AND): takes two booleans and results in true if they're both true

 || (OR): results in true if any of the two booleans is true

Examples

!true // => false

!false // => true

true && false // => false

true && true // => true

false || false // => false

false || true // => true

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.

Here is the standard syntax for initializing an array:

type[] variableName = new type[size];

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).

// Declare array with explicit size (size is 2)

int[] twoInts = new int[2];

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[] threeIntsV1 = new int[] { 4, 9, 7 };

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:

// Assign second element by index

twoInts[1] = 8;

// Retrieve the second element by index and assign to the int element

int secondElement = twoInts[1];

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:

int arrayLength = someArray.length;

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:

char[] vowels = { 'a', 'e', 'i', 'o', 'u' };

for(char vowel: vowels) {

// Output the vowel

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' };

for (int i = 0; i < 3; i++) {

// Output the vowel

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.

Consider this non-generic Container interface:

class Container {

private Object object;

public void set(Object object) { this.object = object; }

public Object get() { return object; }

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.

A generic class and generic interface have the following formats:

class ClassName<T1, T2, ..., Tn> { ... }

interface InterfaceName<T1, T2, ..., Tn> { ... }

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.

Here is the generic version of Container:


class Container<E> {

private E object;

public void set(E object) { this.object = object; }

public E get() { return object; }

When created, now we have to declare what type it holds and the compiler will enforce that constraint:

// empty <> can infer from context

Container<String> stringContainer = new Container<>();

// compiler knows this is a String, so it is allowed

stringContainer.set("Some string");

// no cast needed, compiler knows it is a String

String result = stringContainer.get();

// this causes a compiler error:

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:

List<String> emptyListOfStrings = List.of();

List<Integer> singleInteger = List.of(1);

List<Boolean> threeBooleans = List.of(true, false, true);

List<Object> listWithMultipleTypes = List.of("hello", 1, true);

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'));

int startingSize = vowels.size(); // 7

vowels.add('u'); // vowels is now ['a', 'e', 'i', 'o', 'i', 'e', 'a', 'u']

char a = vowels.get(0); // 'a'


boolean hadI = vowels.remove('i'); // true and vowels is now ['a', 'e', 'o', 'i', 'e', 'a', 'u']

boolean hasI = vowels.contains('i'); // true

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:

 public: the member can be accessed by any code (no restrictions).

 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 {

// Create two car instances

Car myCar = new Car();

Car yourCar = new 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

public int weight;

// Only accessible by code in this class

private String color;

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 {

// Will be set to specified value

public int weight = 2500;


// Will be set to default value (0)

public int year;

Car newCar = new Car();

newCar.weight; // => 2500

newCar.year; // => 0

// Update value of the field

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 {

private int carsImported;

public void importCars(int numberOfCars)

// Update private field from public method

carsImported = carsImported + numberOfCars;

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".

 The remaining battery charge, displayed as: "Battery at <PERCENTAGE>%".


If the battery is at 0%, you can't drive the car anymore and the battery display will show "Battery empty".

You have six tasks, each of which will work with remote controlled car instances.

Task 1

Buy a brand-new remote controlled car

Implement the (static) ElonsToyCar.buy() method to return a brand-new remote controlled car instance:

ElonsToyCar car = ElonsToyCar.buy();

You might also like