The Infinte For Loop – Java

The infinite for loop is rather similar to the standard infinite while loop. The while loop uses true as an argument and will continue to operate forever because the argument is true and will not change. Similarly the infinite for loop works almost the exact same way. It uses true as it’s boolean expression and just leaves the initialization as null and the stepper as null. It looks like this.

1
2
3
4
5
6
7
8
9
10
//creating an infinite loop by making the boolean value true and the other expressions null.
for(; true ;){
    System.out.println("Test");
}
 
//similar to this there is the while loop.
while(true){
    //The expression just needs to be true.
    //for example, it could be while(5 > 2){...
}

The Comma Operator in Java

Java has an often look past feature within it’s for loop and this is the comma operator. Usually when people think about commas in the java language they think of a way to split up arguments within a functions parameters. ie:

1
2
3
private static void toast(int temp, int duration){
System.out.println("That is some nice toast!");
}

The comma operator can be used in two sections of the for loop. First we need to look at a for loop and identify what each section is and does.

1
2
3
for(int x = 0; x <= 10; x++){
System.out.println("nom");
}

The first part where we declared x as 0 is known as the initialization, the second part where we say that x <= 10 is the boolean or sometimes known as the expression, the last part is known as the step or increment.

The first part of the for loop that we can apply our comma operator to is the initialization and the second part of the loop that we can apply it to is the incrementing part. Because the expression needs to equate to a booleon we cannot use the comma operator here.

Note: The comma operator will only work if the data types declared are of the same type. ie: integer.

Here is an example of a for loop using the comma operator.

1
2
3
for(int x = 1, int z = 9; z &lt;= 923; z++, x += 2){
    //statements
}

Writing and reading objects and arrays to a binary file with java

This article requires that you have read the following java tutorials or you feel comfortable writing and reading variables to a binary file.

Advantage of writing files in binary with java

Reading information from a binary file with java

Writing information to a binary file with java

The first thing that is needed in this tutorial is an object that we are going to save into binary. This object is going to be a simple object with one instance variable, two constructors, one of which is default and a get name method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.io.Serializable;
public class Person implements Serializable{
    private String name;
 
    public Person(){
        name = "no name";
    }
    public Person(String x){
        name = x;
    }
    public String getName(){
        return name;
    }
}

You may notice that at the top of our new object we have a line that says “import java.io.Serializable” This line imports a class that we can use. It is required when we want to turn an object into binary and save it to a file. There is also a line that implements Serializable. This line is needed so the class can use the methods within the class Serializable.

The next piece of code will be added outside of the main method. It is added because we will need to use the file input and output streams along with the object input and output streams. We will also be using an IOException. If you would like to use other exception handling classes you can certainly feel free too. I would advise using the file not found and end of file exception.

1
2
3
4
5
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;

This next bit of code is going to save what we want for a filename inside of a string variable. After that we will be creating two person objects and two arrays, one being a string type and the other an integer type. The next line of code will create a null output stream then create the output stream while testing it for any errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//the filename to create.
        String fileName = "file.dat";
 
        //Person Objects
        Person p1 = new Person("Bob");
        Person p2 = new Person("Paul");
 
        //Array to write
        String[] helloThere = new String[]{"dog","cat","hamburger"};
        int[] thereHello = new int[]{1,2,3,4,5,6,7,8,9};
 
        //creating the space in memory for the file
        ObjectOutputStream  outputStream = null;
 
        try{
            outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
        }catch(IOException e){
            System.out.println("Could not open the file." + e);
            System.exit(0);
        }

Writing the objects to a binary file is done in a similar way to writing everything else. Since an array is actually an object it uses the same method as the object person. To write these two kinds of objects we will need to use the try catch in order to handle any errors then inside of that write objects using the outputstream.

1
2
3
4
5
6
7
8
9
10
11
12
try{
            outputStream.writeObject(p1);
            outputStream.writeObject(p2);
            outputStream.writeObject(helloThere);
            outputStream.writeObject(thereHello);
 
            outputStream.close();
 
        }catch(IOException e){
            System.out.println("Writing error: " + e);
            System.exit(0);
        }

Now that we are done writing the objects to the binary file we will need to read the information back into new objects.

We are going to create a new input stream in the same way that we made the output stream. It will first be of type null and then we will truly create it inside of the try catch blocks.

