diff --git a/01-setup/01-setup-de.md b/01-setup/01-setup-de.md new file mode 100644 index 0000000..9f4760d --- /dev/null +++ b/01-setup/01-setup-de.md @@ -0,0 +1,338 @@ +--- +marp: true +paginate: true +theme: default +header: ![h:80](../imgs/cegos-integrata.png) +footer: 'Cegos Integrata | Java Basics | 1. Tools, Setup' +--- + + + + +# Java Basics + +![width:400px](../imgs/java.jpg) + +### 1. Einführung + +--- + +# 1. Setup & Werkzeuge +## Agenda + +* Motivation +* Java-Anwendungen +* Java-Geschichte +* Prinzipien +* Java-Plattform (JDK, JRE, JVM) +* Git +* IDEs & Links +* Quiz + +## Aufgabe + +Erstes Programm ausführen: Hallo Welt! + +--- + +# 1. Setup & Werkzeuge + +## Motivation + +* Nenne Unterschiede zwischen einem Programm und einem Betriebssystem. +* Für welche Anwendungsfälle würdet ihr Java nutzen? +* Welche Programmiersprachen kennt ihr? + +--- + +# 1. Setup & Werkzeuge + +## Java-Anwendungen + +Ursprünglich als Sprache für das World Wide Web entwickelt, wird Java aufgrund seiner Plattformunabhängigkeit, Sicherheit und Robustheit in vielen Branchen eingesetzt. + +## Anwendungen, die Java nutzen: + +* **Webanwendungen** – z. B. Twitter, LinkedIn, Netflix +* **Mobile Apps** – Android-Apps (Java ist eine primäre Sprache für die Android-Entwicklung) +* **Unternehmenssoftware** – z. B. ERP-Systeme, Bankensoftware +* **Spiele** – z. B. Minecraft +* **Big Data & Cloud Computing** – Hadoop, Apache Spark +* **KI & Maschinelles Lernen** – TensorFlow, Deeplearning4j +* Java wird oft als Backend verwendet, während das Frontend auf JavaScript basiert. + +--- + +# 1. Setup & Werkzeuge + +## Java-Geschichte + +* Entwickelt von James Gosling bei Sun Microsystems, veröffentlicht im Mai 1995. +* 1998 Einführung des Java Community Process: + * Mitglieder heute: Alibaba, Amazon, ARM, Azul Systems, IBM, Intel, JetBrains, Microsoft, Oracle, SAP, u. v. m. +* 2006/2007 Java Virtual Machine (JVM) wird als Open-Source-Software unter GPL-2.0-only lizenziert. +* 2010 Übernahme von Sun Microsystems durch Oracle. +* 2017 Jakarta EE wechselt zur Eclipse Foundation. + +--- + +# 1. Setup & Werkzeuge + +## Prinzipien + +* Einfach, **objektorientiert** und vertraut (inspiriert von C++, Smalltalk, Eiffel, Objective-C). +* Robust und sicher (**automatische Speicherverwaltung**, keine Pointer-Arithmetik nötig). +* Architekturneutral und portabel (**plattformunabhängig**). +* Hohe Leistung. +* **Interpretiert**, threaded und dynamisch: + * Java-Interpreter führt Java-Bytecode direkt aus, Klassen werden bei Bedarf verlinkt. + * **Multithreading und Thread-safe**. +* **Typsicherheit**. + +Quelle: [Oracle Java Einführung](https://www.oracle.com/java/technologies/introduction-to-java.html) + +--- + +# 1. Setup & Werkzeuge + +## Java-Plattform + +Verschiedene Plattformen für unterschiedliche Gerätetypen und Anwendungsbereiche: + +* **Java Card:** Sicheres Ausführen von kleinen Java-Applets auf Smartcards. +* **Java ME (Micro Edition):** Für Geräte mit begrenzten Ressourcen (z. B. Handys, Set-Top-Boxen). +* **Java SE (Standard Edition):** Allgemeine Nutzung auf PCs und Servern. +* **Jakarta EE (Enterprise Edition):** Erweiterung von Java SE für Unternehmensanwendungen. + +--- + +# 1. Setup & Werkzeuge + +## JVM, JRE, JDK + +* **JVM (Java Virtual Machine):** Kernstück der Java-Technologie, führt Bytecode aus. +* **JRE (Java Runtime Environment):** Umgebung für die Ausführung von Java-Anwendungen. +* **JDK (Java Development Kit):** Entwicklungswerkzeuge zum Kompilieren, Debuggen und Ausführen. + +Quelle: [IBM JVM vs. JRE vs. JDK](https://www.ibm.com/think/topics/jvm-vs-jre-vs-jdk) + +--- + +# 1. Introduction to Java + +## Java virtual machine - run everywhere + +![width:800px](../imgs/JvmSpec7.png) + +By Michelle Ridomi - Own work, CC BY-SA 4.0, https://commons.wikimedia.org/w/index.php?curid=35963523 + +--- +# 1. Setup & Werkzeuge + +## Java Development Kit + +- **javac** – Liest Java-Klassen- und Schnittstellendefinitionen und kompiliert sie in Bytecode und Klassendateien. +- **java** – Startet eine Java-Anwendung. +- **jar** – Erstellt ein Archiv für Klassen und Ressourcen und kann einzelne Klassen oder Ressourcen aus einem Archiv manipulieren oder wiederherstellen. + Der `jar`-Befehl ist ein universelles Archivierungs- und Komprimierungswerkzeug, das auf den ZIP- und ZLIB-Komprimierungsformaten basiert. + +--- + +## Beispiel für das Java Development Kit + +Verzeichnis: `quiz` + +Java-Code in Bytecode kompilieren: + +```bash +mkdir classes +javac src/main/java/de/starwit/Quiz.java -d classes +``` + +Java-Programm ausführen: + +```bash +java src/main/java/de/starwit/Quiz.java +cd classes +java de.starwit.Quiz +``` + +JAR-Archiv erstellen und ausführen: + +```bash +jar --create --file foo.jar --main-class de.starwit.Quiz -C classes . +java -jar foo.jar +``` + +--- + +# 1. Setup & Werkzeuge + +## Programmiersprachen auf der JVM + +Neben Java laufen viele weitere Sprachen auf der JVM: + +* **Java** – statisch typisierte, objektorientierte Sprache. +* **Kotlin** – von JetBrains entwickelt, bevorzugte Sprache für Android. +* **Scala** – objektorientiert und funktional. +* **Groovy** – dynamische Programmiersprache. +* **Clojure** – funktionale Lisp-Variante für die JVM. + +Quelle: [Liste der JVM-Sprachen](https://en.wikipedia.org/wiki/List_of_JVM_languages) + +--- + +# 1. Setup & Werkzeuge + +## Git Überblick + +* Ermöglicht parallele Zusammenarbeit durch Versionskontrolle. +* Branches helfen, verschiedene Features separat zu entwickeln. +* Wichtige Befehle: + * `git clone https://...` – Repository klonen. + * `git add .` – Änderungen zur Staging-Area hinzufügen. + * `git commit -m "Message"` – Änderungen lokal speichern. + * `git push` – Änderungen ins Remote-Repository hochladen. + * `git pull` – Neueste Änderungen abrufen. + +--- + + +# 1. Setup & Werkzeuge + +## Git Branches und Workflow + +![h:500](../imgs/git-branches.png) + +--- + +# 1. Setup & Werkzeuge + +## Git Pull Requests / Merge Requests + +* Feature-Branches werden über Pull Requests zusammengeführt. +* Code kann vor dem Merge überprüft und freigegeben werden. + +## Vorteile von Git + +* Getrennte Entwicklung in eigenen Branches ohne Konflikte. +* Kontrollierte Code-Reviews vor dem Deployment. +* Versionierung von Code-Historien und parallele Releases. + +--- + +# 1. Setup & Werkzeuge + +## IDEs (Integrierte Entwicklungsumgebungen) + +* Visual Studio Code +* IntelliJ IDEA +* Eclipse +* NetBeans + +## Nützliche Links + +* [Java Wikipedia](https://de.wikipedia.org/wiki/Java_(Programmiersprache)) +* [Offizielles Java-Tutorial](https://docs.oracle.com/javase/tutorial/) +* [Liste der JVM-Sprachen](https://en.wikipedia.org/wiki/List_of_JVM_languages) +* [JVM, JRE, JDK](https://www.ibm.com/think/topics/jvm-vs-jre-vs-jdk) + +--- + +# 1. Setup & Werkzeuge + +## Quiz + +* Aus welchen Teilen besteht die Java-Plattform? +* Was ist der Unterschied zwischen einem Interpreter und Compiler? Wo wird in Java was genutzt? +* Aus welchen Dateien besteht ein Java-Projekt? +* Auf welchen Prinzipien basiert Java? +* Warum lässt sich mit Java geschriebener Code einfacher auf andere Systeme (Mikroprozessoren/Betriebssysteme) übertragen? +* Wann und warum sollte man Git benutzen? +* Was ist der Unterschied zwischen Debuggen und Ausführen? + +--- + + +# 1. Setup & Werkzeuge + +## weitere Aufgaben befinden sich in der [readme](Readme.md) + +![width:300px](../imgs/duke.png) diff --git a/01-setup/01-setup.md b/01-setup/01-setup.md new file mode 100644 index 0000000..cd93f4a --- /dev/null +++ b/01-setup/01-setup.md @@ -0,0 +1,344 @@ +--- +marp: true +paginate: true +theme: default +header: ![h:80](../imgs/cegos-integrata.png) +footer: 'Cegos Integrata | Java Basics | 1. Tools, Setup' +--- + + + + +# Java Basics + +![width:400px](../imgs/java.jpg) + +### 1. Setup & Tools + +--- + +# 1. Setup & Tool + +## Agenda + +* Motivation +* Java-Powered Applications +* Java History +* Principles +* Java Platform (JDK, JRE, JVM) +* Git +* IDE & Links +* Quiz + +## Task + +Run first Programm: Hello World! + +--- + +# 1. Setup & Tool + +## Motivation + +* describe differences between a program and an operating system. +* For which use cases would you use Java? +* Which programming languages do you know? + +--- + +# 1. Setup & Tool + +## Java-Powered Applications + +Originally developed as language for the world wide web, Java is widely used across various industries due to its platform independence, security, and robustness. + +## Applications Running Java + +* **Web Applications** – e.g., Twitter, LinkedIn, Netflix +* **Mobile Apps** – Android apps (Java is a primary language for Android development) +* **Enterprise Software** – e.g., ERP systems, banking software +* **Games** – e.g., Minecraft +* **Big Data & Cloud Computing** – Hadoop, Apache Spark +* **AI & Machine Learning** – TensorFlow, Deeplearning4j +* it is common to use Java as backend while using a Javascript-based frontend + +--- + +# 1. Setup & Tool + +## Java History + +* designed by James Gosling at Sun Microsystems, release in May 1995 +* 1998 Java Community Process + * members today: Alibaba, Amazon.com, Services, Inc., Arm Ltd, Azul Systems, Bellsoft , BNY Mellon, Eclipse, Ken Foge, Fujitsu, IBM , Intel, Japan JUG, JetBrains, MicroDoc, Microsoft, Oracle, SAP, SouJava +* 2006, 2007 Java virtual machine (JVM) as free and open-source software (FOSS), under the terms of the GPL-2.0-only license +* 2010 Oracle aquired SUN and Java +* 2017 Jakarta EE goes to Eclipse Foundation + +--- + +# 1. Setup & Tool + +## Principles + +* It must be simple, **object-oriented**, and familiar. + * inpired by C++, Smalltalk, Eiffel, ObjectiveC +* It must be robust and secure. + * **automatic garbadge collection**, no pointer arithmetic needed +* It must be architecture-neutral and portable. + * **platform-independent** +* It must execute with high performance. +* It must be **interpreted**, threaded, and dynamic. + * Java interpretor runs Java bytecode directly,classes are linked as needed + * **multiy-threaded and thread-safe** +* **type-save** + +Source: https://www.oracle.com/java/technologies/introduction-to-java.html + +--- + +# 1. Setup & Tool + +## Java Platform + +Different platforms target different classes of device and application domains: + +* **Java Card:** A technology that allows small Java-based applications (applets) to be run securely on smart cards and similar small-memory devices. +* **Java ME (Micro Edition):** Specifies several different sets of libraries (known as profiles) for devices with limited storage, display, and power capacities. It is often used to develop applications for mobile devices, PDAs, TV set-top boxes, and printers. +* **Java SE (Standard Edition):** For general-purpose use on desktop PCs, servers and similar devices. +* **Jakarta EE (Enterprise Edition):** Java SE plus various APIs which are useful for multi-tier client–server enterprise applications. + +--- + +# 1. Setup & Tool + +## JVM, JRE, JDK + +* **JVM (Java Virtual Runtime)**: Included in both, JRE and JDK. Loads, verifies, and runs Java bytecode. It is known as the interpreter or the core of the Java programming language because it runs Java programming. +* **Java Runtime Environment, or JRE**, is a set of software tools responsible for execution of the Java program or application on your system. +* **Java Development Kit, or JDK**, is a software development kit that is a superset of JRE. JDK contains all the tools that are required to compile, debug, and run a program developed using the Java platform. + +Source: https://www.ibm.com/think/topics/jvm-vs-jre-vs-jdk + +--- + +# 1. Setup & Tool + +## The Java virtual machine - run everywhere + +![width:800px](../imgs/JvmSpec7.png) + +By Michelle Ridomi - Own work, CC BY-SA 4.0, https://commons.wikimedia.org/w/index.php?curid=35963523 + +--- + +# 1. Setup & Tool + +## Java Development Kit + +**javac** - read Java class and interface definitions and compile them into bytecode and class files + +**java** - launch a Java application + +**jar** - creates an archive for classes and resources, and can manipulate or restore individual classes or resources from an archive. The jar command is a general-purpose archiving and compression tool, based on the ZIP and ZLIB compression formats. + +--- + +# 1. Setup & Tool + +## Java Development Kit Example + +Root folder: ```quiz``` +Compile in bytecode: + +```bash +mkdir classes +javac src/main/java/de/starwit/Quiz.java -d classes +``` + +Execute Java program: + +```bash +java src/main/java/de/starwit/Quiz.java +cd classes +java de.starwit.Quiz +``` + +Create and execute archive: + +```bash +jar --create --file foo.jar --main-class de.starwit.Quiz -C classes . +java -jar foo.jar +``` + +--- + +# 1. Setup & Tool + +## Programming Languages running on JVM + +The JVM was initially designed to support only the language Java. However, over time, ever more languages were adapted or designed to run on the Java platform. + +* **Java** a statically-typed object-oriented language +* **Kotlin** a statically-typed language from JetBrains, the developers of IntelliJ IDEA[3] and Google's preferred language for Android +* **Scala** a statically-typed object-oriented and functional programming language +* **Groovy** a dynamic programming language (also with static typing) and scripting languag +* **Clojure** a dynamic, and functional dialect of the Lisp programming language + +Source: https://en.wikipedia.org/wiki/List_of_JVM_languages + +--- + +# 1. Setup & Tool + +## Git Overview + +* in order to work together, you need to handle parallel changes of your team +* Git is a version control system designed to do this +* you work with branches e.g. to separate different features from each other +* important commands: + * `git clone https://...` clones a project from a git repository to your lokal file system + * `git add .` adds your changes to a stage + * `git commit .` commits your changes in your local branch + * `git push` pushes your changes to remote branch + * `git pull` get the latest changes from your repository + +--- + +# 1. Setup & Tool + +## Git Branches and Workflow + +![h:500](../imgs/git-branches.png) + +--- + +# 1. Setup & Tool + +## Git Pull Requests / Merge Requests + +* to merge feature branches in the main branch, pull request or merge requests can be created +* a pull request can be reviewed and approved before merging + +## Git Advantages + +* you can work in a separated version of code (branch) without disturbing anyone +* contolled way to do reviews before code is going live +* building and maintaining more than one release is possible +* versioned code history + +--- + +# 1. Setup & Tool + +## IDE (Integrated Development Environment) + +* Visual Studio Code +* IntelliJ +* Eclipse +* NetBeans + +## Links / Sources + +* [Java Programming Language in Wikipedia](https://en.wikipedia.org/wiki/Java_(programming_language)) +* [Offical tutorial](https://docs.oracle.com/javase/tutorial/) +* [List of JVM Languages](https://en.wikipedia.org/wiki/List_of_JVM_languages) +* [JVM, JRE, JDK](https://www.ibm.com/think/topics/jvm-vs-jre-vs-jdk) + +--- +# 1. Setup & Tool + +## Quiz + +* What are the parts of the Java platform? +* What is the difference between an interpreter and a compiler? Where is each used in Java? +* What files make up a Java project? +* What principles is Java based on? +* Why is Java-written code easier to transfer to other systems (microprocessors/operating systems)? +* When and why should you use git? +* What is the difference between debugging and running a java program? + +--- + +# 1. Setup & Tool + +## see [readme](Readme.md) for tasks + +![width:300px](../imgs/duke.png) \ No newline at end of file diff --git a/01-setup/Readme.md b/01-setup/Readme.md index 0e379a5..873cebd 100644 --- a/01-setup/Readme.md +++ b/01-setup/Readme.md @@ -2,18 +2,72 @@ In this section you will find a number of simple examples, that shall help you, setting up your development environment. -## Example list +## 1. Setup + +### Installation + +* **Check, if Java is already installed with command line: `java --version`** + * If not present, install Java JDK: + * Download JDK from https://adoptium.net/temurin/releases/ and extract zip/tar file + * add Java bin-directory to environment variable PATH +* **Check if Maven is already installed with commandline: `mvn --version`** + * If not present, install Maven: + * Download Maven from https://maven.apache.org/download.cgi and extract zip/tar file + * add Maven bin-directory to environment variable PATH +* **Check if git is available with command line: `git --version`** + * If not present, install git: + * https://git-scm.com/downloads/win +* **Check if IDE is available (e.g. execute `code` on command line)** + * If not present + * install IDE like Visual Studio Code https://code.visualstudio.com/ + * add Java Plugins:Extension Pack for Java + +### 2. Execute Quiz Program + +#### 1.1 Run and debug Quiz via IDE + +Try to run the Quiz.java program via your IDE. Set a breakpoint and start Quiz.java in debug mode + +#### 1.2 Run Quiz via command line + +As already mentioned in the slides, JDK or JRE comes with tools to execute java programs. Run your Quiz program in different ways as described: + +Root folder: ```quiz``` + +Compile in bytecode: + +```bash +mkdir classes +javac src/main/java/de/starwit/Quiz.java -d classes +``` + +Execute Java program: + +```bash +java src/main/java/de/starwit/Quiz.java +cd classes +java de.starwit.Quiz +``` + +Create and execute archive: + +```bash +jar --create --file foo.jar --main-class de.starwit.Quiz -C classes . +java -jar foo.jar +``` + +Answer the Questions. + +### 3. Execute and Change Hello World -### Hello World No software development lecture can start without a hello word example. So execute the following commands: + ```bash cd hello-world mvn clean package java -jar target/hello-world.jar ``` -#### Tasks - * Edit something in App.java and run __mvn compile__ and observe output - * Change output to three different messages of your choosing - * run __mvn test__ and observe output - * look into [logging config](hello-world/src/main/resources/log4j2.xml) and change name of log file \ No newline at end of file +* Edit something in App.java and run __mvn compile__ and observe output +* Change output to three different messages of your choosing +* run __mvn test__ and observe output \ No newline at end of file diff --git a/01-setup/hello-world/pom.xml b/01-setup/hello-world/pom.xml index 07e12bb..8b90614 100644 --- a/01-setup/hello-world/pom.xml +++ b/01-setup/hello-world/pom.xml @@ -19,21 +19,6 @@ - - org.apache.logging.log4j - log4j-api - 2.20.0 - - - org.apache.logging.log4j - log4j-core - 2.20.0 - - - org.apache.logging.log4j - log4j-slf4j-impl - 2.20.0 - junit diff --git a/01-setup/hello-world/src/main/java/de/starwit/App.java b/01-setup/hello-world/src/main/java/de/starwit/App.java index 60e5890..26dd2fe 100644 --- a/01-setup/hello-world/src/main/java/de/starwit/App.java +++ b/01-setup/hello-world/src/main/java/de/starwit/App.java @@ -1,14 +1,8 @@ package de.starwit; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - public class App { - static Logger log = LogManager.getLogger(App.class.getName()); public static void main(String[] args) { System.out.println("Hello World!"); - log.info("hello world"); - log.debug("hello world"); } } diff --git a/01-setup/pdf/01-setup-de.pdf b/01-setup/pdf/01-setup-de.pdf new file mode 100644 index 0000000..250e518 Binary files /dev/null and b/01-setup/pdf/01-setup-de.pdf differ diff --git a/01-setup/pdf/01-setup.pdf b/01-setup/pdf/01-setup.pdf new file mode 100644 index 0000000..6d99aa3 Binary files /dev/null and b/01-setup/pdf/01-setup.pdf differ diff --git a/01-setup/pdf/Readme.pdf b/01-setup/pdf/Readme.pdf new file mode 100644 index 0000000..222d95e Binary files /dev/null and b/01-setup/pdf/Readme.pdf differ diff --git a/01-setup/quiz/src/main/java/de/starwit/Quiz.java b/01-setup/quiz/src/main/java/de/starwit/Quiz.java new file mode 100644 index 0000000..6e33938 --- /dev/null +++ b/01-setup/quiz/src/main/java/de/starwit/Quiz.java @@ -0,0 +1,45 @@ +package de.starwit; + +import java.io.FileWriter; +import java.io.IOException; +import java.util.Scanner; + +public class Quiz { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + String[] questions = { + "Aus welchen Teilen besteht die Java-Plattform?", + "Was ist der Unterschied zwischen einem Interpreter und Compiler? Wo wird in Java was genutzt?", + "Aus welchen Dateien besteht ein Java-Projekt?", + "Auf welchen Prinzipien basiert Java?", + "Warum lässt sich mit Java geschriebener Code einfacher auf andere Systeme (Mikroprozessoren/Betriebssysteme) übertragen?", + "Wann und warum sollte man git benutzen?", + "Was ist der Unterschied zwischen Debuggen und Ausführen?" + }; + + StringBuilder output = new StringBuilder(); + + System.out.println("Willkommen zum Java-Quiz! Bitte beantworten Sie die folgenden Fragen:"); + output.append("# Willkommen zum Java-Quiz!\n\n"); + + for (int i = 0; i < questions.length; i++) { + System.out.println("\nFrage " + (i + 1) + ": " + questions[i]); + output.append("### ").append(i + 1).append(". ").append(questions[i]).append("\n\n"); + System.out.print("Ihre Antwort: "); + String answer = scanner.nextLine(); // Benutzerantwort einlesen + output.append(answer).append("\n\n"); + + } + + output.append("Quiz beendet!").append("\n"); + + + try (FileWriter writer = new FileWriter("quiz_output.md")) { + writer.write(output.toString()); + } catch (IOException e) { + System.out.println("Fehler beim Speichern der Datei: " + e.getMessage()); + } + + scanner.close(); + } +} diff --git a/02-java-intro/02-java-intro-de.md b/02-java-intro/02-java-intro-de.md new file mode 100644 index 0000000..d3c5aa4 --- /dev/null +++ b/02-java-intro/02-java-intro-de.md @@ -0,0 +1,406 @@ +--- +marp: true +paginate: true +theme: default +header: ![h:80](../imgs/cegos-integrata.png) +footer: 'Cegos Integrata | Java Basics | 1. Tools, Setup' +--- + + + + +# Java Basics + +![width:400px](../imgs/java2.jpg) + +# 2. Einführung in die Sprache + +--- + +## Agenda + +* Variablen, Datentypen +* Arrays +* Steuerstrukturen (Bedingungen, switch, Schleifen) +* Operatoren +* Methoden +* Klassen + +--- + +# 2. Einführung in die Sprache + +### Motivation + +* Welche Erfahrungen haben Sie mit anderen Programmiersprachen? Welche Datentypen kennen Sie? +* Was ist der Unterschied zwischen Java und Javascript hinsichtlich Datentypen? +* Was sollte Sie bei Berechnungen mit großen Ganzzahlen beachten? +* Was sollte bei Berechnungen mit Dezimalzahlen (z. B. Geld) beachtet werden? + +--- + +# 2. Einführung in die Sprache + +### Variablen + +* Eine Variable: + * hält einen Wert + * hat einen Datentyp + * wird in einer Deklaration erstellt +* Namenskonvention: + * beginnt mit einem Kleinbuchstaben + * Verwendung von CamelCase + +--- + +# 2. Einführung in die Sprache + +### Primitive Datentypen in Java + +```bash +type variableName = value; +``` + +* **byte**: Ganzzahlen von -128 bis 127 +* **short**: Ganzzahlen von -32,768 bis 32,767 +* **int**: Ganzzahlen von -2,147,483,648 bis 2,147,483,647 +* **long**: Ganzzahlen von -9,223,372,036,854,775,808 bis 9,223,372,036,854,775,807 +* **float**: Gleitkommazahlen. Geeignet für 6-7 Dezimalstellen +* **double**: Gleitkommazahlen. Geeignet für 15-16 Dezimalstellen +* **boolean**: Wahrheitswerte (true/false) +* **char**: Ein einzelnes Zeichen oder ASCII-Werte + +--- + +# 2. Einführung in die Sprache + +### Nicht-primitve, vordefinierte Datentypen + +* **String**: Speichert Text +* **BigDecimal**: Speichert Dezimalzahlen mit definierter Genauigkeit +* **BigInteger** + +#### Beispiel: + +```bash +int myNum = 5; // Ganzzahl +float myFloatNum = 5.99f; // Gleitkommazahl +char myLetter = 'D'; // Zeichen +boolean myBool = true; // Boolean +String myText = "Hallo"; // String + +String x = "10"; +int y = 20; +String z = x + y; // z wird "1020" (als String) +``` + +--- + +# 2. Einführung in die Sprache + +### Arrays + +Arrays können eine oder mehrere Dimensionen haben: + +```bash +string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; +int[][] coordinates = {{1, 2}, {2, 3}}; +``` + +> Weitere Informationen finden Sie [hier](https://www.w3schools.com/java/java_arrays.asp). + +--- + +# 2. Einführung in die Sprache + +### Operatoren + +Für eine detaillierte Liste der Operatoren besuchen Sie [w3schools - Java Operatoren](https://www.w3schools.com/java/java_operators.asp). + +#### Arithmetische Operatoren: + +* `+` Addition: Addiert zwei Werte `x + y` +* `-` Subtraktion: Subtrahiert einen Wert vom anderen `x - y` +* `*` Multiplikation: Multipliziert zwei Werte `x * y` +* `/` Division: Teilt einen Wert durch einen anderen `x / y` +* `%` Modulo: Gibt den Rest der Division zurück `x % y` +* `++` Inkrement: Erhöht den Wert einer Variablen um 1 `++x` +* `--` Dekrement: Verringert den Wert einer Variablen um 1 `--x` + +--- + +# 2. Einführung in die Sprache + +### Zuweisungsoperatoren + +| Operator | Beispiel | Gleichwertig | +|---|---|---| +| = | x = 5 | x = 5 | +| += | x += 3 | x = x + 3 | +| -= | x -= 3 | x = x - 3 | +| *= | x *= 3 | x = x * 3 | +| /= | x /= 3 | x = x / 3 | +| %= | x %= 3 | x = x % 3 | + +--- + +# 2. Einführung in die Sprache + +### Vergleichsoperatoren + +| Operator | Beispiel | Gleichwertig | +|---|---|---| +| == | Gleich | x == y | +| != | Ungleich | x != y | +| > | Größer als | x > y | +| < | Kleiner als | x < y | +| >= | Größer oder gleich | x >= y | +| <= | Kleiner oder gleich | x <= y | + +--- + +# 2. Einführung in die Sprache + +### Logische Operatoren + +* **&&** Logisches UND: Gibt `true` zurück, wenn beide Ausdrücke wahr sind `x < 5 && x < 10` +* **||** Logisches ODER: Gibt `true` zurück, wenn einer der Ausdrücke wahr ist `x < 5 || x < 4` +* **!** Logisches NICHT: Kehrt das Ergebnis um, gibt `false` zurück, wenn der Ausdruck wahr ist `!(x < 5 && x < 10)` + +--- + +# 2. Einführung in die Sprache + +### Steuerfluss - Bedingung + +```java +if (Bedingung1) { + // Codeblock, wenn Bedingung1 wahr ist +} else if (Bedingung2) { + // Codeblock, wenn Bedingung1 falsch und Bedingung2 wahr ist +} else { + // Codeblock, wenn sowohl Bedingung1 als auch Bedingung2 falsch sind +} +``` + +--- + +# 2. Einführung in die Sprache + +### Steuerfluss - Switch + +```java +switch(Ausdruck) { + case x: + // Codeblock + break; + case y: + // Codeblock + break; + default: + // Codeblock +} +``` + +--- + +# 2. Einführung in die Sprache + +### Steuerfluss - Schleifen (For-each Beispiel) + +```java +String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; +for (String i : cars) { + System.out.println(i); +} +``` + +--- + +# 2. Einführung in die Sprache + +### Methoden, Parameter und Strukturierung des Codes + +* Methoden: + * sind Codeblöcke, die nur ausgeführt werden, wenn sie aufgerufen werden + * verwenden Parameter, um Daten in die Methode zu übergeben + * können einen Rückgabewert oder `void` haben + * werden in einer Klasse oder Struktur deklariert +* Verwenden Sie Methoden, um Code wiederzuverwenden + +#### Beispiel: + +```java +class SimpleMathExtension { + public int divideTwoNumbers(int number1, int number2) { + return number1 / number2; + } +} +``` + +--- + +# 2. Einführung in die Sprache + +### Main Methode + +Die Entry-Methode, die nach dem Starten der App aufgerufen wird: + +```java +class SimpleMathExtension { + public static void Main(String[] args) { + int result = divideTwoNumbers(9, 3); + System.out.println(result); + } + + public int divideTwoNumbers(int number1, int number2) { + return number1 / number2; + } +} +``` + +--- + +# 2. Einführung in die Sprache + +### Method Overloading + +```java +/** +* Methoden haben denselben Namen, aber unterschiedliche Parameter +**/ +class MethodOverloadExample { + public int addNumbers(int number1, int number2) { + return number1 + number2; + } + + public int addNumbers(int number1, int number2, int number3) { + return number1 + number2 + number3; + } + + public double addNumbers(double number1, double number2) { + return number1 + number2; + } +} +``` + +--- + +# 2. Einführung in die Sprache + +### Lokale Variablen + +```java +public int divideTwoNumbers(int number1, int number2) { + // Lokale Variable, nur innerhalb der Methode verfügbar + int returnValue = number1 / number2; + return returnValue; +} +``` + +--- + + +# 2. Einführung in die Sprache + +### Klassendefinition + +![Klassendefinition](../imgs/OO-concepts-class-def.drawio.svg) + +--- + +# 2. Einführung in die Sprache + +## Quiz + +* Nennen Sie jeweils einen Datentyp für: ganze Zahlen, Dezimalzahlen, Text, Zeichen. +* Nennen Sie arithmetische Operatoren. Welche Arten von Operatoren gibt es noch? +* Wie heißt die Methode, die beim Starten eines Projektes ausgeführt wird? +* Was sind lokale Variablen? +* Aus welchen drei Elementen besteht die Signatur einer Methode? +* Wie kann eine Klasse verwendet werden? Was muss man dafür tun? + +--- + +# 2. Einführung in die Sprache + +## weitere Aufgaben befinden sich in der [readme](Readme.md) + +![width:300px](../imgs/duke.png) diff --git a/02-java-intro/02-java-intro.md b/02-java-intro/02-java-intro.md new file mode 100644 index 0000000..ed84504 --- /dev/null +++ b/02-java-intro/02-java-intro.md @@ -0,0 +1,439 @@ +--- +marp: true +paginate: true +theme: default +header: ![h:80](../imgs/cegos-integrata.png) +footer: 'Cegos Integrata | Java Basics | 1. Tools, Setup' +--- + + + + +# Java Basics + +![width:400px](../imgs/java2.jpg) + +### 2. Language Introduction + +--- + +# 2. Language Introduction + +## Agenda + +* Variables, Data Types +* Arrays +* Control Flow + * code block + * condition + * loops + * switch +* Operators +* Methods +* Class Definition + +--- + +# 2. Language Introduction + +## Motivation + +* What are your experiences using other programming languages? Which data types do you know +* Concerning data types - what's the difference between Java and Javascript? +* Making calculations with big whole numbers what should you consider closely? +* Making calculations decimal numbers (e.g. money), what should you be aware of? + +--- + +# 2. Language Introduction + +## Variables + +* A variable: + * holds a value + * has a data type + * is created in a declaration statement +* coding convention for naming: + * starting with lower case + * using camel case + +--- + +# 2. Language Introduction + +## Variables - Primitive Data Types + +```bash +type variableName = value; +``` + +* **byte** whole numbers from -128 to 127 +* **short** whole numbers from -32,768 to 32,767 +* **int** whole numbers from -2,147,483,648 to 2,147,483,647 +* **long** whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 +* **float** floating point numbers. Sufficient for storing 6 to 7 decimal digits +* **double** floating point numbers. Sufficient for storing 15 to 16 decimal digits +* **boolean** true or false values +* **char** a single character/letter or ASCII values + +--- + +# 2. Language Introduction + +## Variables - Non-primitive pre-defined data types + +* **String** stores text +* **BigDecimal** stores decimal numbers with a defined precision +* **BigInteger** + +## Examples + +```bash +int myNum = 5; // Integer (whole number) +float myFloatNum = 5.99f; // Floating point number +char myLetter = 'D'; // Character +boolean myBool = true; // Boolean +String myText = "Hello"; // String + +String x = "10"; +int y = 20; +String z = x + y; // z will be 1020 (a String) +``` + +--- + +# 2. Language Introduction + +## Arrays + +* can have one or more dimensions + + `string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};` + `int[][] coordinates = {{1, 2}, {2,3}};` + +> more information can be find [here](https://www.w3schools.com/java/java_arrays.asp) + +--- + +# 2. Language Introduction + +## Operators + +https://www.w3schools.com/java/java_operators.asp + +## Arithmetic Operators + +* `+` Addition: Adds together two values x + y +* `-` Subtraction: Subtracts one value from another x - y +* `*` Multiplication: Multiplies two values x * y +* `/` Division: Divides one value by another x / y +* `%` Modulus: Returns the division remainder x % y +* `++` Increment: Increases the value of a variable by 1 ++x +* `--` Decrement: Decreases the value of a variable by 1 --x + +--- + +# 2. Language Introduction + +## Assignment Operators + +| Operator | Example | Same as | +|---|---|---| +| = | x = 5 | x = 5 | +| += | x += 3 | x = x + 3 | +| -= | x -= 3 | x = x - 3 | +| *= | x *= 3 | x = x * 3 | +| /= | x /= 3 | x = x / 3 | +| %= | x %= 3 | x = x % 3 | +| &= | x &= 3 | x = x & 3 | +| ... | ... | ... | + +--- + +# 2. Language Introduction + +## Comparision Operators + +| Operator | Example | Same as | +|---|---|---| +| == | Equal to | x == y | +| != | Not equal | x != y | +| > | Greater than | x > y | +| < | Less than | x < y | +| >= | Greater than or equal to | x >= y | +| <= | Less than or equal to | x <= y | + +--- + +# 2. Language Introduction + +## Logical Operators + +* **&&** Logical and Returns true if both statements are true `x < 5 && x < 10` +* **||** Logical or Returns true if one of the statements is true `x < 5 || x < 4` +* **!** Logical not Reverse the result, returns false if the result is true `!(x < 5 && x < 10)` + +--- + +# 2. Language Introduction + +## Control flow - condition + +see https://www.w3schools.com/java/java_conditions.asp + +```java +if (condition1) { + // block of code to be executed if condition1 is true +} else if (condition2) { + // block of code to be executed if the condition1 is false and condition2 is true +} else { + // block of code to be executed if the condition1 is false and condition2 is false +} +``` +--- + +# 2. Language Introduction + +## Control flow - switch + +```java +switch(expression) { + case x: + // code block + break; + case y: + // code block + break; + default: + // code block +} +``` + +--- + +# 2. Language Introduction + +## Control flow - loop + +for each as example + +```java +String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; +for (String i : cars) { + System.out.println(i); +} +``` + +--- + +# 2. Language Introduction + +## Methods, Parameters and structuring your code + +* methods + * are code block which only runs when they are called + * use parameters to pass data into methods + * can have a return value or void + * are declared in a class or struct +* use methods in order to reuse code + +--- +# 2. Language Introduction + +## Methods, Parameters and structuring your code + +Example: + +```java +class SimpleMathExtension +{ + public int divideTwoNumbers(int number1, int number2) + { + return number1 / number2; + } +} +``` + +Definition: + +```java +class Class_Name +{ + methodName(Parameters) + { + //method statements + return Return_Value; + } +} +``` +--- +# 2. Language Introduction + +## Main Method + +Entry method which is called after start of the app + +```java +class SimpleMathExtension +{ + public static void Main(String[] args) + { + int result = divideTwoNumbers(9, 3); + System.out.println(result); + } + + public int divideTwoNumbers(int number1, int number2) + { + return number1 / number2; + } +} +``` + +--- + +# 2. Language Introduction + +## Method Overloading + +```java +/** +* Methods has the same name but different parameters +**/ +class MethodOverloadExample +{ + public int addNumbers(int number1, int number2) + { + return number1 + number2; + } + + public int addNumbers(int number1, int number2, int number3) + { + return number1 + number2 + number3; + } + + public double addNumbers(double number1, double number2) + { + return number1 + number2; + } +} +``` + +--- + +# 2. Language Introduction + +## Local Scope Variables + +```java +public int divideTwoNumbers(int number1, int number2) +{ + //local scoped variable - only available in method + int returnValue = number1 / number2; + return returnValue; +} +``` + +--- + +# 2. Language Introduction + +## Class Definition + +![Class Definition, width:800px](../imgs/OO-concepts-class-def.drawio.svg) + +--- +# 2. Language Introduction + +## Quiz + +* Name a data type for: whole numbers, decimal numbers, text, and characters. +* Name arithmetic operators. What other types of operators exist? +* What is the name of the method that is executed when a project starts? +* What are local variables? +* What three elements make up the signature of a method? +* How can a class be used? What needs to be done for that? + +--- + +# 2. Language Introduction + +## see [readme](Readme.md) for tasks + +![width:300px](../imgs/duke.png) \ No newline at end of file diff --git a/02-java-intro/Readme.md b/02-java-intro/Readme.md index 13a6824..889a749 100644 --- a/02-java-intro/Readme.md +++ b/02-java-intro/Readme.md @@ -1,19 +1,23 @@ -# Introduction to Java +# Language Introduction In this section you will find a number of simple examples, that will introduce the Java programming language. Goal is to cover the most basic features and help you, to start developing your own software as quickly as possible. -## Example list +## 1. Control + +*Controlling what's happening* -### Controlling what's happening This example demonstrate some of Java's features, to make decisions and control your program's flow. Execute the following commands: + ```bash - cd control - mvn clean package - java -jar target/control.jar +cd control +mvn clean package +java -jar target/control.jar ``` -#### Concepts covered +### Concepts Covered + This example has examples for the following language features: + * [if/else](https://www.w3schools.com/java/java_conditions.asp) -> based on variables or expressions, your program can decide different ways to act * [switch/case](https://www.w3schools.com/java/java_switch.asp) -> if you have a multitude of possible choises, based on the value of a variable, this helps you defining them in an easy to understand way. * loops @@ -21,27 +25,40 @@ This example has examples for the following language features: * [for(each)](https://www.w3schools.com/java/java_foreach_loop.asp) -> Java's way of looping over every element in arrays/collections/... * [while](https://www.w3schools.com/java/java_while_loop.asp) -> Run a loop for as long a value/expression is true -#### Tasks - * Run app and test with various inputs - * add a switch case to input method, selecting numbers 1,2,3 - * write four methods one for each above switch cases and one for default - * modify the method for case three that outputs 10 times a message - * If input is a number - * call makeDecision with that number - modify method signature - * call forloops/whileloops methods with input as parameter, use param as loop condition - * Write a method, that runs a for loop as often as _input_ but breaks if input is divisable by 11 [hint break](https://www.w3schools.com/java/java_break.asp) [hint modulus](https://www.w3schools.com/java/java_operators.asp) - * Write a method, that runs a while loop, but dismiss current iteration, if input is divisable by 11 -* Rewrite method readingInput such, that input is returned as a value, if input is a number. Remove log output from that method and move that output to main method. - -### On data types +### Tasks + +We want to test different concepts by choosing different Input numbers. Console output should look like this: + +```console +Select method to test: +(1) Condition +(2) Switch case +(3) For loop +(4) While loop +(default) random choice +``` + +1. Run app and test with various inputs +2. add a switch case to input method (method name `readingInput`), selecting numbers 1 - 4 +3. call the existing methods depending on choice +4. modify readingInput method to run switch case 10 times +5. Write a method, that runs a for loop as often as _input_ but breaks if input is divisable by 3 [hint break](https://www.w3schools.com/java/java_break.asp) [hint modulus](https://www.w3schools.com/java/java_operators.asp) +6. instead of running switch case 10 times, let user decide if he wants to run it again + +## 2. Data Types + Storing data in variables is essential for any programming language. This example provides help, to understand Java's build-in types and how you use them. [Here](https://www.w3schools.com/java/java_data_types.asp) is an overview of primitive types. + ```bash - cd data - mvn clean package - java -jar target/data.jar +cd data +mvn clean package +java -jar target/data.jar ``` -#### Concepts covered -This example has examples for the following language features: + +### Concepts Covered + +This application has examples for the following language features: + * [Java's (primitive) datatypes](https://www.w3schools.com/java/java_data_types.asp) * [Type conversions](https://www.w3schools.com/java/java_type_casting.asp) How to convert types and which rules are applied implicitly * [Operators](https://www.w3schools.com/java/java_operators.asp) @@ -50,35 +67,100 @@ This example has examples for the following language features: __Please note__ As Java is an object oriented programming language, it's type system can be extended and it is in fact the much more interesting part of the language :) -#### Tasks - * Run app - * Modify dataTypes/moreDataTypes method, such that StringBuffer output separates values - * Write a method, that in/decreases all integer types to its respective maximum/minimum - * Enhance calculating method by all [arithmetic operators](https://www.w3schools.com/java/java_operators.asp) - * Enhance array method with an array that holds random integers, after that every number in the array shall be increased by 1, except if the value is greater or equal 1000 [Hint for random numbers](https://www.geeksforgeeks.org/generating-random-numbers-in-java/) - * Write a method, that collects more than one input, checks if input is an integer and put all integers into an array. After completion - how do you know? - array shall be printed (see method multiple things) - * Can you implement output from last task, using a while loop? +### Tasks + +* Run app +* Modify methods `dataTypes` and `moreDataTypes` method, such that StringBuffer output each value in a seperate line +* Enhance method `calculations` by three [arithmetic operators](https://www.w3schools.com/java/java_operators.asp) +* Enhance array method with an array of 10 that holds random integers[Hint for random numbers](https://www.geeksforgeeks.org/generating-random-numbers-in-java/) + * output random element + * output integer values and the sum of all values + * what's happening, using datatype short instead of integer and sum or element value is greater than datatype scope? + +## 3. Parameters and Methods -### Parameters and Methods In order to break down software into manageable pieces, handing over parameters is essential. This example project shows you, how to do this on program start and with methods. + ```bash - cd params - mvn clean package - java -jar target/params.jar param1 9 param3 +cd params +mvn clean package +java -jar target/params.jar param1 9 param3 ``` -#### Concepts covered +### Concepts covered + This example has examples for the following language features: + * [Java methods](https://www.w3schools.com/java/java_methods.asp) Java's core concept to break code into manageable blocks * [Parameters in Methods](https://www.w3schools.com/java/java_methods_param.asp) How to deal with parameters for methods. * [Overloading Methods](https://www.w3schools.com/java/java_methods_overloading.asp) On the magic, that multiple methods can have the same name and yet do something different. -#### Tasks - * Run app with various parameters - * output number of handed over parameters - * Write a method, that checks for every parameter if it is a string or integer - * Put all integer params in an array, write a method that takes this array as input and results sum of all elements - * write a method that takes first parameter and switch cases over values calling a method for each case. Choose how many cases you want to distinguish - * Look at method _returnParameterExample_, create two other methods with the same name. On shall take _double_ and the other _int_ as input parameters. Both shall return the sum of it's two parameters - * move all static methods to FirstClass definition and call them from there - * __Bonus challenge__: If first parameter is an integer, this shall be taken as an input for a method, that asks for as many user inputs as the integer's value. All input values shall be stored in an array. Inform user on how many items are still necessary to input. +### Tasks + +1. run the application and explain the methods already written +2. create a method to add 3 numbers given by user input +3. we are doing hiking and bike tours, we want to know the average speed on a tour. Create a method calculating speed by given distance and time. Substract time for breaks. +4. create a method to caculate volume of a cuboid (Quader) from user input +5. create a method to caculate the entire surface of a cuboid + +## 3. Object Orientation + +The core concept of Java programming language ist object orientation. Hence programming without object orientation in Java is not really possible. You already used predifined Objects like `String`. That's why we give a short introduction for object orientation. More detailed information and complex tasks will be shown in next chapters. + +```bash +cd oop +mvn clean package +java -jar target/data.jar +``` + +### Concepts covered + +* [Classes, Objects and Instances](https://www.w3schools.com/java/java_classes.asp) +* [Attributes](https://www.w3schools.com/java/java_class_attributes.asp) +* [Methods](https://www.w3schools.com/java/java_class_methods.asp) + +### Tasks + +* create a class diagram with https://app.diagrams.net/ for class named Cuboid +* add attributes +* add methods for calculating surface and volume +* create class in java code +* create a new cuboid in main class. The attributes should be filled by user input +* calculate and output volume and surface + +## 4. Guessing Game + +This is a task to repeat learned content. Espacially control flow. + +```bash +cd guessing-game +mvn clean package +java -jar target/guessing-game.jar +``` + +### Tasks + +1. run application and implement missing parts +2. discuss understandability of the code. Can you extract methods? +3. create a class in https://app.diagrams.net/ with attributes and methods +4. Implement class + +## 5. Quiz + +This is a task to repeat learned content. Espacially multidimensional array and loops. + +```bash +cd quiz +mvn clean package +java -jar target/quiz.jar +``` + +### Tasks + +ChatGPT created the source code for this example. + +1. Check if it's running correctly and answer questions +2. Use for each loop instead of for loop. +3. discuss source code. Is it understandable, simple, well documented? +4. Use class instead of multidimensional array +5. Add questions of chapter 1 and let user choose which chapter he wants to play \ No newline at end of file diff --git a/02-java-intro/Readme.pdf b/02-java-intro/Readme.pdf new file mode 100644 index 0000000..7970254 Binary files /dev/null and b/02-java-intro/Readme.pdf differ diff --git a/02-java-intro/control/src/main/java/de/starwit/App.java b/02-java-intro/control/src/main/java/de/starwit/App.java index 9f81d91..f2dbd96 100644 --- a/02-java-intro/control/src/main/java/de/starwit/App.java +++ b/02-java-intro/control/src/main/java/de/starwit/App.java @@ -11,14 +11,14 @@ public class App { public static void main(String[] args) throws Exception { log.info("programm started"); - makeDecision(); + condition(); forloops(); whileloops(); - switching(2); readingInput(); + switching(2); } - private static void makeDecision() { + private static void condition() { int i = 10; if(i < 10) { log.info("smaller"); diff --git a/02-java-intro/data/pom.xml b/02-java-intro/data/pom.xml index 3b56e93..46385a2 100644 --- a/02-java-intro/data/pom.xml +++ b/02-java-intro/data/pom.xml @@ -8,7 +8,7 @@ data 1.0-SNAPSHOT - control + data UTF-8 diff --git a/02-java-intro/data/src/main/java/de/starwit/DataApp.java b/02-java-intro/data/src/main/java/de/starwit/DataApp.java index b87b7cb..9ce3c4d 100644 --- a/02-java-intro/data/src/main/java/de/starwit/DataApp.java +++ b/02-java-intro/data/src/main/java/de/starwit/DataApp.java @@ -15,7 +15,7 @@ public static void main(String[] args) throws Exception { dataTypes(); moreDataTypes(); calculations(); - multipleThings(); + handleMultipleVariables(); } private static void dataTypes() { @@ -60,7 +60,7 @@ private static void calculations() { log.info(result); } - private static void multipleThings() { + private static void handleMultipleVariables() { log.info("handling multiple variables"); // defining an array diff --git a/02-java-intro/guessing-game/pom.xml b/02-java-intro/guessing-game/pom.xml new file mode 100644 index 0000000..4c0b72b --- /dev/null +++ b/02-java-intro/guessing-game/pom.xml @@ -0,0 +1,51 @@ + + + + 4.0.0 + + de.starwit + guessing-game + 1.0-SNAPSHOT + + guessing-game + + + UTF-8 + UTF-8 + 21 + 21 + 21 + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + package + + single + + + guessing-game + + + + de.starwit.App + + + + + jar-with-dependencies + + false + + + + + + + diff --git a/02-java-intro/guessing-game/src/main/java/de/starwit/App.java b/02-java-intro/guessing-game/src/main/java/de/starwit/App.java new file mode 100644 index 0000000..49ee9ff --- /dev/null +++ b/02-java-intro/guessing-game/src/main/java/de/starwit/App.java @@ -0,0 +1,34 @@ +package de.starwit; + +import java.util.Random; +import java.util.Scanner; + +public class App { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + Random random = new Random(); + + int secretNumber = random.nextInt(100) + 1; // Random number between 1 and 100 + int userGuess = 0; //guessed number + int attempts = 0; + boolean guessedCorrectly = false; + + System.out.println("Welcome to the Number Guessing Game!"); + System.out.println("I have picked a number between 1 and 100. Try to guess it!"); + + while (!guessedCorrectly) { + System.out.print("Enter your guess: "); + userGuess = scanner.nextInt(); + + //TODO: Increment number of attempts + + //TODO: Create If-statemant + //if number is too low, print: Too low! Try again." + //if number is too high, print: "Too high! Try again." + //if number is guessed correctly, stop while loop and output number of attempts + } + + scanner.close(); + } +} diff --git a/02-java-intro/params/pom.xml b/02-java-intro/params/pom.xml index 0c898a1..f32bbb2 100644 --- a/02-java-intro/params/pom.xml +++ b/02-java-intro/params/pom.xml @@ -5,10 +5,10 @@ 4.0.0 de.starwit - data + params 1.0-SNAPSHOT - control + params UTF-8 diff --git a/02-java-intro/params/src/main/java/de/starwit/ParamsApp.java b/02-java-intro/params/src/main/java/de/starwit/ParamsApp.java index bff5e63..6ed9f62 100644 --- a/02-java-intro/params/src/main/java/de/starwit/ParamsApp.java +++ b/02-java-intro/params/src/main/java/de/starwit/ParamsApp.java @@ -17,10 +17,6 @@ public static void main(String[] args) throws Exception { simpleParamExample("test"); complexParamExample(args); log.info(returnParameterExample("hello", "world")); - - // let's instanciate our first object - FirstClass fc = new FirstClass(); - fc.anObjectMethod(); } private static void simpleParamExample(String s) { @@ -37,11 +33,3 @@ private static String returnParameterExample(String s1, String s2) { return s1 + s2; } } - -class FirstClass { - Logger log = LogManager.getLogger(FirstClass.class.getName()); - - public void anObjectMethod() { - log.info("Object method called"); - } -} \ No newline at end of file diff --git a/02-java-intro/pdf/02-java-intro-de.pdf b/02-java-intro/pdf/02-java-intro-de.pdf new file mode 100644 index 0000000..05107ba Binary files /dev/null and b/02-java-intro/pdf/02-java-intro-de.pdf differ diff --git a/02-java-intro/pdf/02-java-intro.pdf b/02-java-intro/pdf/02-java-intro.pdf new file mode 100644 index 0000000..cba2498 Binary files /dev/null and b/02-java-intro/pdf/02-java-intro.pdf differ diff --git a/02-java-intro/quiz/pom.xml b/02-java-intro/quiz/pom.xml new file mode 100644 index 0000000..544457e --- /dev/null +++ b/02-java-intro/quiz/pom.xml @@ -0,0 +1,51 @@ + + + + 4.0.0 + + de.starwit + quiz + 1.0-SNAPSHOT + + quiz + + + UTF-8 + UTF-8 + 21 + 21 + 21 + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + package + + single + + + quiz + + + + de.starwit.Quiz + + + + + jar-with-dependencies + + false + + + + + + + diff --git a/02-java-intro/quiz/src/main/java/de/starwit/Quiz.java b/02-java-intro/quiz/src/main/java/de/starwit/Quiz.java new file mode 100644 index 0000000..3b07d3f --- /dev/null +++ b/02-java-intro/quiz/src/main/java/de/starwit/Quiz.java @@ -0,0 +1,45 @@ +package de.starwit; + +import java.util.Random; +import java.util.Scanner; + +public class Quiz { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + Random random = new Random(); + + String[][] questions = { + {"Welche der folgenden ist eine primitive Datentyp in Java?", "String", "int", "Array", "2"}, + {"Welche Schleife wird verwendet, wenn die Anzahl der Iterationen bekannt ist?", "while", "for", "do-while", "2"}, + {"Welches Schlüsselwort wird verwendet, um eine Methode in Java zu definieren?", "method", "function", "void", "3"}, + {"Was bedeutet '==' in Java?", "Zuweisung", "Vergleich", "Logische UND-Verknüpfung", "2"}, + {"Welches Schlüsselwort beendet eine Schleife sofort?", "exit", "break", "return", "2"}, + {"Was ist ein Konstruktor in Java?", "Eine spezielle Methode zur Initialisierung eines Objekts", "Ein Datentyp", "Ein Schlüsselwort", "1"} + }; + + int score = 0; + + System.out.println("Willkommen zum Java-Quiz! Wählen Sie die richtige Antwort aus."); + + for (int i = 0; i < questions.length; i++) { + System.out.println("\nFrage " + (i + 1) + ": " + questions[i][0]); + System.out.println("1) " + questions[i][1]); + System.out.println("2) " + questions[i][2]); + System.out.println("3) " + questions[i][3]); + + System.out.print("Ihre Antwort (1-3): "); + int answer = scanner.nextInt(); + + if (answer == Integer.parseInt(questions[i][4])) { + System.out.println("Richtig!"); + score++; + } else { + System.out.println("Falsch! Die richtige Antwort war: " + questions[i][Integer.parseInt(questions[i][4])]); + } + } + + System.out.println("\nQuiz beendet! Ihr Score: " + score + "/" + questions.length); + scanner.close(); + } +} diff --git a/03-library/Readme.md b/03-library/Readme.md index 4c49344..1a6dde1 100644 --- a/03-library/Readme.md +++ b/03-library/Readme.md @@ -9,9 +9,11 @@ In the Java eco-system literally millions of libraries are available. To get an ## Example list ### Apache Commons Example + This example introduces the Apache commons collection of libraries and shows, how to use it. Check out this vast lib collection here https://commons.apache.org/ To run example, execute the following commands: + ```bash cd commons mvn clean package @@ -19,13 +21,16 @@ To run example, execute the following commands: ``` #### Concepts covered + This example has examples for the following language features: + * [Java packages](https://www.w3schools.com/java/java_packages.asp) How to manage larger blocks of code and how to address objects in libraries * How to work with libraries, that are downloaded via dependency management * [Javadoc](https://en.wikipedia.org/wiki/Javadoc) how to use Java's documentation system * [Working with Strings](https://www.w3schools.com/java/java_strings.asp) More tricks to work with strings in Java #### Tasks + * Browse JavaDoc: https://commons.apache.org/proper/commons-text/apidocs/index.html * Play with the two strings and try various combinations * Rewrite program, to get both strings as a CLI parameter @@ -33,10 +38,12 @@ This example has examples for the following language features: * Use string parameters and check every entry if name is equal to one of the params ### Maven Introduction + Maven is a tool to manage dependencies and to define build/release processes. It is a proven and quite powerful tool. No software project should be build without a tool like Maven. This example will introduce you to some (basic) features of Maven. So far you have "just" used Maven. Now it is time, to dive into some details. To run example, execute the following commands: + ```bash cd maven-example mvn package @@ -44,13 +51,16 @@ To run example, execute the following commands: ``` #### Concepts covered + Packaging software is about managing complexity and it covers the following concepts: + * [Dependency Management](https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html) * [Build Management](https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html) * [Continuously building software](https://www.redhat.com/en/topics/devops/what-is-ci-cd) * [Log4J](https://howtodoinjava.com/log4j2/useful-conversion-pattern-examples/) - output of your application that is meant, to understand it's state, should be done with a logging framework. #### Tasks + * Run example with phases: compile, test, package, install * Observe results in target folder, check also content HOME_DIR/.m2 * Make sure you understand executable jar process - change name of resulting filename @@ -59,21 +69,24 @@ Packaging software is about managing complexity and it covers the following conc * One thing Maven is great, is to track software bill of materials - add [CycloneDX plugin](https://github.com/CycloneDX/cyclonedx-maven-plugin) and execute it ### Apache Commons CLI + This example shall be build by you. As you just learned how to add a library to your software, create a new folder called apachecli and copy content of last example. Rename all necessary fields in pom.xml and add [Apache CLI](https://commons.apache.org/proper/commons-cli/introduction.html) as a dependency. This example shall except the following parameters: + * -f that holds CSV file location from last example * -t that prints time and date * -h to print info and parameter help #### Tasks + * create a new project, you can let Maven help you: + ```java mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.5 -DjavaCompilerVersion=21 ``` + * Add commons CLI as a dependency * Implement parameter handover * __Bonus challenge:__ Take CSV reading code from first example in this chapter and let it run, if -f parameter is set. - - \ No newline at end of file diff --git a/PrepareYourComputer.md b/PrepareYourComputer.md index f053824..87a70ce 100644 --- a/PrepareYourComputer.md +++ b/PrepareYourComputer.md @@ -5,15 +5,15 @@ Neccessary: * openJDK - Java Compiler * Maven - Build & Dependency Management -* Visual Studio Code - Write & edit source code +* IDE like Visual Studio Code - Write & edit source code * git - Source code versioning Recommended + * Java Mission Control - Observe the Java virtual machine * Docker - Build and run containers * NodeJS/NPM - Build and package Javascript applications (used for web frontends) - ## Downloading Software For each tool, you can download installation packages. * Java: https://adoptium.net/temurin/releases/ diff --git a/imgs/OO-concepts-class-def.drawio.svg b/imgs/OO-concepts-class-def.drawio.svg new file mode 100644 index 0000000..7c93199 --- /dev/null +++ b/imgs/OO-concepts-class-def.drawio.svg @@ -0,0 +1,112 @@ + + + + + + + + + +
+
+
+ <<class name>> +
+
+
+
+ + <<class name>> + +
+
+ + + +
+
+
+ attribute1: data type +
+
+
+
+ + attribute1: data type + +
+
+ + + +
+
+
+ attribute2: data type +
+
+
+
+ + attribute2: data type + +
+
+ + + +
+
+
+ ______________________________________________ +
+
+
+
+ + ______________________________________________ + +
+
+ + + +
+
+
+ method1 (data type: param, ...): data type of return value +
+
+
+
+ + method1 (data type: param, ...): data type of retur... + +
+
+ + + +
+
+
+ method2 (data type: param, ...): data type of return value +
+
+
+
+ + method2 (data type: param, ...): data type of retur... + +
+
+
+ + + + + Text is not SVG - cannot display + + + +
\ No newline at end of file diff --git a/imgs/cegos-integrata.png b/imgs/cegos-integrata.png new file mode 100644 index 0000000..445655f Binary files /dev/null and b/imgs/cegos-integrata.png differ diff --git a/imgs/duke.png b/imgs/duke.png new file mode 100644 index 0000000..77bab1d Binary files /dev/null and b/imgs/duke.png differ diff --git a/imgs/git-branches.png b/imgs/git-branches.png new file mode 100644 index 0000000..9a4e0e2 Binary files /dev/null and b/imgs/git-branches.png differ diff --git a/imgs/java.jpg b/imgs/java.jpg new file mode 100644 index 0000000..67d512c Binary files /dev/null and b/imgs/java.jpg differ diff --git a/imgs/java2.jpg b/imgs/java2.jpg new file mode 100644 index 0000000..36e4b15 Binary files /dev/null and b/imgs/java2.jpg differ diff --git a/slides.md b/slides.md index 303a747..e1f06ee 100644 --- a/slides.md +++ b/slides.md @@ -42,7 +42,9 @@ This section contains an introduction into the Java programming language. Next t * Intermediary code * Three decades of optimization * OpenJDK & Java's release cycle + --- + ## The Java virtual machine Which runs everything, has been around forever and will become your best friend. ![width:700px](imgs/JvmSpec7.png)