2 - Second commit for articles:
* to core-java-lang: * https://www.baeldung.com/java-inner-interfaces * https://www.baeldung.com/java-polymorphism * https://www.baeldung.com/java-recursion * https://www.baeldung.com/java-finalize * https://www.baeldung.com/java-method-overload-override * https://www.baeldung.com/java-deep-copy * https://www.baeldung.com/java-inheritance * https://www.baeldung.com/java-type-casting * https://www.baeldung.com/java-final * https://www.baeldung.com/a-guide-to-java-enums
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Animal {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Animal.class);
|
||||
|
||||
public void eat() {
|
||||
LOGGER.info("animal is eating");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class AnimalFeeder {
|
||||
|
||||
public void feed(List<Animal> animals) {
|
||||
animals.forEach(animal -> {
|
||||
animal.eat();
|
||||
if (animal instanceof Cat) {
|
||||
((Cat) animal).meow();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void uncheckedFeed(List<Animal> animals) {
|
||||
animals.forEach(animal -> {
|
||||
animal.eat();
|
||||
((Cat) animal).meow();
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class AnimalFeederGeneric<T> {
|
||||
private Class<T> type;
|
||||
|
||||
public AnimalFeederGeneric(Class<T> type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public List<T> feed(List<Animal> animals) {
|
||||
List<T> list = new ArrayList<T>();
|
||||
animals.forEach(animal -> {
|
||||
if (type.isInstance(animal)) {
|
||||
T objAsType = type.cast(animal);
|
||||
list.add(objAsType);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
|
||||
}
|
||||
16
core-java-lang/src/main/java/com/baeldung/casting/Cat.java
Normal file
16
core-java-lang/src/main/java/com/baeldung/casting/Cat.java
Normal file
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Cat extends Animal implements Mew {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Cat.class);
|
||||
|
||||
public void eat() {
|
||||
LOGGER.info("cat is eating");
|
||||
}
|
||||
|
||||
public void meow() {
|
||||
LOGGER.info("meow");
|
||||
}
|
||||
}
|
||||
12
core-java-lang/src/main/java/com/baeldung/casting/Dog.java
Normal file
12
core-java-lang/src/main/java/com/baeldung/casting/Dog.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Dog extends Animal {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Dog.class);
|
||||
|
||||
public void eat() {
|
||||
LOGGER.info("dog is eating");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
public interface Mew {
|
||||
public void meow();
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class Address implements Serializable, Cloneable {
|
||||
|
||||
@Override
|
||||
public Object clone() {
|
||||
try {
|
||||
return (Address) super.clone();
|
||||
} catch (CloneNotSupportedException e) {
|
||||
return new Address(this.street, this.getCity(), this.getCountry());
|
||||
}
|
||||
}
|
||||
|
||||
private static final long serialVersionUID = 1740913841244949416L;
|
||||
private String street;
|
||||
private String city;
|
||||
|
||||
private String country;
|
||||
|
||||
public Address(Address that) {
|
||||
this(that.getStreet(), that.getCity(), that.getCountry());
|
||||
}
|
||||
|
||||
public Address(String street, String city, String country) {
|
||||
this.street = street;
|
||||
this.city = city;
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public Address() {
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
}
|
||||
|
||||
48
core-java-lang/src/main/java/com/baeldung/deepcopy/User.java
Normal file
48
core-java-lang/src/main/java/com/baeldung/deepcopy/User.java
Normal file
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class User implements Serializable, Cloneable {
|
||||
|
||||
private static final long serialVersionUID = -3427002229954777557L;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private Address address;
|
||||
|
||||
public User(String firstName, String lastName, Address address) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public User(User that) {
|
||||
this(that.getFirstName(), that.getLastName(), new Address(that.getAddress()));
|
||||
}
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object clone() {
|
||||
User user;
|
||||
try {
|
||||
user = (User) super.clone();
|
||||
} catch (CloneNotSupportedException e) {
|
||||
user = new User(this.getFirstName(), this.getLastName(), this.getAddress());
|
||||
}
|
||||
user.address = (Address) this.address.clone();
|
||||
return user;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
}
|
||||
88
core-java-lang/src/main/java/com/baeldung/enums/Pizza.java
Normal file
88
core-java-lang/src/main/java/com/baeldung/enums/Pizza.java
Normal file
@@ -0,0 +1,88 @@
|
||||
package com.baeldung.enums;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Pizza {
|
||||
|
||||
private static EnumSet<PizzaStatusEnum> deliveredPizzaStatuses = EnumSet.of(PizzaStatusEnum.DELIVERED);
|
||||
|
||||
private PizzaStatusEnum status;
|
||||
|
||||
public enum PizzaStatusEnum {
|
||||
ORDERED(5) {
|
||||
@Override
|
||||
public boolean isOrdered() {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
READY(2) {
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
DELIVERED(0) {
|
||||
@Override
|
||||
public boolean isDelivered() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private int timeToDelivery;
|
||||
|
||||
public boolean isOrdered() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isReady() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isDelivered() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getTimeToDelivery() {
|
||||
return timeToDelivery;
|
||||
}
|
||||
|
||||
PizzaStatusEnum(int timeToDelivery) {
|
||||
this.timeToDelivery = timeToDelivery;
|
||||
}
|
||||
}
|
||||
|
||||
public PizzaStatusEnum getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(PizzaStatusEnum status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public boolean isDeliverable() {
|
||||
return this.status.isReady();
|
||||
}
|
||||
|
||||
public void printTimeToDeliver() {
|
||||
System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
|
||||
}
|
||||
|
||||
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
|
||||
return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
|
||||
return pzList.stream().collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
|
||||
}
|
||||
|
||||
public void deliver() {
|
||||
if (isDeliverable()) {
|
||||
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
|
||||
this.setStatus(PizzaStatusEnum.DELIVERED);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.enums;
|
||||
|
||||
public enum PizzaDeliveryStrategy {
|
||||
EXPRESS {
|
||||
@Override
|
||||
public void deliver(Pizza pz) {
|
||||
System.out.println("Pizza will be delivered in express mode");
|
||||
}
|
||||
},
|
||||
NORMAL {
|
||||
@Override
|
||||
public void deliver(Pizza pz) {
|
||||
System.out.println("Pizza will be delivered in normal mode");
|
||||
}
|
||||
};
|
||||
|
||||
public abstract void deliver(Pizza pz);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.enums;
|
||||
|
||||
public enum PizzaDeliverySystemConfiguration {
|
||||
INSTANCE;
|
||||
|
||||
PizzaDeliverySystemConfiguration() {
|
||||
// Do the configuration initialization which
|
||||
// involves overriding defaults like delivery strategy
|
||||
}
|
||||
|
||||
private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
|
||||
|
||||
public static PizzaDeliverySystemConfiguration getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public PizzaDeliveryStrategy getDeliveryStrategy() {
|
||||
return deliveryStrategy;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.finalize;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
public class CloseableResource implements AutoCloseable {
|
||||
private BufferedReader reader;
|
||||
|
||||
public CloseableResource() {
|
||||
InputStream input = this.getClass().getClassLoader().getResourceAsStream("file.txt");
|
||||
reader = new BufferedReader(new InputStreamReader(input));
|
||||
}
|
||||
|
||||
public String readFirstLine() throws IOException {
|
||||
String firstLine = reader.readLine();
|
||||
return firstLine;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
reader.close();
|
||||
System.out.println("Closed BufferedReader in the close method");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.finalize;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
public class Finalizable {
|
||||
private BufferedReader reader;
|
||||
|
||||
public Finalizable() {
|
||||
InputStream input = this.getClass().getClassLoader().getResourceAsStream("file.txt");
|
||||
reader = new BufferedReader(new InputStreamReader(input));
|
||||
}
|
||||
|
||||
public String readFirstLine() throws IOException {
|
||||
String firstLine = reader.readLine();
|
||||
return firstLine;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finalize() {
|
||||
try {
|
||||
reader.close();
|
||||
System.out.println("Closed BufferedReader in the finalizer");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public class BlackCat {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public class BlackDog extends Dog {
|
||||
// public void sound() {
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public final class Cat {
|
||||
|
||||
private int weight;
|
||||
|
||||
public int getWeight() {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public void setWeight(int weight) {
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public void methodWithFinalArguments(final int x) {
|
||||
// x=1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public class Dog {
|
||||
|
||||
public final void sound() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class ArmoredCar extends Car implements Floatable, Flyable{
|
||||
private int bulletProofWindows;
|
||||
private String model;
|
||||
|
||||
public void remoteStartCar() {
|
||||
// this vehicle can be started by using a remote control
|
||||
}
|
||||
|
||||
public String registerModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public String getAValue() {
|
||||
return super.model; // returns value of model defined in base class Car
|
||||
// return this.model; // will return value of model defined in ArmoredCar
|
||||
// return model; // will return value of model defined in ArmoredCar
|
||||
}
|
||||
|
||||
public static String msg() {
|
||||
// return super.msg(); // this won't compile.
|
||||
return "ArmoredCar";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void floatOnWater() {
|
||||
System.out.println("I can float!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fly() {
|
||||
System.out.println("I can fly!");
|
||||
}
|
||||
|
||||
public void aMethod() {
|
||||
// System.out.println(duration); // Won't compile
|
||||
System.out.println(Floatable.duration); // outputs 10
|
||||
System.out.println(Flyable.duration); // outputs 20
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class BMW extends Car {
|
||||
public BMW() {
|
||||
super(5, "BMW");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return model;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class Car {
|
||||
private final int DEFAULT_WHEEL_COUNT = 5;
|
||||
private final String DEFAULT_MODEL = "Basic";
|
||||
|
||||
protected int wheels;
|
||||
protected String model;
|
||||
|
||||
public Car() {
|
||||
this.wheels = DEFAULT_WHEEL_COUNT;
|
||||
this.model = DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
public Car(int wheels, String model) {
|
||||
this.wheels = wheels;
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
// Check essential parts
|
||||
// If okay, start.
|
||||
}
|
||||
public static int count = 10;
|
||||
public static String msg() {
|
||||
return "Car";
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return model;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class Employee {
|
||||
private String name;
|
||||
private Car car;
|
||||
|
||||
public Employee(String name, Car car) {
|
||||
this.name = name;
|
||||
this.car = car;
|
||||
}
|
||||
|
||||
public Car getCar() {
|
||||
return car;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public interface Floatable {
|
||||
int duration = 10;
|
||||
void floatOnWater();
|
||||
|
||||
default void repair() {
|
||||
System.out.println("Repairing Floatable object");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public interface Flyable {
|
||||
int duration = 10;
|
||||
void fly();
|
||||
|
||||
/*
|
||||
* Commented
|
||||
*/
|
||||
//default void repair() {
|
||||
// System.out.println("Repairing Flyable object");
|
||||
//}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class SpaceCar extends Car implements SpaceTraveller {
|
||||
@Override
|
||||
public void floatOnWater() {
|
||||
System.out.println("SpaceCar floating!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fly() {
|
||||
System.out.println("SpaceCar flying!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remoteControl() {
|
||||
System.out.println("SpaceCar being controlled remotely!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public interface SpaceTraveller extends Floatable, Flyable {
|
||||
int duration = 10;
|
||||
void remoteControl();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.interfaces;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class CommaSeparatedCustomers implements Customer.List {
|
||||
|
||||
private List<Customer> customers = new ArrayList<Customer>();
|
||||
|
||||
@Override
|
||||
public void Add(Customer customer) {
|
||||
customers.add(customer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCustomerNames() {
|
||||
return customers.stream().map(customer -> customer.getName()).collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.interfaces;
|
||||
|
||||
public class Customer {
|
||||
public interface List {
|
||||
void Add(Customer customer);
|
||||
|
||||
String getCustomerNames();
|
||||
}
|
||||
|
||||
private String name;
|
||||
|
||||
public Customer(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.methodoverloadingoverriding.application;
|
||||
|
||||
import com.baeldung.methodoverloadingoverriding.model.Car;
|
||||
import com.baeldung.methodoverloadingoverriding.model.Vehicle;
|
||||
import com.baeldung.methodoverloadingoverriding.util.Multiplier;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Multiplier multiplier = new Multiplier();
|
||||
System.out.println(multiplier.multiply(10, 10));
|
||||
System.out.println(multiplier.multiply(10, 10, 10));
|
||||
System.out.println(multiplier.multiply(10, 10.5));
|
||||
System.out.println(multiplier.multiply(10.5, 10.5));
|
||||
|
||||
Vehicle vehicle = new Vehicle();
|
||||
System.out.println(vehicle.accelerate(100));
|
||||
System.out.println(vehicle.run());
|
||||
System.out.println(vehicle.stop());
|
||||
|
||||
Vehicle car = new Car();
|
||||
System.out.println(car.accelerate(80));
|
||||
System.out.println(car.run());
|
||||
System.out.println(car.stop());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.methodoverloadingoverriding.model;
|
||||
|
||||
public class Car extends Vehicle {
|
||||
|
||||
@Override
|
||||
public String accelerate(long mph) {
|
||||
return "The car accelerates at : " + mph + " MPH.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.methodoverloadingoverriding.model;
|
||||
|
||||
public class Vehicle {
|
||||
|
||||
public String accelerate(long mph) {
|
||||
return "The vehicle accelerates at : " + mph + " MPH.";
|
||||
}
|
||||
|
||||
public String stop() {
|
||||
return "The vehicle has stopped.";
|
||||
}
|
||||
|
||||
public String run() {
|
||||
return "The vehicle is running.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.methodoverloadingoverriding.util;
|
||||
|
||||
public class Multiplier {
|
||||
|
||||
public int multiply(int a, int b) {
|
||||
return a * b;
|
||||
}
|
||||
|
||||
public int multiply(int a, int b, int c) {
|
||||
return a * b * c;
|
||||
}
|
||||
|
||||
public double multiply(double a, double b) {
|
||||
return a * b;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.polymorphism;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class FileManager {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(FileManager.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
GenericFile file1 = new TextFile("SampleTextFile", "This is a sample text content", "v1.0.0");
|
||||
logger.info("File Info: \n" + file1.getFileInfo() + "\n");
|
||||
ImageFile imageFile = new ImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString()
|
||||
.getBytes(), "v1.0.0");
|
||||
logger.info("File Info: \n" + imageFile.getFileInfo());
|
||||
}
|
||||
|
||||
public static ImageFile createImageFile(String name, int height, int width, byte[] content, String version) {
|
||||
ImageFile imageFile = new ImageFile(name, height, width, content, version);
|
||||
logger.info("File 2 Info: \n" + imageFile.getFileInfo());
|
||||
return imageFile;
|
||||
}
|
||||
|
||||
public static GenericFile createTextFile(String name, String content, String version) {
|
||||
GenericFile file1 = new TextFile(name, content, version);
|
||||
logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n");
|
||||
return file1;
|
||||
}
|
||||
|
||||
public static TextFile createTextFile2(String name, String content, String version) {
|
||||
TextFile file1 = new TextFile(name, content, version);
|
||||
logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n");
|
||||
return file1;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.polymorphism;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class GenericFile {
|
||||
private String name;
|
||||
private String extension;
|
||||
private Date dateCreated;
|
||||
private String version;
|
||||
private byte[] content;
|
||||
|
||||
public GenericFile() {
|
||||
this.setDateCreated(new Date());
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getExtension() {
|
||||
return extension;
|
||||
}
|
||||
|
||||
public void setExtension(String extension) {
|
||||
this.extension = extension;
|
||||
}
|
||||
|
||||
public Date getDateCreated() {
|
||||
return dateCreated;
|
||||
}
|
||||
|
||||
public void setDateCreated(Date dateCreated) {
|
||||
this.dateCreated = dateCreated;
|
||||
}
|
||||
|
||||
public String getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public void setVersion(String version) {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
public byte[] getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(byte[] content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return "Generic File Impl";
|
||||
}
|
||||
|
||||
public Object read() {
|
||||
return content;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.polymorphism;
|
||||
|
||||
public class ImageFile extends GenericFile {
|
||||
private int height;
|
||||
private int width;
|
||||
|
||||
public ImageFile(String name, int height, int width, byte[] content, String version) {
|
||||
this.setHeight(height);
|
||||
this.setWidth(width);
|
||||
this.setContent(content);
|
||||
this.setName(name);
|
||||
this.setVersion(version);
|
||||
this.setExtension(".jpg");
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
public void setHeight(int height) {
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public void setWidth(int width) {
|
||||
this.width = width;
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return "Image File Impl";
|
||||
}
|
||||
|
||||
public String read() {
|
||||
return this.getContent()
|
||||
.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.polymorphism;
|
||||
|
||||
public class TextFile extends GenericFile {
|
||||
private int wordCount;
|
||||
|
||||
public TextFile(String name, String content, String version) {
|
||||
String[] words = content.split(" ");
|
||||
this.setWordCount(words.length > 0 ? words.length : 1);
|
||||
this.setContent(content.getBytes());
|
||||
this.setName(name);
|
||||
this.setVersion(version);
|
||||
this.setExtension(".txt");
|
||||
}
|
||||
|
||||
public int getWordCount() {
|
||||
return wordCount;
|
||||
}
|
||||
|
||||
public void setWordCount(int wordCount) {
|
||||
this.wordCount = wordCount;
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return "Text File Impl";
|
||||
}
|
||||
|
||||
public String read() {
|
||||
return this.getContent()
|
||||
.toString();
|
||||
}
|
||||
|
||||
public String read(int limit) {
|
||||
return this.getContent()
|
||||
.toString()
|
||||
.substring(0, limit);
|
||||
}
|
||||
|
||||
public String read(int start, int stop) {
|
||||
return this.getContent()
|
||||
.toString()
|
||||
.substring(start, stop);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.recursion;
|
||||
|
||||
public class BinaryNode {
|
||||
int value;
|
||||
BinaryNode left;
|
||||
BinaryNode right;
|
||||
|
||||
public BinaryNode(int value){
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
public void setValue(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
public BinaryNode getLeft() {
|
||||
return left;
|
||||
}
|
||||
public void setLeft(BinaryNode left) {
|
||||
this.left = left;
|
||||
}
|
||||
public BinaryNode getRight() {
|
||||
return right;
|
||||
}
|
||||
public void setRight(BinaryNode right) {
|
||||
this.right = right;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.recursion;
|
||||
|
||||
public class RecursionExample {
|
||||
|
||||
public int sum(int n){
|
||||
if (n >= 1){
|
||||
return sum(n - 1) + n;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
public int tailSum(int currentSum, int n){
|
||||
if (n <= 1) {
|
||||
return currentSum + n;
|
||||
}
|
||||
return tailSum(currentSum + n, n - 1);
|
||||
}
|
||||
|
||||
public int iterativeSum(int n){
|
||||
int sum = 0;
|
||||
if(n < 0){
|
||||
return -1;
|
||||
}
|
||||
for(int i=0; i<=n; i++){
|
||||
sum += i;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
public int powerOf10(int n){
|
||||
if (n == 0){
|
||||
return 1;
|
||||
}
|
||||
return powerOf10(n-1)*10;
|
||||
}
|
||||
|
||||
public int fibonacci(int n){
|
||||
if (n <=1 ){
|
||||
return n;
|
||||
}
|
||||
return fibonacci(n-1) + fibonacci(n-2);
|
||||
}
|
||||
|
||||
public String toBinary(int n){
|
||||
if (n <= 1 ){
|
||||
return String.valueOf(n);
|
||||
}
|
||||
return toBinary(n / 2) + String.valueOf(n % 2);
|
||||
}
|
||||
|
||||
public int calculateTreeHeight(BinaryNode root){
|
||||
if (root!= null){
|
||||
if (root.getLeft() != null || root.getRight() != null){
|
||||
return 1 + max(calculateTreeHeight(root.left) , calculateTreeHeight(root.right));
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int max(int a,int b){
|
||||
return a>b ? a:b;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class CastingUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenPrimitiveConverted_thenValueChanged() {
|
||||
double myDouble = 1.1;
|
||||
int myInt = (int) myDouble;
|
||||
|
||||
assertNotEquals(myDouble, myInt);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpcast_thenInstanceUnchanged() {
|
||||
Cat cat = new Cat();
|
||||
Animal animal = cat;
|
||||
animal = (Animal) cat;
|
||||
assertTrue(animal instanceof Cat);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpcastToObject_thenInstanceUnchanged() {
|
||||
Object object = new Animal();
|
||||
assertTrue(object instanceof Animal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpcastToInterface_thenInstanceUnchanged() {
|
||||
Mew mew = new Cat();
|
||||
assertTrue(mew instanceof Cat);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpcastToAnimal_thenOverridenMethodsCalled() {
|
||||
List<Animal> animals = new ArrayList<>();
|
||||
animals.add(new Cat());
|
||||
animals.add(new Dog());
|
||||
new AnimalFeeder().feed(animals);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDowncastToCat_thenMeowIsCalled() {
|
||||
Animal animal = new Cat();
|
||||
((Cat) animal).meow();
|
||||
}
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void whenDownCastWithoutCheck_thenExceptionThrown() {
|
||||
List<Animal> animals = new ArrayList<>();
|
||||
animals.add(new Cat());
|
||||
animals.add(new Dog());
|
||||
new AnimalFeeder().uncheckedFeed(animals);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDowncastToCatWithCastMethod_thenMeowIsCalled() {
|
||||
Animal animal = new Cat();
|
||||
if (Cat.class.isInstance(animal)) {
|
||||
Cat cat = Cat.class.cast(animal);
|
||||
cat.meow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParameterCat_thenOnlyCatsFed() {
|
||||
List<Animal> animals = new ArrayList<>();
|
||||
animals.add(new Cat());
|
||||
animals.add(new Dog());
|
||||
AnimalFeederGeneric<Cat> catFeeder = new AnimalFeederGeneric<Cat>(Cat.class);
|
||||
List<Cat> fedAnimals = catFeeder.feed(animals);
|
||||
|
||||
assertTrue(fedAnimals.size() == 1);
|
||||
assertTrue(fedAnimals.get(0) instanceof Cat);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.commons.lang.SerializationUtils;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
public class DeepCopyUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCreatingDeepCopyWithCopyConstructor_thenObjectsShouldNotBeSame() {
|
||||
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
|
||||
User deepCopy = new User(pm);
|
||||
|
||||
assertThat(deepCopy).isNotSameAs(pm);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenConstructorCopyShouldNotChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
User deepCopy = new User(pm);
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenCloneCopyShouldNotChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
User deepCopy = (User) pm.clone();
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenCommonsCloneShouldNotChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
User deepCopy = (User) SerializationUtils.clone(pm);
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenGsonCloneShouldNotChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
Gson gson = new Gson();
|
||||
User deepCopy = gson.fromJson(gson.toJson(pm), User.class);
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenJacksonCopyShouldNotChange() throws IOException {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
User deepCopy = objectMapper.readValue(objectMapper.writeValueAsString(pm), User.class);
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void whenMakingCopies_thenShowHowLongEachMethodTakes() throws CloneNotSupportedException, IOException {
|
||||
int times = 1000000;
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
|
||||
long start = System.currentTimeMillis();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = (User) SerializationUtils.clone(pm);
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with Apache Commons Lang took " + (end - start) + " milliseconds.");
|
||||
|
||||
start = System.currentTimeMillis();
|
||||
Gson gson = new Gson();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = gson.fromJson(gson.toJson(pm), User.class);
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with Gson took " + (end - start) + " milliseconds.");
|
||||
|
||||
start = System.currentTimeMillis();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = new User(pm);
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with the copy constructor took " + (end - start) + " milliseconds.");
|
||||
|
||||
start = System.currentTimeMillis();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = (User) pm.clone();
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with Cloneable interface took " + (end - start) + " milliseconds.");
|
||||
|
||||
start = System.currentTimeMillis();
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = objectMapper.readValue(objectMapper.writeValueAsString(pm), User.class);
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with Jackson took " + (end - start) + " milliseconds.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ShallowCopyUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void whenShallowCopying_thenObjectsShouldNotBeSame() {
|
||||
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
|
||||
User shallowCopy = new User(pm.getFirstName(), pm.getLastName(), pm.getAddress());
|
||||
|
||||
assertThat(shallowCopy)
|
||||
.isNotSameAs(pm);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenCopyShouldChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
User shallowCopy = new User(pm.getFirstName(), pm.getLastName(), pm.getAddress());
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(shallowCopy.getAddress().getCountry())
|
||||
.isEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.enums;
|
||||
|
||||
import com.baeldung.enums.Pizza.PizzaStatusEnum;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
|
||||
public class PizzaUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenPizaOrder_whenReady_thenDeliverable() {
|
||||
Pizza testPz = new Pizza();
|
||||
testPz.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
assertTrue(testPz.isDeliverable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
|
||||
List<Pizza> pzList = new ArrayList<>();
|
||||
Pizza pz1 = new Pizza();
|
||||
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
|
||||
|
||||
Pizza pz2 = new Pizza();
|
||||
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz3 = new Pizza();
|
||||
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz4 = new Pizza();
|
||||
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
|
||||
pzList.add(pz1);
|
||||
pzList.add(pz2);
|
||||
pzList.add(pz3);
|
||||
pzList.add(pz4);
|
||||
|
||||
List<Pizza> undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
|
||||
assertTrue(undeliveredPzs.size() == 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
|
||||
|
||||
List<Pizza> pzList = new ArrayList<>();
|
||||
Pizza pz1 = new Pizza();
|
||||
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
|
||||
|
||||
Pizza pz2 = new Pizza();
|
||||
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz3 = new Pizza();
|
||||
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
|
||||
|
||||
Pizza pz4 = new Pizza();
|
||||
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
|
||||
pzList.add(pz1);
|
||||
pzList.add(pz2);
|
||||
pzList.add(pz3);
|
||||
pzList.add(pz4);
|
||||
|
||||
EnumMap<Pizza.PizzaStatusEnum, List<Pizza>> map = Pizza.groupPizzaByStatus(pzList);
|
||||
assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
|
||||
assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
|
||||
assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
|
||||
Pizza pz = new Pizza();
|
||||
pz.setStatus(Pizza.PizzaStatusEnum.READY);
|
||||
pz.deliver();
|
||||
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.finalize;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FinalizeUnitTest {
|
||||
@Test
|
||||
public void whenGC_thenFinalizerExecuted() throws IOException {
|
||||
String firstLine = new Finalizable().readFirstLine();
|
||||
Assert.assertEquals("baeldung.com", firstLine);
|
||||
System.gc();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTryWResourcesExits_thenResourceClosed() throws IOException {
|
||||
try (CloseableResource resource = new CloseableResource()) {
|
||||
String firstLine = resource.readFirstLine();
|
||||
Assert.assertEquals("baeldung.com", firstLine);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class FinalUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenChangedFinalClassProperties_thenChanged() {
|
||||
Cat cat = new Cat();
|
||||
cat.setWeight(1);
|
||||
|
||||
assertEquals(1, cat.getWeight());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFinalVariableAssign_thenOnlyOnce() {
|
||||
final int i;
|
||||
i = 1;
|
||||
// i=2;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenChangedFinalReference_thenChanged() {
|
||||
|
||||
final Cat cat = new Cat();
|
||||
// cat=new Cat();
|
||||
cat.setWeight(5);
|
||||
|
||||
assertEquals(5, cat.getWeight());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
import com.baeldung.inheritance.*;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
public class AppUnitTest extends TestCase {
|
||||
|
||||
public AppUnitTest(String testName) {
|
||||
super( testName );
|
||||
}
|
||||
|
||||
public static Test suite() {
|
||||
return new TestSuite(AppUnitTest.class);
|
||||
}
|
||||
|
||||
@SuppressWarnings("static-access")
|
||||
public void testStaticMethodUsingBaseClassVariable() {
|
||||
Car first = new ArmoredCar();
|
||||
assertEquals("Car", first.msg());
|
||||
}
|
||||
|
||||
@SuppressWarnings("static-access")
|
||||
public void testStaticMethodUsingDerivedClassVariable() {
|
||||
ArmoredCar second = new ArmoredCar();
|
||||
assertEquals("ArmoredCar", second.msg());
|
||||
}
|
||||
|
||||
public void testAssignArmoredCarToCar() {
|
||||
Employee e1 = new Employee("Shreya", new ArmoredCar());
|
||||
assertNotNull(e1.getCar());
|
||||
}
|
||||
|
||||
public void testAssignSpaceCarToCar() {
|
||||
Employee e2 = new Employee("Paul", new SpaceCar());
|
||||
assertNotNull(e2.getCar());
|
||||
}
|
||||
|
||||
public void testBMWToCar() {
|
||||
Employee e3 = new Employee("Pavni", new BMW());
|
||||
assertNotNull(e3.getCar());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.interfaces;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class InnerInterfaceUnitTest {
|
||||
@Test
|
||||
public void whenCustomerListJoined_thenReturnsJoinedNames() {
|
||||
Customer.List customerList = new CommaSeparatedCustomers();
|
||||
customerList.Add(new Customer("customer1"));
|
||||
customerList.Add(new Customer("customer2"));
|
||||
assertEquals("customer1,customer2", customerList.getCustomerNames());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.methodoverloadingoverriding.test;
|
||||
|
||||
import com.baeldung.methodoverloadingoverriding.util.Multiplier;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class MethodOverloadingUnitTest {
|
||||
|
||||
private static Multiplier multiplier;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpMultiplierInstance() {
|
||||
multiplier = new Multiplier();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiplierInstance_whenCalledMultiplyWithTwoIntegers_thenOneAssertion() {
|
||||
assertThat(multiplier.multiply(10, 10)).isEqualTo(100);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiplierInstance_whenCalledMultiplyWithTreeIntegers_thenOneAssertion() {
|
||||
assertThat(multiplier.multiply(10, 10, 10)).isEqualTo(1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiplierInstance_whenCalledMultiplyWithIntDouble_thenOneAssertion() {
|
||||
assertThat(multiplier.multiply(10, 10.5)).isEqualTo(105.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiplierInstance_whenCalledMultiplyWithDoubleDouble_thenOneAssertion() {
|
||||
assertThat(multiplier.multiply(10.5, 10.5)).isEqualTo(110.25);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiplierInstance_whenCalledMultiplyWithIntIntAndMatching_thenNoTypePromotion() {
|
||||
assertThat(multiplier.multiply(10, 10)).isEqualTo(100);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.methodoverloadingoverriding.test;
|
||||
|
||||
import com.baeldung.methodoverloadingoverriding.model.Car;
|
||||
import com.baeldung.methodoverloadingoverriding.model.Vehicle;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class MethodOverridingUnitTest {
|
||||
|
||||
private static Vehicle vehicle;
|
||||
private static Car car;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpVehicleInstance() {
|
||||
vehicle = new Vehicle();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpCarInstance() {
|
||||
car = new Car();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVehicleInstance_whenCalledAccelerate_thenOneAssertion() {
|
||||
assertThat(vehicle.accelerate(100)).isEqualTo("The vehicle accelerates at : 100 MPH.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVehicleInstance_whenCalledRun_thenOneAssertion() {
|
||||
assertThat(vehicle.run()).isEqualTo("The vehicle is running.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVehicleInstance_whenCalledStop_thenOneAssertion() {
|
||||
assertThat(vehicle.stop()).isEqualTo("The vehicle has stopped.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCarInstance_whenCalledAccelerate_thenOneAssertion() {
|
||||
assertThat(car.accelerate(80)).isEqualTo("The car accelerates at : 80 MPH.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCarInstance_whenCalledRun_thenOneAssertion() {
|
||||
assertThat(car.run()).isEqualTo("The vehicle is running.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCarInstance_whenCalledStop_thenOneAssertion() {
|
||||
assertThat(car.stop()).isEqualTo("The vehicle has stopped.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVehicleCarInstances_whenCalledAccelerateWithSameArgument_thenNotEqual() {
|
||||
assertThat(vehicle.accelerate(100)).isNotEqualTo(car.accelerate(100));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVehicleCarInstances_whenCalledRun_thenEqual() {
|
||||
assertThat(vehicle.run()).isEqualTo(car.run());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenVehicleCarInstances_whenCalledStop_thenEqual() {
|
||||
assertThat(vehicle.stop()).isEqualTo(car.stop());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.polymorphism;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import org.junit.Test;
|
||||
|
||||
public class PolymorphismUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenImageFile_whenFileCreated_shouldSucceed() {
|
||||
ImageFile imageFile = FileManager.createImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString()
|
||||
.getBytes(), "v1.0.0");
|
||||
assertEquals(200, imageFile.getHeight());
|
||||
}
|
||||
|
||||
// Downcasting then Upcasting
|
||||
@Test
|
||||
public void givenTextFile_whenTextFileCreatedAndAssignedToGenericFileAndCastBackToTextFileOnGetWordCount_shouldSucceed() {
|
||||
GenericFile textFile = FileManager.createTextFile("SampleTextFile", "This is a sample text content", "v1.0.0");
|
||||
TextFile textFile2 = (TextFile) textFile;
|
||||
assertEquals(6, textFile2.getWordCount());
|
||||
}
|
||||
|
||||
// Downcasting
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void givenGenericFile_whenCastToTextFileAndInvokeGetWordCount_shouldFail() {
|
||||
GenericFile genericFile = new GenericFile();
|
||||
TextFile textFile = (TextFile) genericFile;
|
||||
System.out.println(textFile.getWordCount());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.recursion;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class RecursionExampleUnitTest {
|
||||
|
||||
RecursionExample recursion = new RecursionExample();
|
||||
|
||||
@Test
|
||||
public void testPowerOf10() {
|
||||
int p0 = recursion.powerOf10(0);
|
||||
int p1 = recursion.powerOf10(1);
|
||||
int p4 = recursion.powerOf10(4);
|
||||
|
||||
Assert.assertEquals(1, p0);
|
||||
Assert.assertEquals(10, p1);
|
||||
Assert.assertEquals(10000, p4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFibonacci() {
|
||||
int n0 = recursion.fibonacci(0);
|
||||
int n1 = recursion.fibonacci(1);
|
||||
int n7 = recursion.fibonacci(7);
|
||||
|
||||
Assert.assertEquals(0, n0);
|
||||
Assert.assertEquals(1, n1);
|
||||
Assert.assertEquals(13, n7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToBinary() {
|
||||
String b0 = recursion.toBinary(0);
|
||||
String b1 = recursion.toBinary(1);
|
||||
String b10 = recursion.toBinary(10);
|
||||
|
||||
Assert.assertEquals("0", b0);
|
||||
Assert.assertEquals("1", b1);
|
||||
Assert.assertEquals("1010", b10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCalculateTreeHeight() {
|
||||
BinaryNode root = new BinaryNode(1);
|
||||
root.setLeft(new BinaryNode(1));
|
||||
root.setRight(new BinaryNode(1));
|
||||
|
||||
root.getLeft().setLeft(new BinaryNode(1));
|
||||
root.getLeft().getLeft().setRight(new BinaryNode(1));
|
||||
root.getLeft().getLeft().getRight().setLeft(new BinaryNode(1));
|
||||
|
||||
root.getRight().setLeft(new BinaryNode(1));
|
||||
root.getRight().getLeft().setRight(new BinaryNode(1));
|
||||
|
||||
int height = recursion.calculateTreeHeight(root);
|
||||
|
||||
Assert.assertEquals(4, height);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user