Java Examples

Dave Braunschweig

Strings

// This program demonstrates string functions.

class Main {
    public static void main(String[] args) {
        String str = "Hello";

        System.out.println("string: " + str);
        System.out.println("string.toLowerCase(): " + str.toLowerCase());
        System.out.println("string.toUpperCase(): " + str.toUpperCase());
        System.out.println("string.indexOf('e'): " + str.indexOf('e'));
        System.out.println("string.length(): " + str.length());
        System.out.println("string.replace('H', 'j'): " + str.replace('H', 'j'));
        System.out.println("string(substring(2,4): " + str.substring(2, 4));
        System.out.println("string.trim(): " + str.trim());

        String name = "Bob";
        double value = 123.456;
        System.out.println(String.format("%s earned $%.2f", name, value));
    }
}

Output

string: Hello
string..toLowerCase(): hello
string.toUpperCase(): HELLO
string.indexOf('e'): 1
string.length(): 5
string.replace('H', 'j'): jello
string(substring(2,4): ll
string.trim(): Hello
Bob earned $123.46

Files

// This program demonstrates reading a text file with exception handling.

// References:
//     https://en.wikibooks.org/wiki/Java_Programming

import java.util.*;

class Main {
    public static void main(String[] args) {
        String FILENAME = "temperature.txt";
    
        readFile(FILENAME);
    }
    
    private static void readFile(String filename) {
        try {
            java.io.File file = new java.io.File(filename);
            java.io.BufferedReader reader = 
                new java.io.BufferedReader(new java.io.FileReader(file));
            String line;

            while(true) {
                line = reader.readLine();
                if (line == null) {
                    break;
                }
                System.out.println(line);
            }
            reader.close();
            System.out.println("");
        } catch(Exception exception) {
            System.out.println("Error reading " + filename);
            exception.printStackTrace();
        }
    }
}

Output

Celsius,Fahrenheit
0,32
10,50
20,68
...
80,176
90,194
100,212

References

License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Programming Fundamentals Copyright © 2018 by Authors and Contributors is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book