I recently learned Java through the practices in [https://exercism.org/tracks/java/exercises]. My current progress is 13 out of a total of 148 practices. I would like to share what I learned.
This post introduce my understanding about .split(), .trim(), .isDigit(), .isLetter(), Comparable<T>, User-defined Java Exceptions, and Interface.
1) .split()
Definition: The .split()
method divides String into an array based on the separator [1].
Syntax:
public String[] split(String regex, int limit)
Parameter:
- regex: (required field) pattern of separator
- limit: (optional field) maximum length of the returned array
Example:
public class Main{
public void getProductPrice(String products){
double totalPrice = 0.0;
StringBuilder priceDetails = new StringBuilder();
String[] singleProduct = products.split("; ");
for(int i = 0; i < singleProduct.length; i++){
String[] productInfo = singleProduct[i].split(", ");
totalPrice += Double.parseDouble(productInfo[2]);
priceDetails.append(productInfo[2]);
if(i < singleProduct.length - 1){
priceDetails.append(" + ");
}
}
System.out.println(priceDetails + " = " + totalPrice);
}
public static void main(String arg[]){
Main obj = new Main();
obj.getProductPrice("1, dragonfruit, 12.50; 2, guava, 23.45; 3, avocado, 395.67");
}
}
Output:
12.50 + 23.45 + 395.67 = 431.62
2) .trim()
Definition: The .trim()
method removes whitespace from both ends of a string [2].
Syntax:
public String trim()
Parameter:
Example:
public class Main{
public static void main(String args[]){
String str = " You can do it! ";
System.out.println(str);
System.out.println(str.trim());
}
}
Output:
You can do it!
You can do it!
3) .isDigit()
Definition: The .isDigit()
method determines whether a character is digit or not [3].
Syntax:
public static boolean isDigit(char ch)
Parameter:
- ch: (required field) the character value to be tested
Example:
public class Main{
// return true when the given parameter has a digit
public boolean searchDigit(String str){
for(int i = 0; i < str.length(); i++){
// charAt() method returns the character at the specified index in a string
if(Character.isDigit(str.charAt(i))){
return true;
}
}
return false;
}
// print digit index and value
public void digitInfo(String str){
for(int i = 0; i < str.length(); i++){
if(Character.isDigit(str.charAt(i))){
System.out.println("Digit: " + str.charAt(i) + " found at index " + i);
}
}
}
public static void main(String args[]){
Main obj = new Main();
String[] strList = {"RT7J", "1EOW", "WBJK"};
for(String str : strList){
if(obj.searchDigit(str)){
obj.digitInfo(str);
}else{
System.out.println("No digit");
}
}
}
}
Output:
Digit: 7 found at index 2
Digit: 1 found at index 0
No digit
4) .isLetter()
Definition: The .isLetter()
method determines whether a character is letter or not [4].
Syntax:
public static boolean isLetter(char ch)
Parameter:
- ch: (required field) the character value to be tested
Example:
public class Main{
// check whether phoneNum has letter
public void searchLetter(String phoneNum){
boolean hasLetter = false;
for(int i = 0; i < phoneNum.length(); i++){
if(Character.isLetter(phoneNum.charAt(i))){
hasLetter = true;
// return letter value and index
System.out.println(phoneNum + " has letter '" + phoneNum.charAt(i) + "' at index " + i);
}
}
// phone number is valid when no letter
if(!hasLetter){
System.out.println(phoneNum + " is valid");
}
System.out.println();
}
public static void main(String args[]){
Main obj = new Main();
String[] phoneNum = {"A0178967547", "0126H54786K5", "0165643484"};
for(String item: phoneNum){
obj.searchLetter(item);
}
}
}
Output:
A0178967547 has letter 'A' at index 0
0126H54786K5 has letter 'H' at index 4
0126H54786K5 has letter 'K' at index 10
0165643484 is valid
5) Comparable<T>
Definition: The Comparable<T>
interface is used to define a natural ordering for a collection of objects, and it should be implemented in the class of the objects being compared [5]. The type parameter T
represents the type of objects that can be compared.
Example:
// file: Employee.java
public class Employee implements Comparable<Employee>{
private String email;
private String name;
private int age;
public Employee(String email, String name, int age){
this.email = email;
this.name = name;
this.age = age;
}
// The Comparable interface has a method called compareTo(T obj).
// This method helps decide how to order objects, so they can be sorted in a list
@Override
public int compareTo(Employee emp){
// compare age:
// return this.age - emp.age;
// (this.age - emp.age) = negative value means this.age before emp.age;
// (this.age - emp.age) = positive means this.age after emp.age
// compare email:
return this.email.compareTo(emp.email);
}
@Override
public String toString(){
return "[email=" + this.email + ", name=" + this.name + ", age=" + this.age +"]";
}
}
// file: Main.java
import java.util.Arrays;
public class Main {
public static void main(String args[]){
Employee[] empInfo = new Employee[3];
empInfo[0] = new Employee("joseph@gmail.com", "Joseph", 27);
empInfo[1] = new Employee("alicia@gmail.com", "Alicia", 30);
empInfo[2] = new Employee("john@gmail.com", "John", 24);
Arrays.sort(empInfo);
System.out.println("After sorting:n" + Arrays.toString(empInfo));
}
}
Output:
After sorting:
[[email=alicia@gmail.com, name=Alicia, age=30], [email=john@gmail.com, name=John, age=24], [email=joseph@gmail.com, name=Joseph, age=27]]
6) User-defined Java Exceptions
Definition: User-defined Java Exception is a custom exception that a developer creates for handling specific error conditions [6].
Example:
// file: InsufficientFundsException.java
public class InsufficientFundsException extends RuntimeException {
public InsufficientFundsException(String message){
super(message);
}
}
// file: Main.java
public class Main{
private static double currentSaving = 1000.0;
public static String bankAccount(double withdrawMoney){
if(withdrawMoney > currentSaving){
// user-defined exception
throw new InsufficientFundsException("Insufficient balance");
}
return "Withdraw success, remaining balance RM " + (currentSaving - withdrawMoney);
}
public static void main(String args[]){
try{
System.out.println(bankAccount(1500.0));
} catch (InsufficientFundsException e){
System.out.println(e.getMessage());
}
}
}
Output:
Insufficient balance
7) Interface
Interfaces in Java allow users to invoke the same method across various classes, each implementing its own logic [7]. In the example below, the method calculatePrice()
is called in different classes, such as Fruit
and DiscountFruit
, with each class applying its own unique calculation logic.
Example:
// file: FruitPrice.java
interface FruitPrice{
void calculatePrice(int quantity);
}
// file: Fruit.java
public class Fruit implements FruitPrice{
private String fruit;
private double price;
public Fruit(String fruit, double price){
this.fruit = fruit;
this.price = price;
}
@Override
public void calculatePrice(int quantity){
System.out.println("Total price for " + quantity + " " + fruit + " is RM " + price*quantity);
}
}
// file: DiscountFruit.java
public class DiscountFruit implements FruitPrice{
private String fruit;
private double price;
private int percentage;
public DiscountFruit(String fruit, double price, int percentage){
this.fruit = fruit;
this.price = price;
this.percentage = percentage;
}
@Override
public void calculatePrice(int quantity){
double total = price * quantity * ((100.0-percentage)/100.0);
System.out.println("After " + percentage + "% discount, the price for " + quantity + " " + fruit + " is RM " + total);
}
}
// file: Main.java
public class Main{
public static void main(String args[]){
Fruit apple = new Fruit("apple", 2.0);
apple.calculatePrice(5);
DiscountFruit orange = new DiscountFruit("orange", 2, 10);
orange.calculatePrice(5);
}
}
Output:
Total price for 5 apple is RM 10.0
After 10% discount, the price for 5 orange is RM 9.0
Reference
[1] JavaRush, split method in java: split string into parts, 8 August 2023
[2] W3Schools, Java String trim() Method
[3] GeeksforGeeks, Character isDigit() method in Java with examples, 17 May, 2020
[4] tutorialspoint, Java – Character isLetter() method
[5] DigitalOcean, Comparable and Comparator in Java Example, August 4, 2022
[6] Shiksha, Understanding User Defined Exception in Java, Apr 25, 2024
[7] Scientech Easy, Use of Interface in Java with Example, July 9, 2024
Source link
lol