1
2
3
4
5
6
7
ObjectInputStream inputStream = null;
        try{
            inputStream = new ObjectInputStream(new FileInputStream(fileName));
        }catch(IOException e){
            System.out.println("There was a problem opening the file: " + e);
            System.exit(0);
        }

Since we are going to pull the information out of the file and reload them as objects we will need to create new objects in memory to show that we have successfully read the file.

1
2
3
4
5
//Create new blank objects to store the data in.
        Person newp1 = null;
        Person newp2 = null;
        String[] test = null;
        int[] test2 = null;

In order to read the information we will rely on our trusted try and catch blocks to let us test that everything is going as planned. Inside of the try catch blocks there is going to be the code required to load the objects read from memory into the new objects that we created in the code above.

You will also notice that when we saved the object information to a new object we specified what kind of object it was. This casts the information and sets it up as said object so it can once again use the methods that come along with that object type.

1
2
3
4
5
6
7
8
9
10
try{
            newp1 = (Person)inputStream.readObject();
            newp2 = (Person)inputStream.readObject();
            test = (String[])inputStream.readObject();
            test2 = (int[])inputStream.readObject();
            inputStream.close();
        }catch(Exception e){
            System.out.println("There was an issue reading from the file: " + e);
            System.exit(0);
        }

The last thing required is for us to do is test a person and an array. We will do this as follows.

1
2
System.out.println("newp1\'s name is " + newp1.getName());
        System.out.println(test2[0]);

If everything goes according to plan then we will have no errors. If you do have an error then please refer to the last bit of code to see if you did anything wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/* Code with Design
 *
 * Created By: Caleb Jonasson
 *
 * Desc: This class file is used to create a binary file,
 * write values to the file and check for errors along the way.
 */
 
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
 
public class writebin {
 
    public static void main(String[] args) {
        //the filename to create.
        String fileName = "file.dat";
 
        //Person Objects
        Person p1 = new Person("Bob");
        Person p2 = new Person("Paul");
 
        //Array to write
        String[] helloThere = new String[]{"dog","cat","hamburger"};
        int[] thereHello = new int[]{1,2,3,4,5,6,7,8,9};
 
        //creating the space in memory for the file
        ObjectOutputStream  outputStream = null;
 
        try{
            outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
        }catch(IOException e){
            System.out.println("Could not open the file." + e);
            System.exit(0);
        }
 
 
 
        try{
            outputStream.writeObject(p1);
            outputStream.writeObject(p2);
            outputStream.writeObject(helloThere);
            outputStream.writeObject(thereHello);
 
            outputStream.close();
 
        }catch(IOException e){
            System.out.println("Writing error: " + e);
            System.exit(0);
        }
        System.out.println("Records have been written to the file.");
 
 
        /*Reading the objects from memory.*/
 
        ObjectInputStream inputStream = null;
        try{
            inputStream = new ObjectInputStream(new FileInputStream(fileName));
        }catch(IOException e){
            System.out.println("There was a problem opening the file: " + e);
            System.exit(0);
        }
 
        //Create new blank objects to store the data in.
        Person newp1 = null;
        Person newp2 = null;
        String[] test = null;
        int[] test2 = null;
 
        try{
            newp1 = (Person)inputStream.readObject();
            newp2 = (Person)inputStream.readObject();
            test = (String[])inputStream.readObject();
            test2 = (int[])inputStream.readObject();
            inputStream.close();
        }catch(Exception e){
            System.out.println("There was an issue reading from the file: " + e);
            System.exit(0);
        }
        System.out.println("Reading of the file: " + fileName + " has been completed.");
 
        //Now we test to make sure that it worked correctly.
        System.out.println("newp1\'s name is " + newp1.getName());
        System.out.println(test2[0]);
 
    }
 
}

Advantages to writing files in binary with java

There are quite a few reasons that a programmer would like to write to a file in binary but the main reasons are speed, space and precision. Along with those three it is also important to understand when you are going to want to write in binary and when not to.

Speed is a great advantage to writing to files in binary. It allows you to simply pull the information that you want and load it into variables and objects effectively and easily. As you would try to do the same with its counter part you would instead have to go through each line, looping and parsing the information as you go which is not the most effective way to read a file. Using the methods that come with the ObjectOutputStream you can simply write “writeInt(variableInt);” and the data will be written to the file in binary.

The second great advantage to writing is binary is the space. Your files will be much more compact when everything is saved in binary and this makes an especially large difference when you have to pull large amounts of information from a file. Since everything is made up of a set amount of bytes you can compress more into one file by not having any white space.

