Download presentation
Presentation is loading. Please wait.
1
Lecture 1 – Java basics
2
IDE (Integrated development environment)
Used IDE in these examples and shortcuts: Eclipse Not necessary, but easier to use than raw .txt files Other IDEs: IntelliJ, NetBeans, etc.
3
The Java language //This is a comment (shortcut: select a section/line and press Ctrl + 7) /** This is a multi line comment **/ Uses braces {} to encapsulate { classes and methods } Uses paranthesis () to ecapsulate method(parameters), do math (x * y) + (z / x), etc. Uses square brackets [] to get an index[i] in an array, initialize an array: String[] stringArray = new String[5]; etc.
4
The Java language 0-based index String: T e x t e x a m p l e
Length is 11 (number of characters in the string), but maximum index is 10
5
The Java language – Comparing values
A comparison results in a boolean: true or false Strings and objects: someString.equals(otherString); someString equals otherString !someString.equals(otherString); someString doesn’t equal otherString Rest: || (OR) this or that this || that && (AND) this and that this && that >= (greater or equal to) this bigger than/equal to that this >= that <= (less or equal to) this less than/equal to that this <= that == (equal to) this equal to that this == that != (not equal to) this not equal to that this != that < (less than) this less than that this < that > (greater than) this greater than that this > that
6
The Java language – The main method
public class YourClassName { public static void main(String[] args) { // put your code here } } Java has reserved the class name ”main” as the starting method of any program
7
Assigning values to variables
Syntax: variable variable_name = value; String s = “java basics”; // double quotation marks for strings boolean isReadyForDelivery = true; double salary = ; int daysOfWeek = 7; char keyPressed = ‘y’; // single quotation marks for chars
8
Printing values to the console
System.out.println(”text to be printed, ending with line break”); System.out.print(”text to be printed, without a line break”); Example: System.out.println(”first line with line break”); System.out.print(”second line without linebreak”); System.out.print(”, also on second line”); Output: first line with line break second line without linebreak, also on second line Shortcut: ”syso” or ”sysout” Ctrl + Space = System.out.println();
9
Reading input from the console
Same syntax: variable variable_name = value; Scanner scan = new Scanner(System.in); Method used from the scanner: scan.nextLine(); Reads a line from the console
10
Reading and printing input
public class ExampleClass { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print(”enter value: ”); String inputString = scan.nextLine(); scan.close(); System.out.println(inputString); }
11
Modifying Strings (uppercase, lowercase, substring)
someString.toUpperCase(); someString.toLowerCase(); someString.substring(int beginIndex, int endIndex); Example: String someString = “Baltzar”; System.out.println(someString.substring(1, 4)); prints out: “alt” Note, indexes can give: IndexOutOfBoundsException if the requested index is below minimum index, or above maximum index
12
Practise: StringModifier
public class StringModifier { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print(”enter value: ”); String inputString = scan.nextLine(); // Print inputString in lower case // Print inputString in UPPER CASE // Print only the first two letters of inputString // (you can assume input.length > 2) } Methods needed: someString.toUpperCase(); Returns the string in UPPER CASE someString.toLowerCase(); Returns the value in lower case someString.substring(int beginIndex, int endIndex); Returns the value starting at index beginIndex, and ending at one character before endIndex, example: String a = “abcdefg”; a.substring(2, 5) “cde” Explanation: “a b c d e f g ” Index:
13
Solution: StringModifier
public class StringModifier { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print(”enter value: ”); String inputString = scan.nextLine(); System.out.println(inputString.toLowerCase()); System.out.println(inputString.toUpperCase()); System.out.println(inputString.substring(0, 2)); }
14
Why doesn’t the string change value?
public class ExampleClass { public static void main(String[] args) { String s = ”abcdefgh”; s.toUpperCase(); System.out.println(s); // prints out ”abcdefgh” }
15
Answer: Strings are immutable
public class ExampleClass { public static void main(String[] args) { String s = ”abcdefgh”; // We must assign the returned string from toUpperCase() to our s-variable: s = s.toUpperCase(); System.out.println(s); // prints out ”ABCDEFGH” } Rule: Strings are immutable, its value cannot be changed, it can only be reassigned a new value.
16
Modifying Strings (replacing characters and sequences):
someString.replace(char oldChar, char newChar); // replaces all instances of oldChar with newChar: Example: ”some string”.replace(’s’, ’!’) ”ome tring” someString.replaceAll(String regex, String replacement); // replaces all instances of given sequence, with replacement: Example: ”some string some”.replaceAll(”some”, ”new ”); ”new string new ” someString.replaceFirst(String regex, String replacement); // replaces first instance of given sequence, with replacement: Example: ”some string some”.replaceFirst(”some”, ”new ”); ”new string some”
17
Methods listens to values, no matter the form
String text = ”some string some other string”; String toBeReplaced = ”string”; String toBeReplacedWith = ”replacement” text.replaceAll(toBeReplaced, toBeReplacedWith); ”some replacement some other replacement” Is the same as: ”some string some other string”.replaceAll(”string”, ”replacement”); ”some replacement some other replacement”
18
Practise: StringReplacer
Write a program that reads one line which will be the text, and then a string which is the target for modification. It shall then print the String with all of the following modifications in one run: The text, having the target string replaced with: ”!” The text, having the target string removed completely The text, having the target string in uppercase The text, having the target string in lowercase Example: Input ”barbapapa”, ”a” prints(in the same run): b!rb!p!p! brbpp bArbApApA barbapapa Input ” ”, ”-” prints(in the same run): 9124!5131!123123! Used methods and classes: Scanner scan = new Scanner(System.in); scan.readLine(); System.out.println(); //String methods: string.replaceAll(regex, replacement); string.toUpperCase(); string.toLowerCase(); An empty String = ””
19
Solution: StringReplacer
public class StringReplacer { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String text = scan.nextLine(); String replacementLetter = scan.nextLine(); System.out.println(text.replaceAll(replacementLetter, "!")); // replaced with ! System.out.println(text.replaceAll(replacementLetter, "")); // removed System.out.println(text.replaceAll(replacementLetter, replacementLetter.toUpperCase())); // upper case System.out.println(text.replaceAll(replacementLetter, replacementLetter.toLowerCase())); // lower case }
20
Storing the result of a comparison in a boolean
int age = 17; int minimumAge = 18; boolean ageCheck = age >= minimumAge; //storing the result of the comparison in ageCheck if (ageCheck) { System.out.println(”profit”); } else { System.out.println(”trouble”); // this will be printed } Is the same as: if (17 >= 18) { System.out.println(”profit”); } else { System.out.println(”trouble”); // this will be printed }
21
While-loop Syntax: while (boolean) { // this will be executed as long as boolean == true } // this will be executed when boolean == false Example: int numberOfLivesLeft = 10; while (numberOfLivesLeft > 0) { numberOfLivesLeft--; // Decrements the value by 1 each time System.out.println(”The deadly hangover takes its toll, you know have ” + numberOfLivesLeft); } System.out.println(”Damn, have some lives”); //Executed when the condition: (numberOfLivesLeft > 0) == false while (numberOfLives < 10) { numberOfLives++; // Increments value by 1 each time } System.out.println("Good to go, and don’t learn from your mistakes, 02:45 jaeger bombs are always a good idea");
22
While-loop – Infinite loop
public class ExampleClass { public static void main(String[] args) { while (true) { System.out.println(”So much printing”); } System.out.println(”This will never be printed”); } }
23
While-loop – Find the error
public class ExampleClass { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String inputLetter = ”y”; while (inputLetter == ”y”) { System.out.println(” ..yes?”); inputLetter = scan.nextLine(); } System.out.println(”nnno”); } }
24
While-loop – Solution public class ExampleClass { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String inputLetter = ”y”; while (inputLetter.equals(”y”)) { System.out.println(” ..yes?”); inputLetter = scan.nextLine(); } System.out.println(”nnno”); } }
25
While-loop – Find the error
public class ExampleClass { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String inputLetter = ”y”; boolean isInputLetterY = inputLetter.equalsIgnoreCase(”y”); // Storing the comparison in isInputLetterY while (isInputLetterY) { System.out.println(” ..yes?”); inputLetter = scan.nextLine(); } System.out.println(”nnno”); } }
26
While-loop – Solution public class ExampleClass { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String inputLetter = ”y”; boolean isInputLetterY = inputLetter.equalsIgnoreCase(”y”); while (isInputLetterY) { // Infinite loop, isInputLetterY is never changed System.out.println(” ..yes?”); inputLetter = scan.nextLine(); isInputLetterY = inputLetter.equalsIgnoreCase(”y”); } System.out.println(”nnno”); } }
27
Parsing the numeric value from a String
public class ExampleClass { public static void main(String[] args) { int parsedNumber = Integer.parseInt(”a”); // NumberFormatException int parsedNumber2 = Integer.parseInt(”3”); // OK int parsedNumber3 = Integer.parseInt(”3.5”); // NumberFormatException double parsedNumber4 = Double.parseDouble(”3.5”); // OK } }
28
Parsing the numeric value from a scanned String
public class ExampleClass { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String stringToBeParsed = scan.nextLine(); int parsedNumber = Integer.parseInt(stringToBeParsed); // Can give NumberFormatException if (parsedNumber < 10) { System.out.println(”Number is below 10”); } else if (parsedNumber > 10) { System.out.println(”Number is above 10”); } else { System.out.println(”Number is equal to 10”); } } }
29
Practise: Number to ten
Write a program that reads a number (String which is then parsed to a number), which does both of the following things in the same loop (no exception handling is required): If the number is equal to 10, print ”The number is 10” If the number is less than 10, increment the number to 10 and print out the incrementions, finish with ”The number is 10” Input 7 returns: 8 9 10 The number is 10 Input 9 returns: 10 Input 10 returns: The number is 10 If the number is greater than 10, decrement the number to 10 and print out the decrementions, finish with ”The number is 10”: Input 14 returns: 13 12 11 Input 11 gives: 10 Input 10 gives: The number is 10 Methods and objects used: Scanner, nextLine(); System.out.println(); while (boolean) { //code here } String number = ”123”; int parsedNumber = Integer.parseInt(number); parsedNumber++; //increments value by 1 parsedNumber--; //decrements value by 1 if (condition1) { //do this if condition is true } else if (condition2) { //do this is condition1 == false, but condition2 == true } else { //do this if all conditions are false }
30
Solution: Number to ten
public class NumberToTen { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String scannedString = scan.nextLine(); scan.close(); int scannedNumber = Integer.parseInt(scannedString); while (scannedNumber != 10) { if (scannedNumber < 10) { scannedNumber++; } else { scannedNumber--; } System.out.println(scannedNumber); } System.out.println("The number is 10"); } }
31
Solution: Number to ten (solution 2)
public class NumberToTenAdvanced { public static void main(String[] args) { int scannedNumber = 0; if ((scannedNumber = Integer.parseInt(new Scanner(System.in).nextLine())) != 10) { while (scannedNumber != 10) System.out.println(scannedNumber += (scannedNumber < 10) ? 1 : -1); } System.out.println("The number is 10"); } } Less readability More advanced doesn’t necessarily mean better
32
Exceptions When something has gone wrong, an Exception is thrown
Can be handled via try catch (later topic) Prints a stack trace
33
Reading the stack trace
34
Reading the stack trace
Exception in thread "main" java.lang.NumberFormatException: For input string: "this is definitely not a number” refers to what exception (error) has occured at ExampleClass.main(ExampleClass.java:4) refers to what line in what class has caused the error (line 4 in ExampleClass)
35
Google the exception name
36
Matching the Stackoverflow-question
37
Finding the answer
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.