# Java Cheat Sheet
This my Java cheat sheet for the 1st semester course '[Introduction to Programming](https://www.lst.inf.ethz.ch/education/einfuehrung-in-die-programmierung-i--252-0027-.html)' at ETH. It's written as a mix of German and English because the primary purpose is to help me during the course.
# Eclipse Shortcuts
Source: https://javapapers.com/wp-content/uploads/2012/02/Eclipse-Shortcuts.pdf
| Shortcut | Action |
| -------- | -------- |
| `CMD-space` | **Code completion**|
| `CMD-1` | **Quick fix drop-down menu** |
| `CMD-.` | **Go to next error** |
| `CMD+N` | New Wizard |
| `CMD+D` | **Delete current line** |
| `CMD-Alt-Down` | **Duplicate current line** |
| `Alt-Down/Up` | Move current line up or down |
| `CMD+/` | Comment/Uncomment lines |
| `CMD+Shift+P` | Go to matching bracket |
| `CMD+Alt+N` | Context Menu to create class, package, interface |
| `CMD+T` | Show inheritance tree of current token |
| `CMD+O` | List all methods of the class, repeat for lists including inherited methods. |
| `CMD-Shift-U` | Find reference of highlighted in file |
| `CMD-F11` | Run last program |
| `F3` | Go to declaration of variable |
| Type| Template | Result |
| --- | -------- | -------- |
| `so` | `sysout` | `System.out.println();` |
| variable `=` | | autocomplete variable name |
# Programming basics
### Scope
Scope: Der Teil eines Programm in dem eine Variable sichtbar ist.
* Variable müssen deklariert sein bevor sie sichtbar sind
* Deklarationen müssen eindeutig sein
* Sichtbar von Deklaration bis zum Ende des Blocks für den die Variable deklariert ist
Block: durch `{` und `}` begrenzt
### Errors / Excemptions
``Errors`` happen during the compilation of the code. \
```Excemptions``` happen during the runtime of the program.
### If
![](https://i.imgur.com/vDzJywV.png)
### while
```java=
while (test) {
statement(s);
}
```
:::success
Bsp: EProg
```java=
int num = 1; // initialization
while (num*num <= 2000) { // test
System.out.print(num + " ");
num = num * 2; // update
}
//output: 1 2 4 8 1 6 3 2
```
:::
### do/while
Stellt sicher dass der Rumpf { ... } mindestens einmal ausgeführt wird.
Führt test am Ende des Schleifenrumpfes aus um zu entscheiden, ob ein weiterer Durchlauf nötig ist
```java=
do {
statement(s);
} while (test);
```
## Operators
### Boolean Operators
![](https://i.imgur.com/j4YiEQh.png)
## Kurzformen, Inkrement, Dekrement
`i++`
`i--`
![](https://i.imgur.com/nrU4dqs.png)
### Ternary Operator ```?```
Can be thought of as a simplified ```if-else``` statement.
[![](https://i.imgur.com/cpNtxYb.png)](https://www.educative.io/edpresso/what-is-a-ternary-operator-in-java)
**Syntax**
**Use case example**: Useful in converting a boolean array (with true and false) into an integer array (with 0s and 1s).
```java=
// Suppose this is a boolean array with n true and false 'cells'
boolean[] booleanArray = new boolean[n];
// New default int array with 0s everywhere
int[] array = new int[n]; // integer
// Loop that writes 0/1 when boolean array evaluates to false/true
for (int i = 0; i < n; i++) {
array[i] = road[i] ? 1 : 0;
}
```
# Classes
## Classes (Summary)
In large software system, a class can:
1. contain a ==program==
2. define a ==type== (object class)
3. define a ==module== (re-usable code)
**1. Contain a program**
* Has a `public static main` Method that can call up other `static` Methods if needed.
* Usually without a `static` variable (unless the variable is `final` e.g. `pi` in the `Maths` Class)
* The program usually implements a service for the user
**2. Define an object class (type)**
* the object class describes a new type for objects (Werte und Verhalten)
* Declares attributes, contructors, and methods
* (Might, but rarely, declares `static` variables and methods)
* Ist abgekapselt ('encapsulated') - alle Attribute und `static` Variablen sind `private`
* Examples of object classes: `Point`, `Person`, `File`, `Randon`
**3. Define a module (nur kurz angesprochen)**
* Wiederverwendbarer Code deer durch `static` Methoden implementiert ist
* Examples of modules: `Math`, `Arrays`
### `main(...)` Class
Klasse (“class”): Eine Programm Einheit mit der wir entweder:
1. Einen namenlosen Service implementieren können (via main(..))
2. Eine neue Art (neuen Typ) von Objekten beschreiben können.
Klasse ist die Vorlage (Mustervorlage, Schablone) die Objekte beschreibt
* Objekt wird gemäss Vorlage erschaffen
* Klasse beschreibt die Form/Funktionalität von Objekten
Objekt (“object”): Ein Gebilde das Zustand (“state”) und Verhalten (“behavior”) verbindet.
* Objekte sind Exemplare ("instances") einer Klasse
* Manche Autoren sprechen von Objektinstanzen (statt Objekt)
* Wenn ein Objekt erschaffen wird spricht man von der Instanziierung
* Die Menge aller Objekte einer Klasse bilden einen Typ
## `Point` Objekte
Point Objekte können von anderen Programmen
verwendet werden
* “Andere Programme”: beschrieben durch Klassen (siehe (1) und (2))
* “verwendet”: rufen Methoden auf, erstellen Point Objekte -- um ein Objekt zu verwenden müssen wir es erreichen können
Programme die Point Objekte verwenden heissen Klienten (“client programs”) der Point Klasse.
* Später werden wir sehen dass auch die Point Klasse Point Objekte verwenden kann (Point ist Klient von Point)
Klasse ist die Vorlage (Mustervorlage, Schablone) die Objekte beschreibt
* ==Objekt wird **gemäss Vorlage** erschaffen (**Klasse**)==
* ==Vorlage beschreibt **Verhalten**: Operationen (**Methoden**)==
* ==Vorlage beschreibt **Werte**: Zustand (**Attribute**)==
:::success
**`Point` Objekt erwünscht**
```java=
Point p1 = new Point(5, 2);
Point p2 = new Point(); // origin, (0, 0)
```
| Attribut Name | Beschreibung |
|---------------|----------------------------|
| `x` | x – Koordinate des Punktes |
| `y` | y – Koordinate des Punktes |
**Methoden für jedes `Point` Objekt:**
| Methoden Name | Bechreibung |
|---------------------|--------------------------------------------------------------|
| `setLocation(x, y)` | Setze die x und y Koordinaten dieses Punktes auf diese Werte |
| `translate(dx, dy)` | Verändere die x und y Koordinaten des Punktes um diese Werte |
| `distance(p)` | Wie weit ist der Punkt p von diesem Punkt entfernt |
| `draw(g)` | Zeichne den Punkt auf einer 2D Fläche g |
**`Point` Klasse als Vorlage (Cookie cutter)**
Point Class
```java=
// Zustand
int x, y
// Verhalten
setLocation(int x, int y)
translate(int dx, int dy)
distance(Point p)
draw(Graphics g)
```
Point object #1
```java=
// Zustand
x = 5
y = -2
// Verhalten
setLocation(int x, int y)
translate(int dx, int dy)
distance(Point p)
draw(Graphics g)
```
Point object #2
```java=
// Zustand
x = -245
y = 1897
// Verhalten
setLocation(int x, int y)
translate(int dx, int dy)
distance(Point p)
draw(Graphics g)
```
:::
# Attributes
:::info
Attribute: Zustand eines Objekts.
:::
Attribute (“field”): Eine Variable innerhalb eines Objektes die Teil des Objekt Zustandes ist. (Manchmal auch Objektattribut
genannt.)
* Jedes Objekt hat seine eigene Kopie jedes Attributes.
==**Deklaration**==
Syntax für Deklaration wie für Variable in Methoden.
```java=
type name;
```
:::success
Attribute:
* name (String)
* notenDS (double)
```java=
public class Student {
String name;
double notenDS;
}
```
:::
==**Zugriff**==
Andere Klassen können auf die Attribute eines Objektes mittels Referenzvariable zugreifen (lesen oder verändern).
Wir sagen "die (Referenz)Variable wird dereferenziert" (um auf ein Attribut zuzugreifen bzw eine Methode aufzurufen)
Zugriff (**lesen**):
```java=
variable.attribute
```
Verändern (**schreiben**):
```java=
variable.attribute = value;
```
:::success
```java=
Point p1 = new Point();
Point p2 = new Point();
System.out.println("the x-coord is " + p1.x); // Zugriff (lesen)
p2.y = 1290130; // Verändern (schreiben)
```
:::
## Mit Objekten arbeiten (Zusammenfassung)
`new` liefert ==Verweis== ("Reference") auf Exemplar
* Kann in einer Variable gespeichert werden
```java=
Point p = new Point();
```
* Wir sagen dass `p` eine Referenzvariable ("reference variable") ist.
* Besser: `p` ist eine Variable eines Referenztyps
* Im Gegensatz zu Variablen eines Basistypes (eingebauten Typs)
==Zugriff== auf Objektattribute via Referenzvariable (dereferenzieren)
* "Dot Notation”
* Dereferenzieren ("dereference"): Zugriff auf Attribute oder Methoden eines Objektes in Dot Notation, z.B. `.length()`.
```java=
int z = p.x; // p refers to a Point, see above
```
`null` ist ein ==Wert== (den eine Referenzvariable haben kann).
```java=
Point p2;
p2 = null; // forget whatever p2 referred to! int[] a = new int[10];
a = null; // forget this array!
String s = "Hello";
s = null; // forget this string
```
Wenn der Wert zu `null` gesetzt wird, wird das Objekt vergessen und falls nicht anderswo dereferenciert vom Java garbaga collector aufgesammelt.
Hat eine Variable den Wert null so sprechen wir manchmal von einer "null reference".
`null` ist der Wert einer Referenzvariable die auf kein Objekt verweist.
Daher werden Array Elemente, die auf Objekte verweisen können, mit `null` initialisiert.
:::danger
Es ist nicht erlaubt, null zu dereferenzieren (Laufzeitfehler, hat eine Exception zur Folge):
`java.lang.NullPointerException`:
```java=
Point p1 = new Point();
p1.x = 3; p1.y = 2;
Pointp2=p1; //p2.x==3,p2.y==2
p2 = null;
System.out.println(“p2.x :” + p2.x); // <-- Exception Error!!!
```
Output
```java=+
// Exception in thread "main" java.lang.NullPointerException
```
:::
==Arrays und Referenzvariablen==
:::success
```java=
Point[]
```
Deklariert eine neue Referenzvariable (places) die sich auf
einen Array beziehen kann:
```java=+
places = new Point[10];
places[0] = new Point(1,1);
```
Element mit Index 0 verweist jetzt auf Punkt (1,1).
`places[0]` ist eine Variable die eine Referenz (auf ein `Point` Exemplar/Objekt) enthält.
:::
## Attribute (Zusammenfassung)
:::info
==Attribute== eines Objekts können einen beliebigen Typ haben und legen den ==Zustand== (legale ==Werte==) fest
* Basistypen
* Strings
* Arrays
* ...
Das ==Verhalten== (Menge der ==Operationen==) wird durch ==Methoden== bestimmt
:::
# Contructors
:::info
Ein Konstruktor ist keine Methode.
:::
Konstruktoren sind optional:
* Wenn eine Klassendefinition keinen Konstruktor enthält, dann stellt Java einen (voreingestellten) default Konstruktor (“default constructor”) zur Verfügung
* Der default Konstruktor hat keine Parameter und setzt alle Felder auf Null (entweder `0`, `0.0`, `false` oder `null`)
:::success
**Example constructor**
```java=
public class Person { String name;
int id;
double hourlyRate;
double[] hours;
double[] overtime;
// Constructs a Person with given name and Id
public Person(String firstName, int uniqueId) {
name = firstName;
id = uniqueId;
}
// Methods
...
}
```
:::
:::success
**Example constructor**
```java=
public class Point {
int x;
int y;
// Constructs a Point at the given x/y location.
public Point(int initialX, int initialY) {
x = initialX;
y = initialY;
}
// Methods
...
}
```
:::
# `Static`
## `Static` Methods
:::info
Sind nicht problematisch weil Methoden keinen Zustand speicher.
:::
* Gemeinsam für alle Exemplare, nicht für jedes Exemplar kopiert.
* Es gibt keinen *impliziten Parameter* `this.` weil kein Objektexemplar mit der static Methode verbunden ist.
* Daher kann eine solche Methode nicht auf den Zustand eines Objekts
zugreifen, d.h. (Objekt)Attribute können nicht gelesen oder geschrieben
werden.
Questions to ask yourself when creating a Method:
1. Sichtbarkeit (Wer kann Methode aufrufen?): `public` oder `static`
2. Return value: `int`, `boolean` etc
3. Parameter (Was braucht Methode um Job zu erledigen?)
4. Lebensdauer (So lange wie ein Exemplar, so lange wie die Klasse `static`)
## `Static` Variables :warning:
:::danger
Static Variable speichern Zustand über mehrere Aufrufe für verschiedene Exemplare.
:::
Gemeinsame ("shared") Variable für alle Exemplare.
Alle Objektexemplare können auf diese Variable zugreigen.
:::success
Example of use case: **Unique ID generation**
```java=
public class Person {
private static int uniqueId = 0; // <-- Unique ID
String name;
int id;
double hourlyRate;
double[] hours;
double[] overtime;
// Constructs a Person with given name and assigns ID
public Person(String firstname) {
name = firstname;
id = uniqueId++; // <-- Unique ID
}
// Methods
...
}
```
Versus (code where ID might not be unique):
```java=
public class Person {
String name;
int id;
double hourlyRate;
double[] hours;
double[] overtime;
// Constructs a Person with given name and ID
public Person(String firstname) {
name = firstname;
id = uniqueId; // <-- Unique ID
}
// Methods
...
}
```
:::
## Intro to Objects
:::info
A `class` is the set of **instructions** used to create/instantiate an `object`. It describes the **characteristics** and '**abilities**' of every object that is created.
:::
* A ==class== describes a ==type== (Class is a cookie cutter, i.e. cutting *device*)
* A ==type== describes characteristics of data (types are the various cookie types, i.e. *shapes*).
* An ==object== is a representations of a ==type== during the runtime of the program (objects are the resulting *cookie*).
:::info
==Objects== can be used by other classes (==client== programs).
:::
To work with an ==object==, it has to be created/instantiated first:
* with the `new` keyword
```java=
Random rand;
rand = new Random(); // Erschaffung mit new Keyword
// kann auch auf der gleichen Linie erledigt werden
Scanner console = new Scanner(System.in);
```
* or through initialization
```java=
String s ;
s = "Hello␣" + "World!";
// Erschaffung durch Initialisierung String s2 = "Hello" + "␣World␣kompakt";
```
### Objects as Parameters in a Methods
* `Scanner` as Parameter
* `Filter` Method that takes array (object) and set to `0` any element that is `<0`.
Objekte können an eine Methode als Parameter übergeben werden.
Die üblichen Regeln gelten (Parameter muss deklariert werden, wenn ein Parameter deklariert ist dann muss er übergeben werden).
:::success
**`Scanner` als Parameter:**
Wenn mehrere Methoden Input lesen wollen, deklarieren Sie einen `Scanner` in `main` und übergeben ihn an andere Methoden als Parameter.
```java=
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int sum = readSum3(console);
System.out.println("The sum is " + sum);
}
// Prompts for 3 numbers and returns their sum.
public static int readSum3(Scanner console) {
System.out.print("Type 3 numbers: ");
int num1 = console.nextInt();
int num2 = console.nextInt();
int num3 = console.nextInt();
return num1 + num2 + num3; }
```
:::
:::success
**`Filter` (Method)**
That takes an `array` (objects) and set to `0` any element that is `<0`.
```java=
```
:::
## Reference Semantics and Value Semantics
:::info
Primitive variables store the actual values.
:::
* **Value semantics** for ==primitive variables== (8 primitive types / variables defined by Java):
* `int`
* `boolean`
* `double`
* `char`
* (`short`, `long`, `float`, `byte`)
:::info
Reference variables store the addresses of the objects they refer to.
:::
* **Reference semantics** for ==reference variables== (for ==objects== / any instantiable class, i.e. everything else):
* `int[]` (arrays are objects!)
* `String[]` (arrays are objects!)
* `Scanner`
* `Random`
* `Die`
* all other `instantiable classes`
:::success
Bsp: (Source PVW EProg)
All arrays are objects created by the `Arrays` class. If you change something in an array, the changes will be visible in all variables that refer to that array (object).
```java=
public class Main {
public static void main(String [] args) {
int[] a1 = { 1, 2 };
int[] a2 = a1;
swapFirst2(a1) ;
for (int i = 0; i < a1.length; i++) {
System.out.print(a1[i] + "␣");
}
System . out . p r i n t l n ( ) ;
for (int i = 0; i < a2.length; i++) {
System.out.print(a2[i] + "␣");
}
}
public static void swapFirst2(int [] arr) {
if (arr.length < 2) { // Nothing to swap
return ;
}
else {
int temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
}
}
}
// Output:
// 2 1
// 2 1
```
:::
# Data structures
# Arrays
Ein Array erlaubt uns, mehrere Werte des selben **Typs** zu speichern.
```java=
type[] name = new type[length];
```
:::success
```java=
Bsp:
int[] numbers = new int[10];
```
:::
| Type | Default Wert |
|-----------|--------------|
| `int` | `0` |
| `double` | `0` |
| `boolean` | `FALSE` |
| `String` | `null` |
### `length` **Attribute**
Das length Attribut eines Arrays name liefert die Anzahl der Elemente.
```java=
name.length
```
:::success
```java=
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
// output: 0 2 4 6 8 10 12 14
```
:::
### Array Parameter (in a Method)
==**Deklaration**==
```java=
public static type methodName(type[] name) {
```
In der Deklaration steht dass ein Array Parameter gebraucht wird.
* Keine Angabe der Grösse
* Angabe des Typs der Elemente
* Obwohl die Länge des Arrays nicht in der Parameterliste erscheint so kann die Methode die Länge jedoch herausfinden
:::success
Bsp:
```java=
// Returns the average of the given array of numbers.
public static double average(int[] numbers) { // <-- This is a method
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return (double) sum / numbers.length;
}
```
:::
==**Aufruf**==
```java=
methodName(arrayName);
```
:::warning
No "[]" wenn der Array aufgerufen wird!
```java=
double avg = average(iq); <-- array as parameter but no "[]"
```
:::
:::success
```java=
public class MyProgram {
public static void main(String[] args) {
// figure out the average TA IQ
int[] iq = {126, 84, 149, 167, 95};
double avg = average(iq); // <-- Methoden Aufruf
// No "[]" wenn der Array aufgerufen wird!
System.out.println("Average IQ = " + avg);
}
...
```
:::
==**`main(String[] args)`**== (Bsp)
`main` erwartet als Parameter einen Array; die Element des Arrays sind vom Typ `String`.
`args[i]` erlaubt Zugriff auf Element `i` (`0 ≤ i < args.length`) wenn es dieses Element gibt.
### Array Rückgabe (in a Method)
==**Deklaration**==
Wieder verwenden wir ein `return` Statement um anzugeben, was als Ergebnis einer Methode zurückgegeben wird.
```java=
public static type[] methodName(parameters) {
```
:::success
This is a method `duplicateElements()` taking an integer array `int[] numbers` as a parameter ("input") and returning an integer array `int[] result` as "output".
```java=
// Returns a new array with two copies of each value.
// Example: [1, 4, 0, 7] -> [1, 1, 4, 4, 0, 0, 7, 7]
// Note the return type is an integer array "int[]"
public static int[] duplicateElements(int[] numbers) {
int[] result = new int[2 * numbers.length];
// ^ this is the return value
for (int i = 0; i < numbers.length; i++) {
result[2 * i] = numbers[i];
result[2 * i + 1] = numbers[i];
}
return result;
}
```
:::
==**Aufruf**==
:::warning
Die aufrufende Methode muss den Rückgabewert entgegen nehmen.
:::
```java=
type[] name = methodName(parameters);
```
:e-mail:
:::success
```java=
public class MyProgram {
public static void main(String[] args) {
int[] iq = {126, 84, 149, 167, 95};
int[] iqd = duplicateElements(iq);
...
```
:::
Together it would look something like this:
:::success
```java=
public class MyProgram {
public static void main(String[] args) {
int[] iq = {126, 84, 149, 167, 95};
int[] iqd = duplicateElements(iq);
}
public static int[] duplicateElements(int[] numbers) {
int[] result = new int[2 * numbers.length];
for (int i = 0; i < numbers.length; i++) {
result[2 * i] = numbers[i];
result[2 * i + 1] = numbers[i];
}
return result;
}
}
```
:::
# Linked Lists
# Specific classes in review (below)
# `Objects` (Class)
# `String` (Class)
\+ erzwingt Konversion von anderen Typen (zu String)
```java=
int x = 3;
String point = "(" + x + ", " + 5 + ")";
```
![](https://i.imgur.com/mW6v6Ng.png)
## `String` (Methods)
| Method name | Description |
|------------------------------|----------------------------------------------------------------------------------------------------|
| `indexOf(str)` | index where the start of the given string appears in this string (-1 if not found) |
| `length()` | number of characters in this string |
| `substring(index1, index2)` | the characters in this string from index1 (inclusive) to index2 (exclusive); |
| `substring(index1)` | if index2 is omitted, grabs till end of string |
| `toLowerCase()` | a new string with all lowercase letters |
| `toUpperCase()` | a new string with all uppercase letters |
| `equals(str)` | ob 2 Strings die selben Buchstaben enthalten |
| `equalsIgnoreCase(str)` | ob 2 Strings die selben Buchstaben enthalten, ohne Berücksichtigung von Gross- und Kleinschreibung |
| `startsWith(str)` | ob der String mit den Buchstaben des anderen (str) anfängt |
| `endsWith(str)` | ob ... endet |
| `contains(str)` | ob der String str (irgendwo) auftritt |
`==` vergleicht Objektverweise (“references”) und liefert daher evtl. `false` selbst wenn zwei Strings die gleichen Buchstaben haben. Die Methode `equals` liefert einen booleschen Wert.
### `.equals` (Method)
# `Arrays` (Class)
**Syntax**
```java=
// Declaring the array
type[] name;
// Instantiating the array
name = new type[length];
// Or both in 1 step
type[] name = new type[length];
```
**Example**
```java=
int[] array = new int[10]; // array of length 10
```
:::info
All arrays are initialised in with their default ```null``` values in every cell (e.g. `0`, `false`, `null` etc).
:::
| Type | Default Value |
|---------|---------------|
| **`int`** | **`0`** |
| **`double`** | **`0.0`** |
| `boolean` | `false` |
| **`objects`** (e.g. `String`) | **`null`** |
## `Arrays` (Methods)
Die Klasse `Arrays` in der Bibliothek `java.util` enthält einige Methoden, die wir in einer static Methode aufrufen können.
| Method name | Description |
|------------------------------|------------------------------------------------------------------------------|
| `binarySearch(array, value)` | returns the index of the given value in a sorted array (or < 0 if not found) |
| `copyOf(array, length)` | returns a new copy of an array |
| `equals(array1, array2)` | returns true if the two arrays contain same elements in the same order |
| `fill(array, value)` | sets every element to the given value |
| `sort(array)` | arranges the elements into sorted order |
| `toString(array)` | returns a string representing the array, such as "`[10, 30, - 25, 17]`" |
```java=
import java.util.*;
Arrays.methodName(parameters)
```
:::success
```java=
int[] a1 = {42, -7, 1, 15};
int[] a2 = {42, -7, 1, 15};
if (Arrays.equals(a1, a2)) {
...
}
```
:::
### `Arrays.toString` (Method)
`Arrays.toString` nimmt einen Array als Parameter und liefert einen `String` mit den Array Elementen
:::info
Praktisch wenn ein Array ausgegeben werden soll!
:::
:::success
```java=
int[] e = {0, 2, 4, 6, 8};
e[1] = e[3] + e[4];
System.out.println("e is " + Arrays.toString(e));
```
Output
```java=+
e is [0, 14, 4, 6, 8]
```
:::
Note you cannot use `System.out.println(array)` it will show you some weird memory location.
:::danger
```java=
int[] a1 = {42, -7, 1, 15};
System.out.println(a1);
```
Output
```java=+
[I@98f8c4]
```
:::
# `LinkedList` (Class)
# `Files` (Class)
Source: https://www.w3schools.com/java/java_files_read.asp
To use the File class, create an object of the class, and specify the filename or directory name:
```java=
import java.io.File; // Import the File class
File myObj = new File("src/tripData.txt");
```
Make sure the file is created in in the java project not the src folder (if it's in the src folder include `src/file.txt`.
| Method | Type | Description |
|-------------------|----------|------------------------------------------------|
| `canRead()` | Boolean | Tests whether the file is readable or not |
| `canWrite()` | Boolean | Tests whether the file is writable or not |
| `createNewFile()` | Boolean | Creates an empty file |
| `delete()` | Boolean | Deletes a file |
| `exists()` | Boolean | Tests whether the file exists |
| `getName()` | String | Returns the name of the file |
| `getAbsolutePath()` | String | Returns the absolute pathname of the file |
| `length()` | Long | Returns the size of the file in bytes |
| `list()` | String[] | Returns an array of the files in the directory |
| `mkdir()` | Boolean | Creates a directory |
# `Scanner` (Class)
**Read from file:**
Source: https://www.w3schools.com/java/java_files_read.asp
```java=
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
```
**Read user input from console**
:warning: `.nextline()` will consume "\n" if it is put straight after `.nextInt()`. You may have to include it twice.
Source:
https://www.w3schools.com/java/java_user_input.asp
```java=
import java.util.Scanner; // Import the Scanner class
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
```
## `Scanner` Methods
| Method | Description |
|----------------|-------------------------------------------|
| `nextInt()` | reads an int from the user and returns it |
| `nextDouble()` | reads a double from the user |
| `next()` | reads a one-word String from the user |
| `nextLine()` | reads a one-line String from the user |
# `Math` (Class)
Bemerkung: Nicht alle Math Methoden lieferen einen `int` Wert den wir erwarten (könnten), manche z.B. liefern einen `double` Wert.
```java=
Math.methodName(parameters)
```
:::success
```java=
double squareRoot = Math.sqrt(121.0); // 11.0
System.out.println(squareRoot);
int absoluteValue = Math.abs(-50);
System.out.println(absoluteValue); // 50
System.out.println(Math.min(3, 7) + 2); // 5
```
:::
# `Random` (Class)
Die Random Klasse liefert uns einen Zufallszahlengenerator (pseudo random).
Die Klasse ist auch in `java.util.`
```java=
import java.util.*;
```
| Method name | Description |
|----------------|---------------------------------------------------------------------------------------|
| `nextInt()` | returns a random integer |
| `nextInt(max)` | returns a random integer in the range [0, max) in other words, 0 to max - 1 inclusive |
| `nextDouble()` | returns a random real number in the range [0.0, 1.0) |
| `nextLine()` | reads a one-line String from the user |
:::success
Häufig brauchen wir (ganze) Zufallszahlen zwischen 1 und N
```java=
int n = rand.nextInt(20) + 1; // 1-20 inclusive
```
Um eine ganze Zahl in irgendeinem Interval [min, max] zu
bekommen (inklusive Grenzen):
```java=+
name.nextInt(size of range) + min; // name RandomNbGenerator
mit (size of range) == (max - min + 1)
```
Beispiel: Eine zufällige ganze Zahl zwischen 4 und 10 einschliesslich:
```java=+
int n = rand.nextInt(7) + 4;
```
:::