The third reason to why binary is a good alternative is the precision of writing what is in memory to the file. There is no parsing, the files are written and pulled as they once where when they were placed in memory at one point in time. This allows for less of a risk factor for your programs to stop working on a client and will allow you to have more trust in what you are pulling out of a saved file.

There are times that you will want to write to a file using the full print writer over binary and this is when you have something like a crash log that allows a user to read what happened when the program crashed, where the bug was etc. Aside from information you want to be seen the upside of binary is quite significant. It allows you to have your own set pattern as to writing and pulling information making it harder for someone to go into your file and know what they are changing. And example of this would be a video game. You don’t want someone able to simple log in and change his or her score. You would be better off if they were unable to read the file.

Keeping information secretive is a great part about binary files. Sure you can crack it using patterns but it is less likely a general user will be able to do so unless they know how the program was written.

Reading information from a binary file with java

This tutorial is an extension from “writing information to a binary file with java.” It is in your best interest to read the previous article since this one will be continuing the code.

Previously we created a bunch of primitive data types along with a string. These files have been written to the data file entitled “file.dat” If you did not want to follow the previous article you can download the article here along with the data file within it.

We are going to want to add more classes to import. The classes that we need to import are the “ObjectInputStream” and “FileInputStream.” You should now have the following classes imported into your file.

1
2
3
4
5
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

Since we have already written our data to the file and closed it we will need to open the file to read it using the input stream. Like in the last tutorial we are going to need to associate the memory to blank then try to load the file that we created earlier. The code will look something like this.

1
2
3
4
5
6
7
ObjectInputStream inputStream = null;
        try{
            inputStream = new ObjectInputStream(new FileInputStream(fileName));
        }catch(IOException e){
            System.out.println("There was a problem opening the file: " + e);
            System.exit(0);
        }

The next thing to do is read the binary in the same order that it was written, top to bottom, so if we first write an integer then boolean we need to read an integer then a boolean or else we are going to get some wrong numbers coming back at us. The next part of the code is also in try catch using the Exception e.

Please note that it is good practice to place individual try catch whenever you read from the file and load into memory. This will allow you to better find errors but for the sake of this article we are going to save the space.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
try{
            byte var1 = inputStream.readByte();
            short var2 = inputStream.readShort();
            int var3 = inputStream.readInt();
            long var4 = inputStream.readLong();
 
            float var5 = inputStream.readFloat();
            double var6 = inputStream.readDouble();
 
            char var7 = inputStream.readChar();
            String var8 = inputStream.readUTF();
 
            boolean b1 = inputStream.readBoolean();
 
            inputStream.close();
        }catch(Exception e){
            System.out.println("There was an issue reading from the file: " + e);
            System.exit(0);
        }

If you would like to take a look at all of the code used in this demo it is placed below for your convenience.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* Code with Design
 *
 * Created By: Caleb Jonasson
 *
 * Desc: This class file is used to create a binary file,
 * write values to the file and check for errors along the way.
 */
 
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
 
public class writebin {
 
    public static void main(String[] args) {
        //the filename to create.
        String fileName = "file.dat";
 
        //creating the space in memory for the file
        ObjectOutputStream  outputStream = null;
 
        try{
            outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
        }catch(IOException e){
            System.out.println("Could not open the file." + e);
            System.exit(0);
        }
 
        byte foo = 1;
        short bar = 5;
        int baz = 543;
        long qurk = 123923892;
 
        float flt = 1;
        double dbl = 1.2323;
 
        char chr = 'a';
        String str = "hello";
 
        boolean bool = false;
 
        try{
            //integet based
            outputStream.writeByte(foo);
            outputStream.writeShort(bar);
            outputStream.writeInt(baz);
            outputStream.writeLong(qurk);
 
            //decimal based
            outputStream.writeFloat(flt);
            outputStream.writeDouble(dbl);
 
            //alpha based
            outputStream.writeChar(chr);
            outputStream.writeUTF(str);
 
            //true false based
            outputStream.writeBoolean(bool);
 
            outputStream.close();
 
        }catch(IOException e){
            System.out.println("Writing error: " + e);
            System.exit(0);
        }
        System.out.println("Records have been written to the file.");
 
        ObjectInputStream inputStream = null;
        try{
            inputStream = new ObjectInputStream(new FileInputStream(fileName));
        }catch(IOException e){
            System.out.println("There was a problem opening the file: " + e);
            System.exit(0);
        }
        try{
            byte var1 = inputStream.readByte();
            short var2 = inputStream.readShort();
            int var3 = inputStream.readInt();
            long var4 = inputStream.readLong();
 
            float var5 = inputStream.readFloat();
            double var6 = inputStream.readDouble();
 
            char var7 = inputStream.readChar();
            String var8 = inputStream.readUTF();
 
            boolean b1 = inputStream.readBoolean();
 
            inputStream.close();
        }catch(Exception e){
            System.out.println("There was an issue reading from the file: " + e);
            System.exit(0);
        }
        System.out.println("Reading of the file: " + fileName + " has been completed.");
 
    }
 
}

