7. Additional Java SE Classes

About this Tutorial –

Objectives –

This course is aimed at object-oriented developers (e.g. C++ or C#) who need to transition into Java. It is also aimed at those learning to program for the first time; the course covers the Java programming constructs and APIs quickly, focussing on the differences between Java and other OO languages.

Audience

This training course is aimed at OO developers who need to transition into Java.

Prerequisites

No previous experience in Java programming is required. But any experience you do have in programming will help. Also no experience in eclipse is required. But again any experience you do have with programming development environments will be a valuable.

Contents

The Java course cover these topics and more:

  • Flow Control: Decision making: if and if-else; The switch statement; Looping: for loops; while loops; do-while loops; for-each style loops; Assertionsv
  • Concurrency: Overview of multithreading; Creating new threads; Object locking; Using wait, notify, and notifyAll
  • Collections: Overview of Java SE collection classes; Generics; Using List-based collection classes; Using Set-based collection classes; Using Map-based collection classes; Collection techniques

Exam Preparation

The Java course will help you prepare for these certifications:

  • Oracle Certified Java Associate – Exam 1Z0-803
  • Oracle Certified Java Professional – Exam 1Z0-804

Download Solutions

HTML tutorial


Overview

Estimated Time – 1.5 Hours

Not what you are looking? Try the next tutorial – Inheritance

Lab 1: The Console class

Lab 1: The Console class
  1. Overview of the Console Class
    • Java 1.6 introduces the java.io.Console class
      • Provides methods to access the character-based console device (if any) associated with the current JVM
      • Provides simplified access to keyboard/screen (unless I/O has been redirected)
    • To get the (singleton) Console instance for the JVM:
      import java.io.*;
      ...
      Console console = System.console();
      if (console != null) {
       ...
      }
  2. Console Functionality
    • Useful methods in the Console class:
      • printf() – print formatted string (also format())
      • writer() – get a PrintWriter for the Console
      • flush() – force buffered content to be written now
      • reader() – get a Reader for the Console
      • readLine() – read a string (with optional prompt)
      • readPassword() – read a password (with optional prompt)
  3. Using Console
    • Example
      Console console = System.console();
      if (console != null) {
        console.printf("Hello at %s. Please tell me your name: ", new Date());
        String name = console.readLine();
        String nat = console.readLine("Thanks %s, now tell me your nationality: ", name);
        char[] pwChars = console.readPassword("Great %s, you're %s! Password? ", name, nat);
        String password = new String(pwChars);
        console.printf("Thanks. Your password is: %s", password);
      } else {
        System.out.println("Sorry, console unavailable.");
      }
    • T7P1

Lab 2: The StringBuilder class

Lab 2: The StringBuilder class
  1. Overview of StringBuilder Class
    • String objects are immutable
      • Once you’ve created a String object, you can’t modify it
      • This enables the JVM to optimize memory usage
      • But it can impair performance if you do a lot of string handling
    • StringBuilder (and StringBuffer) are mutable
      • Assigned an initial capacity (16 characters by default)
      • Allows you to change the text
      • Automatically resizes when necessary
    • StringBuilder vs. StringBuffer:
      • StringBuilder has the same API as StringBuffer
      • StringBuilder only available in Java 1.5 onwards
      • StringBuilder isn’t thread-safe, so faster than StringBuffer
      • Recommendation: Use StringBuilder where possible
  2. StringBuilder Functionality
    • Useful methods in the StringBuilder class:
      • constructor – optionally specify initial capacity or initial text
      • append() – append to text (various overloads)
      • delete() – delete text from start to end positions
      • insert() – insert at specified position (various overloads)
      • replace() – replace text from start to end positions
      • toString() – create immutable String from text
      • setCharAt() – set character at specific position
      • And More…
    • StringBuffer has the same methods
  3. Using StringBuilder
    • Example
      StringBuilder sb1 = new StringBuilder("Hello");
      sb1.append(" world");
      sb1.append('!');
      sb1.insert(5, " Andy and the rest of the");
      sb1.insert(10, 43);
      String str1 = sb1.toString();
      System.out.println(str1);
      StringBuilder sb2 = sb1;
      sb2.replace(6, 9, "Fred");
      sb2.reverse();
      String str2 = sb2.toString();
      System.out.println(str2);
    • T7P2

Lab
  1. Using the StringBuilder class
    • Open UsingStringBuilder.java, and write an application that explores the capabilities of the StringBuilder class
    • Suggestions and requirements:
      • Write a simple main() method that creates a StringBuilder object with an initial capacity of 50 characters (say), to give it some initial space to grow into
        StringBuilder sb1 = new StringBuilder(50);
      • Call append() on the StringBuilder object, to append some text
        sb1.append("");
        sb1.append("Johan");
        sb1.append("21");
        sb1.append("
        ");
        System.out.println(sb1);
      • View code file.
      • Call delete() to delete some of the text
        // Delete 21
        sb1.delete(25, 38);
        System.out.println(sb1);
      • View code file.
      • Call deleteCharAt() to delete a character at a specific position
        // Delete the o and the h in Johan
        sb1.deleteCharAt(15);
        sb1.deleteCharAt(15);
        System.out.println(sb1);
      • View code file.
      • Call insert() to insert new text at various positions
        // Insert new text
        sb1.insert(24, "UK");
        sb1.insert(24, "M");
        System.out.println(sb1);
      • View code file.
      • Call replace() to replace text at various positions
        // Replace some text
        sb1.replace(51, 53, "Wales");
        System.out.println(sb1);
      • View code file.
      • Call setCharAt() to set a character at a specific position
        // Set a specific character
        sb1.setCharAt(32, 'F');
        System.out.println(sb1);
      • View code file.
      • Finally, call toString() to create an immutable String from the text
        String finishedString = sb1.toString();
        System.out.println("\nFinished string: " + finishedString);
      • View code file.

Lab 3: Formatting techniques

Lab 3: Formatting techniques
  1. Overview of Formatting
    • Java 1.6 introduced extensive formatting capabilities:
    • java.util.Formatter class
      • Formats content in a string, stream, or file
      • Locale-sensitive
      • Extremely parameterized
    • String.format() method
      • Creates a formatted string
    • System.out.format() method
      • Outputs a formatted string
  2. Example of Using Formatter Class
    • This example shows some simple Formatter techniques
      private static void demoFormatter() {
        // Use a StringBuilder to accumulate output, using the UK locale.
        StringBuilder sb = new StringBuilder();
        Formatter formatter = new Formatter(sb, Locale.UK);
        // Simple output, with field-width specifiers.
        formatter.format("%2s %2s %2s %2s\n", "A", "B", "C", "D");
        // Reorder items, using explicit indices.
        formatter.format("%4$2s %3$2s %2$2s %1$2s\n", "A", "B", "C", "D");
        // Use different locale (One-off).
        formatter.format(Locale.FRANCE, "Here's a big number: %.4f\n", 123456789.1234567);
        // Output negative parameter in parentheses.
        formatter.format("Stocks and shares this week: %(,.2f\n", -6217.577);
        System.out.println(sb.toString());
      }
    • View code file.
    • T7P3

Lab
  1. Using formatting techniques
    • Open Formatting.java, and write some code to explore the formatting capabilities of the Formatter class and the String class
    • Suggestions and requirements:
      • First, take a look at the demo code that accompanies this chapter (see the DemoNewJavaSEClasses project, and the Formatting.java source file)
      • In your application, create a Formatter object, and use it to format strings using various format specifiers (see the demoFormatter() method in the demo code, and experiment with the options)
        Scanner scanner = new Scanner(System.in);
        System.out.println("Choose a locale [US|NO|FR|UK]: ");
        String loc = scanner.next().toUpperCase();
        Locale locale;
        if (loc.equals("US")) {
         locale = Locale.US;
        } else if (loc.equals("NO")) {
         locale = new Locale("NO");
        } else if (loc.equals("FR")) {
         locale = Locale.FRENCH;
        } else {
         locale = Locale.UK;
        }
        doStringFormatting(locale);
        doNumberFormatting(locale);
        doTimeFormatting(locale);
        doDateFormatting(locale);
        scanner.close();
      • View code file.
      • Use String.format() to achieve the same effect (see the demoStringFormat() method in the demo code)
        private static void doStringFormatting(Locale locale) {
         System.out.println("\nString formatting");
         System.out.printf("Normal strings:\n");
         System.out.printf(locale, "%s %s %s %s %s %s %s %n", "Sleepy", "Doc", "Happy", "Grumpy", "Sneezy", "Bashful", "Dopey");
         System.out.printf("\nStrings with specific ordering:\n");
         System.out.printf(locale, "%7$s %6$s %5$s %4$s %3$s %2$s %1$s %n", "Sleepy", "Doc", "Happy", "Grumpy", "Sneezy", "Bashful", "Dopey");
         System.out.printf("\nStrings with a width of 10:\n");
         System.out.printf(locale, "%10s %10s %10s %10s %10s %10s %10s %n", "Sleepy", "Doc", "Happy", "Grumpy", "Sneezy", "Bashful", "Dopey");
         System.out.printf("\nStrings with a width of 10, left-aligned:\n");
         System.out.printf(locale, "%-10s %-10s %-10s %-10s %-10s %-10s %-10s %n", "Sleepy", "Doc", "Happy", "Grumpy", "Sneezy", "Bashful", "Dopey");
        }
      • View code file.
      • Experiment with number formatting (see the demoNumberFormatting() method in the demo code)
        private static void doNumberFormatting(Locale locale) {
         System.out.println("\n\nNumber formatting");
         int num = 255;
         System.out.printf("255 in decimal, hex, HEX, and octal:\n");
         System.out.printf(locale, "%1$d %1$h %1$H %1$o \n", num);
         double pi = 3.14159;
         System.out.printf("\n3.14159 as is, to 2DP, to 4DP, and using exponential format:\n");
         System.out.printf(locale, "%1$f %1$.2f %1$.4f %e\n", pi);
        }
      • View code file.
      • Experiment with time formatting (see the demoTimeFormatting() method in the demo code)
        private static void doTimeFormatting(Locale locale) {
         System.out.println("\n\nTime formatting");
         Calendar calendar = Calendar.getInstance();
         System.out.printf("Complete d/t: %1$tc %n", calendar);
         System.out.printf(locale, "24-hr time: %1$tH/%1$tM/%1$tS    %n", calendar);
         System.out.printf(locale, "12-hr time: %1$tk/%1$tM/%1$tS %1$tp %n", calendar);
         System.out.printf(locale, "HH:MM (24):  %1$tR %n", calendar);
         System.out.printf(locale, "HH:MM:SS (24): %1$tT %n", calendar);
         System.out.printf(locale, "HH:MM:SS (12): %1$tr %n", calendar);
        }
      • View code file.
      • Experiment with date formatting (see the demoDateFormatting() method in the demo code)
        private static void doDateFormatting(Locale locale) {
         System.out.println("\n\nDate formatting");
         Calendar calendar = Calendar.getInstance();
         System.out.printf(locale, "Complete d/t: %1$tc %n", calendar);
         System.out.printf(locale, "Today is:   %1$tA %1$tB %1$tY %n", calendar);
         System.out.printf(locale, "Abbreviated: %1$ta %1$tb %1$ty %n", calendar);
         System.out.printf(locale, "MM/DD/YY:   %1$tD %n", calendar);
         System.out.printf(locale, "YYYY-MM-DD:  %1$tF %n", calendar);
        }
      • View code file.

Lab 4: Regular expressions

Lab 4: Regular expressions
  1. Basic Regular Expression Syntax
    • REs use literal characters and meta-characters – Use \ character to make meta-character into literal character
    • T7P4

  2. Support for Regular Expressions in Java
    • Support for REs in Java since Java 1.4
      • java.util.regex package
    • CharSequence interface
      • Encapsulates sequence of characters, implemented by String, StringBuilder, StringBuffer, CharBuffer
    • Pattern class
      • Encapsulates an RE (in “compiled form”)
    • Matcher class
      • Supports matching of Pattern objects against a CharSequence
    • MatchResult interface
      • Represents the result of a match operation
  3. Performing a One-Off Pattern Match
    • The Pattern class has a static matches() method
      • Allows you to perform a one-off pattern match, to see if a character sequence matches a regular expression
      • Just returns true or false
    • Example
      String charseq = "aaaab";
      boolean result = Pattern.matches("a*b", charseq);
    • View code file.
  4. Using Compiled Regular Expressions (1)
    • If you’re going to use an RE more than once, you should compile it into a Pattern object
      • Invoke Pattern.compile() to build a Pattern object
        Pattern p = Pattern.compile("a*b");
      • View code file.
    • To match an RE match on a character sequence:
      • Invoke matcher() on Pattern object, returns Matcher object
        Matcher m = p.matcher("aaaab");
      • View code file.
    • Matcher methods:
      • matches()
      • lookingAt()
      • find()
      • group()
    • Example
      private static void demoMatching(CharSequence source, String regex) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(source);
        // Call matches() to see if there's an exact match on the entire source.
        if (m.matches()) { ...
        // Call lookingAt() to see if there's a match from the start of the source.
        if (m.lookingAt()) { ...
        // Call find() to see if there's a match somewhere in the source. Note reset() call!
        m.reset();
        if (m.find()) { ...
      }
    • View code file.
    • The find() method continues searching from the end of the previous match
      • Makes repeated matches easy
      • Invoke find(n) to match the nth occurrence of RE (it starts at 1)
    • Example –
      private static void demoRepeatedFinds(CharSequence source, String regex) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(source);
        // Find each occurrence of RE in source, in a loop.
        while (m.find()) {
          System.out.printf("find() matches: %s\n", m.group());
        }
        // Find the 2nd occurrence of RE in source.
        if (m.find(2)) {
          System.out.printf("find(2) matches: %s\n", m.group());
        }
      }
    • View code file.
  5. Aside: Pattern Compilation Options
    • Options for Pattern.compile() method 2nd parameter
    • T7P5

  6. Wildcards
    • You can use wildcards to indicate a number of common character types
    • T7P6

  7. Greedy and Reluctant Matching
    • An RE can sometimes lead to ambiguity when repeat quantifiers are used
      • Default behaviour is to use greedy matching
      • Match as much as possible
      • T7P7

    • Non-greedy (reluctant) matching is also available
    • T7P8

  8. Capturing Groups
    • You can partition an RE into groups
      • Parenthesized sub-expressions
      • Remember portions of text matched by sub-expressions
        "A (glass|bottle|barrel) of (Budweiser|Coors|Milk)"
      • View code file.
      • E.g. (glass|bottle|barrel) = group 1 and (Budweiser|Coors|Milk) = group 2
    • Groups are indexed left to right
      • Index 0 is the entire capture
      • No account taken of nesting
        A((B)(C(D)))
      • View code file.
      • In this case – “A((B)(C(D)))” this would be index 0 and the (D) would be index 4
      • Use (?…) to prevent capture – “Pure” groups do not figure in indexing
    • To access a capture group:
      • Invoke group(n) method on Matcher object
      • Index argument is 1-based
      • Invoke groupCount() to determine number of capture groups
    • Example:
      private static void demoGroups(CharSequence source, String regex) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(source);
        // Perform the match.
        if (m.matches()) {
          // Iterate through all the capture groups.
          for (int i = 1; i <= m.groupCount(); i++) {       System.out.printf("Group %d match: %s\n", i, m.group(i));     }   } }
    • View code file.
    • And when calling this the following code produces the result - Group 1 match: 01792, Group 2 match: 123456
      demoGroups("01792 123456", "(0\\d{3,4})[\\s-](\\d{6})");
    • View code file.
  9. Replacing Text Using Reg Exps
    • Matcher operations for replacing text:
      • replaceFirst(replacementString) - Returns new String where first match is replaced
      • replaceAll(replacementString) - Returns new String where all matches are replaced
    • Example:
      private static void demoReplacement(CharSequence src, String regex, String replacement) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(source);
        String result1 = m.replaceFirst(replacement);
        System.out.printf("replaceFirst() gives: %s \tsource: %s\n", result1, src);
        String result2 = m.replaceAll(replacement);
        System.out.printf("replaceAll()  gives: %s \tsource: %s\n", result2, src);
      }
    • View code file.
    • And the client code for calling this (see results for yourself) -
      demoReplacement("01222-123456 01222-654321 01222-98765", "01222-", "02920-2");
  10. Additions to the String Class
    • String class contains some new methods to support REs
      • boolean matches(String re)
      • String[] split(String re) // optional: int limit
      • String replaceFirst(String re, String repl)
      • String replaceAll(String re, String repl)
    • Example:
      private static void demoStringRE() {
        String greeting = "Hello mum";
        boolean result1 = greeting.matches("Hello mum"); // true
        boolean result2 = greeting.matches("Hello");   // false
        System.out.printf("Result1=%b, Result2=%b\n", result1, result2);
        String path = " Hello. How are you? I'm fine! Thanks!";
        String[] pathComponents = path.split("[.?!]");
        for (String pc : pathComponents) {
          System.out.println(pc);
        }
      }
    • View code file.
    • T7P9

Lab
  1. Using regular expressions
    • Open RegularExpressions.java, and write some code to make use of regular expressions
    • Suggestions and requirements:
      • First, take a look at the demo code that accompanies this chapter (see the DemoNewJavaSEClasses project, and the RegularExpressions.java source file)
      • In your application, write code to do simple pattern matching, as illustrated by the demoSimpleRegex() method in the demo code
        import java.util.regex.Matcher;
      • View code file.
      • Write code to explore the matching functionality provided by the Matcher class, as illustrated by the demoMatching() method in the demo code
        private static void doMatching() {
         System.out.println("Simple regular expressions:");
         Pattern p = Pattern.compile("(Hello)*");
         Matcher m1 = p.matcher("HelloHelloHello");
         boolean result1 = m1.matches();
         System.out.printf("Result1: %b %n", result1); // Should be true.
         Matcher m2 = p.matcher("HelloHelloHello What's Going On Here Then");
         boolean result2 = m2.matches();
         System.out.printf("Result2: %b %n", result2); // Should be false.
         Matcher m3 = p.matcher("HelloHelloHello What's Going On Here Then");
         boolean result3 = m3.lookingAt();
         System.out.printf("Result3: %b %n", result3); // Should be true.
        }
      • View code file.
      • Write code to perform repeated searches on a string, as illustrated by the demoRepeatedFinds() method in the demo code
        private static void doRepeatedFinds() {
         System.out.println("\nRepeated finds:");
         Pattern p = Pattern.compile("[a-z]+");
         Matcher m = p.matcher("testing 12345, god natt og takk for alle fisker!");
         while (m.find()) {
          System.out.printf("Found: %s\n", m.group());
         }
        }
      • View code file.
      • Write code to explore the regular expression support built into the String class, as illustrated by the demoStringRE() method in the demo code
        private static void doStringRE() {
         System.out.println("\nString RE support:");
         String greeting = "Good night";
         boolean result1 = greeting.matches("Good night"); // true
         boolean result2 = greeting.matches("Good"); // false
         System.out.printf("Result1=%b, Result2=%b\n", result1, result2);
         String path = " This. Is a Message! OK?";
         String[] pathComponents = path.split("[.?!]");
         for (String pc : pathComponents) {
          System.out.println(pc);
         }
         System.out.println();
        }
      • View code file.

 

Well done. You have completed the tutorial in the Java course. The next tutorial is

8. Inheritance


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top