Home  >  Article  >  Java  >  Java Learning Journey

Java Learning Journey

Susan Sarandon
Susan SarandonOriginal
2024-10-19 18:20:02440browse

Java Learning Journey

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, 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:

  • no 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

Definition: The Comparable 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:

public String[] split(String regex, int limit)
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

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:

public String trim()
public class Main{
    public static void main(String args[]){
        String str = "   You can do it!   ";
        System.out.println(str);
        System.out.println(str.trim());
    }
}
   You can do it!   
You can do it!
public static boolean isDigit(char ch)

Output:

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");
            }
        }

    }
}

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

The above is the detailed content of Java Learning Journey. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Nested try blocksNext article:Nested try blocks