Writing information to a binary file in java

In this tutorial I will be showing you how to import the required IO classes, check for errors using a try catch and write to a binary file. In order to do this tutorial a basic knowledge of Java, methods and variables is required.

Get the files used in this tutorial.

The first thing we need to do is import our classes. The classes we will import are going to be the following: “ObjectOutputStream”, “FileOutputStream” and the IOException.

1
2
3
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

The next thing that is required is to create the object “ObjectOutputStream.” We will do this by using the classes we imported at the start of this tutorial. We will also be placing this into a try catch statement to see if we are properly opening the file.

1
2
3
4
5
6
7
String fileName = "file.dat";
        try{
            outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
        }catch(IOException e){
            System.out.println("Could not open the file." + e);
            System.exit(0);
        }

Take note that we are getting the file name from the a string variable and using it in our new file stream.

Since we now have our file created and classes imported the next thing required is for us to create all of the variables we will be using in this example. Since I will be using all of the primitive variable types there will be a fair sized list you will need to type out.

1
2
3
4
5
6
7
8
9
10
11
12
byte foo = 1;
        short bar = 5;
        int baz = 543;
        long qurk = 123923892;
 
        float flt = 1;
        double dbl = 1.2323;
 
        char chr = 'a';
        String str = "hello";
 
        boolean bool = false;

The next step is to write all of the variables to the file through the output stream. Once again this will be done using try catch block but you shouldn’t have a problem if you follow along correctly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
try{
            //integet based
            outputStream.writeByte(foo);
            outputStream.writeShort(bar);
            outputStream.writeInt(baz);
            outputStream.writeLong(qurk);
 
            //decimal based
            outputStream.writeFloat(flt);
            outputStream.writeDouble(dbl);
 
            //alpha based
            outputStream.writeChar(chr);
            outputStream.writeUTF(str);
 
            //true false based
            outputStream.writeBoolean(bool);
 
            outputStream.close();
 
        }catch(IOException e){
            System.out.println("Writing error: " + e);
            System.exit(0);
        }

The final piece of the code will close the output stream and tell us that we have successfully written to a file.

1
System.out.println("Records have been written to the file.");

The file with everything in it is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class writebin {
    public static void main(String[] args) {
        String fileName = "file.dat";
 
        ObjectOutputStream  outputStream = null;
 
        try{
            outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
        }catch(IOException e){
            System.out.println("Could not open the file." + e);
            System.exit(0);
        }
 
        byte foo = 1;
        short bar = 5;
        int baz = 543;
        long qurk = 123923892;
 
        float flt = 1;
        double dbl = 1.2323;
 
        char chr = 'a';
        String str = "hello";
 
        boolean bool = false;
 
        try{
            //integet based
            outputStream.writeByte(foo);
            outputStream.writeShort(bar);
            outputStream.writeInt(baz);
            outputStream.writeLong(qurk);
 
            //decimal based
            outputStream.writeFloat(flt);
            outputStream.writeDouble(dbl);
 
            //alpha based
            outputStream.writeChar(chr);
            outputStream.writeUTF(str);
 
            //true false based
            outputStream.writeBoolean(bool);
 
            outputStream.close();
 
        }catch(IOException e){
            System.out.println("Writing error: " + e);
            System.exit(0);
        }
        System.out.println("Records have been written to the file.");
    }
 
}

Java: Tutorial about Arrays vs Static Arrays

This is a tutorial found on dream in code that I recently stumbled upon. It gives you a good look at an alternative to an array when using anything over java JDK 5. The tutorial covers some of the built in methods that the the ArrayList class comes with. It also goes over sorting, looping, checking for null and changing index’.

The tutorial was written by one of the moderators who goes by the screen name Locke.

You can find the tutorial here.