//This will hold the target leaf certificate.
Optional<Certificate> cert;

try {
    //Must hold the target URL.
    final var targetUrl = "https://www.google.com";
    final var httpsURL = new URL(targetUrl);
    final var connection = (HttpsURLConnection) httpsURL.openConnection();
    connection.connect();

    //Retrieve the first certificate. This is normally the leaf certificate.
    cert = Arrays.stream(connection.getServerCertificates()).findFirst();
} catch (IOException e) {
    throw new RuntimeException(e);
}

cert.ifPresent(cer -> {
    //Check if the instance of certificate is of type of X509Certificate.
    if(cer instanceof final X509Certificate x509) {
        System.out.println("Subject: " + x509.getSubjectX500Principal().getName());
        System.out.println("From: " + x509.getNotBefore());
        System.out.println("To: " + x509.getNotAfter());
        System.out.println("Duration: " + ChronoUnit.DAYS.between(LocalDate.now(), LocalDate.ofInstant(x509.getNotAfter().toInstant(),ZoneId.systemDefault())));
        System.out.println("\n");
    }
});