Java Tutorials

Singleton Design Pattern in Java

When we write java applications, sometimes it is appropriate to have only one instance of a class. Windows Managers, Login and Dialog boxes etc are few examples of such classes. The Singleton design pattern solves this common problem and ensures that the class has only one instance. This also provides global point of access to the object.

Copying Text based Files in Java

Java IO Package provides two streams we can use to read and write all types of files including images, audio, video or even text files. These classes are FileInputStream and FileOutputStream. In the following tutorial, I will show you how you can use these classes to read and write image file.

Writing Text Files in Java using FileWriter class

Java IO package provides FileWriter class which developers can use to write contents in disk file as a sequence of characters. The constructor of the class requires file path and creates automatically if it does not exist depending on the user operation system security settings.

Reading Text based Files in Java

The Java IO package provides FileReader class to read contents of a text based file such as txt, html or XML. The most common method to read text file in java is to call read method of FileReader class in the loop and continuously check the return byte of the read method. Read method returns -1 when it reaches at the end of the file and there are no contents to read. However, you must need to keep in mind that read method throws FileNotFoundException if the file you are trying to read does not exist. It also throws IOException if there is any other IO related error during the file reading process.

Reading Console Input in Java

Reading console input in simple java console applications is a very straight forward process. Java provides developers two predefined streams in the java.lang.System class to read and write data to and from standard input and output devices. System.out is a standard output stream which is Console by default and is predefined input stream which is Keyboard by default. To read user input in a console window we connect with other stream classes available in package.

Creating and Using Enums in Java

In J2SE 5.0 Java introduced typesafe enumerations called “Enum” or simply “enums”. They are used to create multiple constants with a single given name.