Writing a Text File in Java

Java has plenty of classes for file manipulation. For simple text files which contains lines of text, the best classes to use are FileWriter and PrintWriter in java.io package. PrintWriter has the method println() which writes a string into the file followed by a new line. Also note that PrintWriter and FileWriter must be closed in that order for the data to be actually written in the file. If you do not close PrintWriter or FileWriter, you may find that the resulting file is empty. FileWriter may throw checked exception IOException in case of any runtime error.

The following program demonstrates how you can write a text file in Java.

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;


/** Writing a text file Java.
 * 
 * @author jj
 */
public class WriteFile {
   
    public static void main(String[] args) {
        
        // data to write in file
        String data = "Hello World!";
        try {
            // Change this to a valid directory and file name in your system
            FileWriter fw = new FileWriter("/Volumes/ZEN/temp/test.txt");
            PrintWriter pw = new PrintWriter(fw);
            
            pw.println(data);
            
            pw.close();
            fw.close();
            
        }catch(IOException ex){
            System.out.println("Unable to write file!");
            ex.printStackTrace();
        }
        
    }
}

Splitting Strings in Java

One of the common string processing requirements in computer programs is to split a string into sub strings based on a delimiter. This can be easily achieved in Java using its rich String API. The split function in String class takes the delimiter as a parameter expressed in regular expression form.

The following Java program demonstrates the use of split function for splitting strings. Note that characters which has special meaning in regular expressions must be escaped using a slash (\) when passed as parameter to split function. Also note that an additional slash is required to escape slash in a Java string.

Please see this page on regular expressions for more details.

/**
 * Sample program to split strings in Java. The Java String API has a built-in 
 * split function which uses regular expressions for splitting strings.
 * 
 * 
 */
public class SplitString {
    
    public static void main(String[] args) {
        
        // Demo1 - splitting comma separated string
        String commaSeparatedCountries = "India,USA,Canada,Germany";
        String[]countries = commaSeparatedCountries.split(",");
        // print each country!
        for(int i=0;i<countries.length;i++) {
            System.out.println(countries[i]);
        }
        
        // Demo2 - Splitting a domain name into its subdomains
        // The character dot (.) has special meaning in regular expressions and 
        // hence must be escaped. Double slash is required to escape slash in Java 
        // string.
        String fullDomain = "www.blog.quickprogrammingtips.com";
        String[] domainParts = fullDomain.split("\\.");
        
        for(int i=0;i<domainParts.length;i++) {
            System.out.println(domainParts[i]);
        }
        
        
        // Demo3 - Splitting a string using regular expressions
        // In this example we want splitting on characters such as comma,dot or 
        // pipe. We use the bracket expression defined in regular expressions.
        // Only dot(.) requires escaping.
        String delimtedText = "data1,data2|data3.data4";
        String[] components = delimtedText.split("[,|\\.]");
        
        for(int i=0;i<components.length;i++) {
            System.out.println(components[i]);
        }   
    } 
}

How to Print Asterisk Triangle Pyramid in Java

Printing asterisk triangle is common programming problem given to beginners learning Java language. This will help students to grasp the power of loop programming construct. There are a number of variants of this problem. The following example shows how a triangle pyramid can be printed using Java.

       *
      ***
     *****
    *******
   *********
  ***********
 *************
***************
/**
 * How to print asterisk triangle pyramid in Java
 * @author jj
 */
public class AsteriskPyramid {
    
    public static void main(String[] args) {
        int sizeOfPyramid = 8;
        
        for(int i=1;i<=sizeOfPyramid;i++) {
			// print reduced number of spaces for each new row
            for(int j=i;j<=sizeOfPyramid-1;j++) {
                System.out.print(" ");
            }
			
			// the number of asterisks per row is 2*rownumber-1
            for(int k=1;k<=2*i-1;k++){
                System.out.print("*");
            }
            System.out.println("");
        }
    }
}

How to Multiply Two Numbers in Java

Simple programming problems such as multiplication of numbers is a good way to teach programming syntax without students getting overwhelmed by the programming solution. The following Java program demonstrates multiplication of two numbers. This is a trivial example program, however it shows how to handle input and output, performing calculations and the use of library classes such as Scanner in Java language.

The user is prompted to enter first and the second number. Product of the entered numbers is calculated and is displayed on the command line in an equation form.

import java.util.Scanner;

/**
 * Java program for multiplying two numbers
 * @author jj
 */
public class MultiplyNumbers {
    public static void main(String[] args) {
        Scanner sn = new Scanner(System.in);
        
        System.out.print("Please enter first number:");
        double n1 = sn.nextDouble();                
        System.out.print("Please enter second number:");
        double n2 = sn.nextDouble();
        
        double product = n1 * n2;
        System.out.println(n1+"*"+n2+"="+product);
        
    }
}

How to Check If a Triangle Can be Formed in Java

The sides of a triangle is constrained by the rule that the sum of any of its two sides is always bigger than the third side. Using this rule, we can find whether 3 sides given for a triangle is valid or not. The following sample Java program checks whether the given 3 sides can form a valid triangle.

import java.util.Scanner;

/**
 * Validates whether the given 3 sides can form a triangle or not.
 * @author jj
 */
public class ValidTriangle {
    
    public static void main(String[] args) {
        
        Scanner sn = new Scanner(System.in);
        System.out.println("Enter length of first side of triangle:");
        double a = sn.nextDouble();
        
        System.out.println("Enter length of second side of triangle:");
        double b = sn.nextDouble();
        
        System.out.println("Enter length of third side of triangle:");
        double c = sn.nextDouble();
        
        ValidTriangle vt   = new ValidTriangle();
        if(vt.isTriangleValid(a, b, c)) {
            System.out.println("Sides entered can form a triangle!");
        }else {
            System.out.println("Sides entered cannot form a triangle!");
        }
        
    }

   
    /**
     * Checks whether the 3 sides can form a triangle
     * The sum of any two sides must be greater than the other side
     * @param a
     * @param b
     * @param c
     * @return 
     */
    private boolean isTriangleValid(double a, double b, double c) {
        if((a+b)>c && (a+c)>b && (b+c)>a) {
            return true;
        }else {
            return false;
        }
    }
}