Skip to content

Commit

Permalink
Add lab-03 Snippets (#120)
Browse files Browse the repository at this point in the history
* Add snippets
* Format code
* Fix initiallizers
  • Loading branch information
desislavaa authored Oct 27, 2023
1 parent 38f0652 commit ee0ccd5
Show file tree
Hide file tree
Showing 23 changed files with 551 additions and 0 deletions.
1 change: 1 addition & 0 deletions 03-oop-in-java-ii/snippets/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# OOP in Java (part II) / Code snippets
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package argumentpassing;

public class PrimitiveArgumentsExample {
public static void main(String[] args) {
int x = 10;
System.out.println("Before modifyPrimitive: " + x);

modifyPrimitive(x);

System.out.println("After modifyPrimitive: " + x);
}

public static void modifyPrimitive(int number) {
number = 20;
System.out.println("Inside method: " + number);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package argumentpassing;

public class ReferencesExample {
public static void main(String[] args) {
Person person = new Person("Alice");

System.out.println("Before modifyReference: " + person.getName());
modifyReference(person);
System.out.println("After modifyReference: " + person.getName());

System.out.println("Before modifyObject: " + person.getName());
modifyObject(person);
System.out.println("After modifyObject: " + person.getName());
}

public static void modifyObject(Person p) {
p.setName("Bob");
System.out.println("Inside modifyObject: " + p.getName());
}

public static void modifyReference(Person p) {
p = new Person("Mary");
System.out.println("Inside modifyReference: " + p.getName());
}
}

class Person {
private String name;

public Person(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
21 changes: 21 additions & 0 deletions 03-oop-in-java-ii/snippets/src/enums/Day.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package enums;

// Enums extend the java.lang.Enum class implicitly.
// Therefore, you cannot extend any other class in enum.
public enum Day {

SUNDAY("Sun."), MONDAY("Mon."), TUESDAY("Tu."), WEDNESDAY("Wed."), THURSDAY("Th."), FRIDAY("Fr."), SATURDAY("Sat.");

private String abbreviation;

// Constructor is always private or default.
// You cannot create an instance of enum using the new operator.
Day(String abbreviation) {
this.abbreviation = abbreviation;
}

public String getAbbreviation() {
return abbreviation;
}

}
38 changes: 38 additions & 0 deletions 03-oop-in-java-ii/snippets/src/enums/DaysExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package enums;

import java.util.Arrays;

class DaysExample {

private Day day;

public DaysExample(Day day) {
this.day = day;
}

public static void main(String[] args) {
DaysExample example = new DaysExample(Day.TUESDAY);
example.tellItLikeItIs(); // Midweek days are so-so.

// The values() method is a special method added by the compiler
Day[] days = Day.values();
System.out.println(Arrays.toString(days)); // [SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]

// The name must match exactly the identifier used to declare the enum constant in this type.
System.out.println(Day.valueOf("MONDAY")); // MONDAY

System.out.println(Day.MONDAY.getAbbreviation()); // Mon.
}

public void tellItLikeItIs() {
String message = switch (day) {
case MONDAY -> "Mondays are bad.";
case FRIDAY -> "Fridays are better.";
case SATURDAY, SUNDAY -> "Weekends are best.";
default -> "Midweek days are so-so.";
};

System.out.println(message);
}

}
21 changes: 21 additions & 0 deletions 03-oop-in-java-ii/snippets/src/enums/StringConstants.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package enums;

public class StringConstants {

// 1. This approach can lead to performance problems because it relies on string comparisons
// 2. If the constants contain typos they will escape detection at compile time and result in bugs at runtime
// 3. There is no way to iterate over all enumerated types
// 4. There is no type safety
public static final String MONDAY = "monday";
public static final String TUESDAY = "tuesday";
public static final String WEDNESDAY = "wednesday";
public static final String THURSDAY = "thursday";
public static final String FRIDAY = "friday";
public static final String SATURDAY = "saturday";
public static final String SUNDAY = "sunday";

// We can pass whatever we want here, no matter if it is an actual day or not
public static void printDayMessage(String day) {
// Print some message according to the day
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package exceptions;

public class AuthenticationException extends Exception {

public AuthenticationException(String message) {
super(message);
}

public AuthenticationException(String message, Throwable cause) {
super(message, cause);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package exceptions;

public class EmailNotFoundException extends AuthenticationException {

public EmailNotFoundException() {
super("Email not found");
}

}
26 changes: 26 additions & 0 deletions 03-oop-in-java-ii/snippets/src/exceptions/HelpfulNPE.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package exceptions;

public class HelpfulNPE {

public static void main(String[] args) {
new HelpfulNPE().helpfulNPEdemo();
}

public void helpfulNPEdemo() {
A a = new A();
a.b.c.number = 100;
}

class A {
public B b;
}

class B {
public C c;
}

class C {
public int number;
}

}
99 changes: 99 additions & 0 deletions 03-oop-in-java-ii/snippets/src/exceptions/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package exceptions;

public class Main {

public static void main(String[] args) {
handleExceptions();
}

private static void handleExceptions() {
// Good - catches the most specific exception
// We are sure an error occurred because the password was wrong
try {
throw new WrongPasswordException();
} catch (WrongPasswordException e) {
System.out.println("\n1:");
System.out.println("Just to be sure -> " + e.getClass().getTypeName());
}

// Bad - catches a generic authentication exception
// We have no idea what kind of authentication error occurred
try {
throw new EmailNotFoundException();
} catch (AuthenticationException e) {
System.out.println("\n2:");
System.out.println("AuthenticationException happened to be -> " + e.getClass().getTypeName());
}

try {
throw new WrongPasswordException();
} catch (AuthenticationException e) {
System.out.println("\n3:");
System.out.println("AuthenticationException happened to be -> " + e.getClass().getTypeName());
}

try {
throwsEmailNotFoundException();
throwsWrongPasswordException();
} catch (EmailNotFoundException | WrongPasswordException e) {
System.out.println("\n4:");
System.out.println("AuthenticationException happened to be -> " + e.getClass().getTypeName());
}

// Awful - catches every checked exception
// We have no idea what error occurred
try {
throw new EmailNotFoundException();
} catch (Exception e) {
System.out.println("\n5:");
System.out.println("Exception happened to be -> " + e.getClass().getTypeName());
}
// ==========================================

// Finally is always executed
try {
doesntThrowException();
} catch (WrongPasswordException e) {
System.out.println(e.getClass().getTypeName() + " was caught");
} finally {
System.out.println("\n6:");
System.out.println("Finally is executed despite an exception wasn't thrown");
}

try {
throw new WrongPasswordException();
} catch (WrongPasswordException e) {
System.out.println("\n7:");
System.out.println("" + e.getClass().getTypeName() + " was caught");
} finally {
System.out.println("Finally is executed after the exception is caught");
}

// Finally is executed even though we return in catch
System.out.println("\n8: " + getNumber());
}

// This is very ugly, don't do this at home. It's just for the sake of demonstration
private static int getNumber() {
try {
throw new Exception();
// return 1; -> Unreachable
} catch (Exception e) {
return 2;
} finally {
return 3;
}
}

private static void throwsEmailNotFoundException() throws EmailNotFoundException {
throw new EmailNotFoundException();
}

private static void throwsWrongPasswordException() throws WrongPasswordException {
throw new WrongPasswordException();
}

private static void doesntThrowException() throws WrongPasswordException {
}

}
35 changes: 35 additions & 0 deletions 03-oop-in-java-ii/snippets/src/exceptions/SmartNPEExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package exceptions;

class Human {
private String name;

public Human(String name) {
this.name = name;
}

public String getName() {
return name;
}
}

class Student extends Human {
int facultyNumber;

public Student(String name, int facultyNumber) {
super(name);
this.facultyNumber = facultyNumber;
}

}

public class SmartNPEExample {

public static void main(String[] args) {
Student student1 = new Student("Pancho", 62438);
Student student2 = new Student(null, 45689);

System.out.println(student1.getName().startsWith("P"));
System.out.println(student2.getName().startsWith("P"));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package exceptions;

public class WrongPasswordException extends AuthenticationException {

public WrongPasswordException() {
super("Wrong password");
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package exceptions.signature;

public class ExceptionSignature extends ExceptionSignatureBase {

@Override
public void fun(String s) throws MyException {
try {
super.fun(s);
} catch (MyExceptionBase e) {
throw new RuntimeException(e);
}
}

}

class MyException extends MyExceptionBase {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package exceptions.signature;

import java.io.IOException;

public class ExceptionSignatureBase {

public void fun(String s) throws MyExceptionBase {

}

}

class MyExceptionBase extends IOException {

}
Loading

0 comments on commit ee0ccd5

Please sign in to comment.