Saturday, 31 January 2015

More About the Java Return Statement

The return statement does not have to pass a value back at all. It can just be used to return control to the calling program. Once a return statement has been executed, the code which follows it is not executed. You can see what I mean in the example below:

andrew@UBUNTU:~/Java$ cat Number_Check.java
public class Number_Check
  {
  public void check_number(int a)
    {
    if (a < 10)
      {
      System.out.println(a + " < 10");
      return;
      }
//  The next line is ignored if the number supplied
//  is less than 10:
    System.out.println(a + " >= 10");
    }
  }
andrew@UBUNTU:~/Java$ javac Number_Check.java
andrew@UBUNTU:~/Java$


andrew@UBUNTU:~/Java$ cat Number_Check_Test.java
class Number_Check_Test
  {
  public static void main(String args[])
    {
    Number_Check x = new Number_Check();
    x.check_number(9);
    x.check_number(10);
    x.check_number(11);
    }
  }
andrew@UBUNTU:~/Java$ javac Number_Check_Test.java
andrew@UBUNTU:~/Java$ java Number_Check_Test
9 < 10
10 >= 10
11 >= 10
andrew@UBUNTU:~/Java$


However, if the compiler sees code which will NEVER execute, it returns a compilation error:

andrew@UBUNTU:~/Java$ cat Another_Number_Check.java
public class Another_Number_Check
  {
  public void check_number(int a)
    {
    if (a < 10)
      {
      System.out.println(a + " < 10");
      return;
      }
    else
      {
      System.out.println(a + " >= 10");
      return;
      }
    System.out.println("This line is ignored");
    }
  }
andrew@UBUNTU:~/Java$ javac Another_Number_Check.java
Another_Number_Check.java:15: unreachable statement
    System.out.println("This line is ignored");
    ^
1 error
andrew@UBUNTU:~/Java$

Thursday, 29 January 2015

How to Return Values From a Java Method

This example is based on an earlier post but I have changed it to show how a method can return a value. The first part creates a class called Square:

andrew@UBUNTU:~/Java$ cat Square.java
public class Square
  {
  double width;
  public void display_area()
    {
// The next line calls the calculate_area method.
// The value returned is assigned to area:
    double area = calculate_area();
    System.out.println("Area = " + area);
    }
// The word double in the next line tells you
// that this method returns a double value:
  private double calculate_area()
    {
    double area = width * width;
// The next line returns the value:
    return area;
    }
  }
andrew@UBUNTU:~/Java$ javac Square.java
andrew@UBUNTU:~/Java$
 

The second part creates a member of the Square class and calls the methods which calculate and display its area:

andrew@UBUNTU:~/Java$ cat SquareExample.java
class SquareExample
  {
  public static void main(String args[])
    {
    Square my_square = new Square();
    my_square.width = 5;
    my_square.display_area();
    }
  }
andrew@UBUNTU:~/Java$ javac SquareExample.java
andrew@UBUNTU:~/Java$ java SquareExample
Area = 25.0
andrew@UBUNTU:~/Java$

Tuesday, 27 January 2015

Java Method Overloading

At this stage, I don’t know why you would want to do this, but Java allows method overloading. This means that you can have two or more methods with the same name:

Java > cat my_class.java
class my_class
  {
  public void multiply (int x, int y)
    {
    int a = x * y;
    System.out.println("a = " + a);
    }
  public void multiply (int x, int y, int z)
    {
    int b = x * y * z;
    System.out.println("b = " + b);
    }
  public void multiply (double x, double y)
    {
    double c = x * y;
    System.out.println("c = " + c);
    }
  }
Java > javac my_class.java
Java >

The only difference the outside world can see between these methods is in the number and type(s) of parameters they expect to receive. When you use an overloaded method, you let Java know which version to use by passing the parameters it requires:

Java > cat test_my_class.java
public class test_my_class
  {
  public static void main(String args[])
   {
    my_class my_class1 = new my_class();
    int i=2, j=3, k=4;
    double m=2.5, n=3;
    my_class1.multiply (i, j);
    my_class1.multiply (i, j, k);
    my_class1.multiply (m, n);
    }
  }
Java > javac test_my_class.java
Java > java test_my_class
a = 6
b = 24
c = 7.5
Java >

Monday, 26 January 2015

Primitive Data Types are Passed to Methods by Value in Java

I created a class called my_class with a method called times_two. The method accepts an integer and multiplies it by 2:

Java > cat my_class.java
public class my_class
  {
  public void times_two(int a)
    {
    a = a * 2;
    System.out.println("a = " + a);
    }
  }
Java > javac my_class.java
Java >

I created a program called test_my_class. This sets up an instance of my_class called b. It then creates an integer variable called x and gives it a values of 2. Next, it passes x as a parameter to the times_two method, which multiplies it by 2 to give 4. Finally, it displays the original value, which is still 2. This is because the value of x is passed to the method, not a reference to its location in memory.

Java > cat test_my_class.java
public class test_my_class
  {
  public static void main(String args[])
    {
    my_class b = new my_class();
    int x = 2;
    b.times_two(x);
    System.out.println("x = " + x);
    }
  }
Java > javac test_my_class.java
Java > java test_my_class
a = 4
x = 2
Java >

A Java Private Method

In this example I create a class called Square. It has a public method called display_area. This has to call a private method called calculate_area before it can display the result. Private methods are only accessible from within the class which contains them:

andrew@UBUNTU:~/Java$ cat Square.java
public class Square
  {
  double width;
  double area;
  public void display_area()
    {
    calculate_area();
    System.out.println("Area = " + area);
    }
  private void calculate_area()
    {
    area = width * width;
    }
  }
andrew@UBUNTU:~/Java$ javac Square.java
andrew@UBUNTU:~/Java$


I create a program to define a square and display its area (I have shown you a similar example already):

andrew@UBUNTU:~/Java$ cat SquareExample1.java
class SquareExample1
  {
  public static void main(String args[])
    {
    Square my_square = new Square();
    my_square.width = 5;
    my_square.display_area();
    }
  }
andrew@UBUNTU:~/Java$ javac SquareExample1.java
andrew@UBUNTU:~/Java$ java SquareExample1
Area = 25.0
andrew@UBUNTU:~/Java$


However, when I try to execute the calculate_area method directly from outside the class, Java returns a compilation error as the method concerned is private:

andrew@UBUNTU:~/Java$ cat SquareExample2.java
class SquareExample2
  {
  public static void main(String args[])
    {
    Square my_square = new Square();
    my_square.width = 5;
    my_square.calculate_area();
    }
  }
andrew@UBUNTU:~/Java$ javac SquareExample2.java
SquareExample2.java:7: calculate_area() has private access in Square
    my_square.calculate_area();
             ^
1 error
andrew@UBUNTU:~/Java$

Sunday, 25 January 2015

Java System.out.write

I decided to try displaying a character on my screen using System.out.write. It accepts an integer parameter, which can even contain a letter, which seems strange to me. I could not get it to work at first:

andrew@UBUNTU:~/Java$ cat prog82.java
public class prog82     
  {
  public static void main(String args[])
    {
    int x = 'Y';
    System.out.write(x);
    }
  }
andrew@UBUNTU:~/Java$ javac prog82.java
andrew@UBUNTU:~/Java$ java prog82
andrew@UBUNTU:~/Java$


I found that I had to include a new line to force Java to display the output:

andrew@UBUNTU:~/Java$ cat prog83.java
public class prog83     
  {
  public static void main(String args[])
    {
    int x = 'Y';
    System.out.write(x);
    System.out.write('\n');
    }
  }
andrew@UBUNTU:~/Java$ javac prog83.java
andrew@UBUNTU:~/Java$ java prog83
Y
andrew@UBUNTU:~/Java$

Saturday, 24 January 2015

How to Pass Parameters to a Java Method

I created a simple class called two_numbers with a method called show_greater. The method accepts two integer parameters and displays the larger:

andrew@UBUNTU:~/Java$ cat two_numbers.java
public class two_numbers
  {
  public void show_greater(int arg1, int arg2)
    {
    int greater = arg1;
    if (arg2 > arg1) greater = arg2;
    System.out.println(greater);
    }
  }
andrew@UBUNTU:~/Java$ javac two_numbers.java
andrew@UBUNTU:~/Java$


Then I created  a program called two_numbers_test. This declares an object called compare in the two_numbers class. It then calls the show_greater method three times, comparing two integers each time to see which one is bigger:

andrew@UBUNTU:~/Java$ cat two_numbers_test.java
public class two_numbers_test
  {
  public static void main(String args[])
    {
    two_numbers compare = new two_numbers();
    compare.show_greater(0,1);
    compare.show_greater(2,1);
    compare.show_greater(3,3);
    }
  }
andrew@UBUNTU:~/Java$ javac two_numbers_test.java
andrew@UBUNTU:~/Java$ java two_numbers_test
1
2
3
andrew@UBUNTU:~/Java$

Friday, 23 January 2015

Can You Change a Java String?

I read in a book that once you have created a Java String, you cannot change it so I decided to try it out myself:

andrew@UBUNTU:~/Java$ cat string_test.java
public class string_test
  {
  public static void main(String args[])
    {
    String str1 = "Andrew ";
    str1 = str1 + "was here";
    System.out.println("str1 = " + str1);
    }
  }
andrew@UBUNTU:~/Java$ javac string_test.java
andrew@UBUNTU:~/Java$ java string_test
str1 = Andrew was here
andrew@UBUNTU:~/Java$


At first glance, it looks as if you CAN change a String variable so I did a bit more reading. It seems that when you change a String, you are not altering the original variable. You are really creating a new variable to hold the updated value. If I can find some way to prove or disprove this statement, I will return to this post and update it accordingly.

Thursday, 22 January 2015

How to See Which Version of Java You Are Using

You can do this with the –version parameter as shown in the examples below, which came from three different machines:

Java > java -version
java version "1.5.0_25"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_25-b03)
Java HotSpot(TM) Server VM (build 1.5.0_25-b03, mixed mode)
Java >
 
C:\Users\J0294094>java -version
java version "1.6.0_38"
Java(TM) SE Runtime Environment (build 1.6.0_38-b05)
Java HotSpot(TM) 64-Bit Server VM (build 20.13-b02, mixed mode)
 
C:\Users\J0294094>

andrew@UBUNTU:~/Java$ java -version
java version "1.6.0_27"
OpenJDK Runtime Environment (IcedTea6 1.12.3) (6b27-1.12.3-0ubuntu1~12.04.1)
OpenJDK Client VM (build 20.0-b12, mixed mode, sharing)
andrew@UBUNTU:~/Java$

Wednesday, 21 January 2015

Java Constants

If you want to declare a constant in Java, you can do so with the final field modifier:

andrew@UBUNTU:~/Java$ cat Constant1.java
public class Constant1
  {
  public static void main(String args[])
    {
    final double PI = 3.14;
    System.out.println("PI = " + PI);
    }
  }
andrew@UBUNTU:~/Java$ javac Constant1.java
andrew@UBUNTU:~/Java$ java Constant1
PI = 3.14
andrew@UBUNTU:~/Java$


If you try to change one of these variables, you get a compilation error:

andrew@UBUNTU:~/Java$ cat Constant2.java
public class Constant2
  {
  public static void main(String args[])
    {
    final double PI = 3.14;
    System.out.println("PI = " + PI);
    PI = 22/7;
    }
  }
andrew@UBUNTU:~/Java$ javac Constant2.java
Constant2.java:7: cannot assign a value to final variable PI
    PI = 22/7;
    ^
1 error
andrew@UBUNTU:~/Java$

Sunday, 18 January 2015

Java static Variables

If a variable in a class is static, it has only one value, which is shared by all members of the class. You can see this in the example below, where I created a class called Tax with a static variable called VAT:

andrew@UBUNTU:~/Java$ cat Tax.java
public class Tax  
  {
  static double VAT = 10;
  }
andrew@UBUNTU:~/Java$ javac Tax.java
andrew@UBUNTU:~/Java$


Then I wrote a program to use the class. In this program, I created 2 members called member1 and member2 and showed that they both had the same VAT value, i,e, 10. I changed member1.VAT to 11 and showed that member2.VAT changed to 11 too, without a specific assignment. Doing it this way can make your code difficult to follow. An alternative is to modify the static variable by prefixing it with the name of the class. To demonstrate this, I changed Tax.VAT to 12 and checked member1.VAT and member2.VAT to see that they had been altered in the same way:

andrew@UBUNTU:~/Java$ cat Tax_test.java
public class Tax_test
  {
  public static void main(String args[])
    {
    Tax member1 = new Tax();
    System.out.println("member1.VAT = " + member1.VAT);
    Tax member2 = new Tax();
    System.out.println("member2.VAT = " + member2.VAT);
    member1.VAT = 11;
    System.out.println("member1.VAT = " + member1.VAT);
    System.out.println("member2.VAT = " + member2.VAT);
    Tax.VAT = 12;
    System.out.println("Tax.VAT = " + Tax.VAT);
    System.out.println("member1.VAT = " + member1.VAT);
    System.out.println("member2.VAT = " + member2.VAT);
    }
  }
andrew@UBUNTU:~/Java$ javac Tax_test.java
andrew@UBUNTU:~/Java$ java Tax_test
member1.VAT = 10.0
member2.VAT = 10.0
member1.VAT = 11.0
member2.VAT = 11.0
Tax.VAT = 12.0
member1.VAT = 12.0
member2.VAT = 12.0
andrew@UBUNTU:~/Java$

Saturday, 17 January 2015

A Java Class with a Method

A Java class can have a method. This is a piece of code which can be used on members of the class. In the example below, a class called Square is created. The Square class has a method called display_area, which calculates and displays the area of the square: 

andrew@UBUNTU:~/Java$ cat Square.java
public class Square
  {
  double width;
  double area;
  public void display_area()
    {
    area = width * width;
    System.out.println("Area = " + area);
    }
  }
class SquareExample
  {
  public static void main(String args[])
    {
    Square my_square = new Square();
    my_square.width = 5;
    my_square.display_area();
    }
  }
andrew@UBUNTU:~/Java$ javac Square.java
andrew@UBUNTU:~/Java$ java SquareExample
Area = 25.0
andrew@UBUNTU:~/Java$

Friday, 16 January 2015

A Simple Example with a Class and 1 Object

As I am a retired COBOL programmer, I don’t know anything about Object Oriented programming so please forgive me if this example seems a bit elementary. Classes are templates for real-life objects. In the example below, a Rectangle class is created. Each object in this class (i.e. each rectangle) has a width and a height. These are called instance variables. An object called my_rectangle is created in the Rectangle class and its width and height are supplied. Finally, a variable called area is created, calculated and displayed:
 
Java > cat Rectangle.java
class Rectangle
  {
  double width;
  double height;
  }
class RectangleExample
  {
  public static void main(String args[])
    {
    Rectangle my_rectangle = new Rectangle();
    double area;
    my_rectangle.width = 3;
    my_rectangle.height = 4;
    area = my_rectangle.width * my_rectangle.height;
    System.out.println("Area = " + area);
    }
  }
Java > javac Rectangle.java
Java > java RectangleExample
Area = 12.0
Java >

Wednesday, 14 January 2015

Division by Zero in Java

Java does not stop you dividing by zero but, if you try, it gives you a run-time error:
 
Java > cat prog81.java
public class prog81
{
public static void main (String args[])
  {
  int x = 1/0;
  System.out.println("x = " + x);
  }
}
Java > javac prog81.java
Java > java prog81
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at prog81.main(prog81.java:5)
Java >
 
You can trap these errors and handle them tidily as shown below. This stops your program falling over:
 
Java > cat prog82.java
public class prog82
{
public static void main (String args[])
  {
  try
    {
    System.out.println("Dividing 1 by 0");
    int x = 1/0;
    System.out.println("x = " + x);
    }
  catch (ArithmeticException e)
    {
    System.out.println("Division by zero not allowed");
    }
  try
    {
    System.out.println("Dividing 1 by 1");
    int y = 1/1;
    System.out.println("y = " + y);
    }
  catch (ArithmeticException e)
    {
    System.out.println("Division by zero not allowed");
    }
  }
}
Java > javac prog82.java
Java > java prog82
Dividing 1 by 0
Division by zero not allowed
Dividing 1 by 1
y = 1
Java >
 
However, if you divide 1.0 by 0.0, the answer is infinity:
 
Java > cat prog83.java
public class prog83
{
public static void main (String args[])
  {
  double x = 1.0/0.0;
  System.out.println("x = " + x);
  }
}
Java > javac prog83.java
Java > java prog83
x = Infinity
Java >

... and, if you divide 0.0 by 0.0, the answer is NaN (not a number):

andrew@UBUNTU:~/Java$ cat prog84.java
public class prog84
{
public static void main (String args[])
  {
  double x = 0.0/0.0;
  System.out.println("x = " + x);
  }
}
andrew@UBUNTU:~/Java$ javac prog84.java
andrew@UBUNTU:~/Java$ java prog84
x = NaN
andrew@UBUNTU:~/Java$

Tuesday, 13 January 2015

equals And equalsIgnoreCase In Java

If you want to make a case sensitive comparison between two string variables in Java, you can do so using equals as shown in prog80 below:

andrew@UBUNTU:~/Java$ cat prog80.java
public class prog80
{
public static void main (String args[])
  {
  String andrew = "andrew";
  String ANDREW = "ANDREW";
  if (andrew.equals(ANDREW))
    System.out.println("andrew = ANDREW");
  else
    System.out.println("andrew != ANDREW");
  }
}
andrew@UBUNTU:~/Java$ javac prog80.java
andrew@UBUNTU:~/Java$ java prog80
andrew != ANDREW
andrew@UBUNTU:~/Java$


If you need to do a case insensitive comparison, you can use equalsIgnoreCase instead:

andrew@UBUNTU:~/Java$ cat prog81.java
public class prog81
{
public static void main (String args[])
  {
  String andrew = "andrew";
  String ANDREW = "ANDREW";
  if (andrew.equalsIgnoreCase(ANDREW))
    System.out.println("andrew = ANDREW");
  else
    System.out.println("andrew != ANDREW");
  }
}
andrew@UBUNTU:~/Java$ javac prog81.java
andrew@UBUNTU:~/Java$ java prog81
andrew = ANDREW
andrew@UBUNTU:~/Java$

Saturday, 10 January 2015

Is Java Slower Than C?

I have seen this suggested before so I decided to check it out on my own PC. I built it myself 11 years ago and it has a Celeron processor. Nothing else was running on the machine at the time. I wrote the C program below and used it to count to 1 billion. It took 12 seconds:

andrew@UBUNTU:~/Java$ cat prog79.c
#include <stdio.h>
void main(void)
{
double x=0;
long a,b;
for (a=1;a<=10000;a++)
  {
  for (b=1;b<=100000;b++)
    {
    x++;
    }
  }
printf("x = %e ", x);
}
andrew@UBUNTU:~/Java$ cc -o prog79.o prog79.c
andrew@UBUNTU:~/Java$ date;./prog79.o;date
Sat Jan 10 18:31:43 GMT 2015
x = 1.000000e+09 Sat Jan 10 18:31:55 GMT 2015
andrew@UBUNTU:~/Java$


I wrote the same program in Java and it only took 3 seconds so, on the basis of this test at least, Java is not slower than C: 

andrew@UBUNTU:~/Java$ cat prog79.java
public class prog79
{
public static void main (String args[])
  {
  double x=0;
  long a,b;
  for (a=1;a<=10000;a++)
    {
    for (b=1;b<=100000;b++)
      {
      x++;
      }
    }
  System.out.println("x = " + x);
  }
}
andrew@UBUNTU:~/Java$ javac prog79.java
andrew@UBUNTU:~/Java$ date;java prog79;date
Sat Jan 10 18:39:00 GMT 2015
x = 1.0E9
Sat Jan 10 18:39:03 GMT 2015
andrew@UBUNTU:~/Java$

Java break Statement

The Java break statement allows you to terminate a loop. Here are a couple of examples:

andrew@UBUNTU:~/Java$ cat prog78.java
public class prog78
{
public static void main (String args[])
  {
  for (int a=1;a<10;a++)
    {
    System.out.println("a = " + a);
    if (a > 4)
      {
      System.out.println("BREAK");
      break;
      }
    }
  int b=0;
  while (true)
    {
    System.out.println("b = " + b);
    b++;
    if (b > 3)
      {
      System.out.println("BREAK");
      break;
      }
    }
  }
}
andrew@UBUNTU:~/Java$ javac prog78.java
andrew@UBUNTU:~/Java$ java prog78
a = 1
a = 2
a = 3
a = 4
a = 5
BREAK
b = 0
b = 1
b = 2
b = 3
BREAK
andrew@UBUNTU:~/Java$

Thursday, 8 January 2015

Java Right Shift Operator

In Java, >> is called the right shift operator. It moves the bits in a variable to the right. >> 1 moves the bits one place, >> 2 moves them two places and so on. If you start off with a value such as decimal 15, which is binary 1111, >> 1 changes it to binary 111 or decimal 7. >> 2 moves all the bits two places to the right and converts it to binary 11 or decimal 3. You can see what I mean in the example below:
 
Java > cat prog77.java
public class prog77
{
public static void main (String args[])
  {
  int x = 15;
  System.out.println("x = " + x);
  int y = x >> 1;
  System.out.println("x >> 1 = " + y);
  y = x >> 2;
  System.out.println("x >> 2 = " + y);
  y = x >> 3;
  System.out.println("x >> 3 = " + y);
  y = x >> 4;
  System.out.println("x >> 4 = " + y);
  }
}
Java > javac prog77.java
Java > java prog77
x = 15
x >> 1 = 7
x >> 2 = 3
x >> 3 = 1
x >> 4 = 0
Java >

Wednesday, 7 January 2015

Java java.lang.ArrayIndexOutOfBoundsException Error

If you use an array in your program, you need to be sure that you always access it with a valid subscript:
 
Java > cat prog75.java
public class prog75
{
public static void main (String args[])
  {
  int[] n = new int[5];
  for (int x=0;x<5;x++)
    {
    n[x]=2*x;
    System.out.println("n[" + x + "] = " + n[x]);
    }
  System.out.println("Finished");
  }
}
Java > javac prog75.java
Java > java prog75
n[0] = 0
n[1] = 2
n[2] = 4
n[3] = 6
n[4] = 8
Finished
Java >
 
…otherwise, you will get a run-time error:
 
Java > cat prog76.java
public class prog76
{
public static void main (String args[])
  {
  int[] n = new int[5];
  for (int x=0;x<6;x++)
    {
    n[x]=2*x;
    System.out.println("n[" + x + "] = " + n[x]);
    }
  System.out.println("Finished");
  }
}
Java > javac prog76.java
Java > java prog76
n[0] = 0
n[1] = 2
n[2] = 4
n[3] = 6
n[4] = 8
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
        at prog76.main(prog76.java:8)
Java >

Tuesday, 6 January 2015

Java While and Do While Loops

You can use a while loop to repeat code until some condition is reached:

andrew@UBUNTU:~/Java$ cat prog68.java
public class prog68
{
public static void main (String args[])
  {
  int iteration = 1;
  while (iteration <= 5)
    {
    System.out.println("Iteration " + iteration);
    iteration++;
    }
  System.out.println("Finished");
  }
}
andrew@UBUNTU:~/Java$ javac prog68.java
andrew@UBUNTU:~/Java$ java prog68
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Finished
andrew@UBUNTU:~/Java$


You can also use a do while loop:

andrew@UBUNTU:~/Java$ cat prog69.java
public class prog69
{
public static void main (String args[])
  {
  int iteration = 1;
  do                      
    {
    System.out.println("Iteration " + iteration);
    iteration++;
    }
  while (iteration <= 5);
  System.out.println("Finished");
  }
}
andrew@UBUNTU:~/Java$ javac prog69.java
andrew@UBUNTU:~/Java$ java prog69
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Finished
andrew@UBUNTU:~/Java$


The difference between the two is that the condition is evaluated before the while loop so it may not be necessary to run the code at all:

andrew@UBUNTU:~/Java$ cat prog70.java
public class prog70
{
public static void main (String args[])
  {
  int iteration = 6;
  while (iteration <= 5)
    {
    System.out.println("Iteration " + iteration);
    iteration++;
    }
  System.out.println("Finished");
  }
}
andrew@UBUNTU:~/Java$ javac prog70.java
andrew@UBUNTU:~/Java$ java prog70
Finished
andrew@UBUNTU:~/Java$


Whereas, with the do while loop, the condition is checked at the end so the code will always be executed at least once:

andrew@UBUNTU:~/Java$ cat prog71.java
public class prog71
{
public static void main (String args[])
  {
  int iteration = 6;
  do                         
    {
    System.out.println("Iteration " + iteration);
    iteration++;
    }
  while (iteration <= 5);
  System.out.println("Finished");
  }
}
andrew@UBUNTU:~/Java$ javac prog71.java
andrew@UBUNTU:~/Java$ java prog71
Iteration 6
Finished
andrew@UBUNTU:~/Java$

Monday, 5 January 2015

Java Nested For Loops

If you code a for loop within another for loop, this is called a nested for loop. You can see an example in prog67 below:

Java > cat prog67.java
public class prog67
{
public static void main (String args[])
  {
  for (int a=1;a<=4;a++)
    {
    for (int b=1;b<=4;b++)
      {
      System.out.println(a + "x" + b + "=" + a*b);
      }
    }
  }
}
Java > javac prog67.java
Java > java prog67
1x1=1
1x2=2
1x3=3
1x4=4
2x1=2
2x2=4
2x3=6
2x4=8
3x1=3
3x2=6
3x3=9
3x4=12
4x1=4
4x2=8
4x3=12
4x4=16
Java >

Sunday, 4 January 2015

Fibonacci Sequence (Part 3)

I wrote prog66 below to calculate a Fibonacci number supplied as a parameter then I tested it by recalculating the 20th term in the sequence:

andrew@UBUNTU:~/Java$ cat prog66.java
import java.math.BigInteger;
public class prog66
{
public static void main (String args[])
  {
  BigInteger x = BigInteger.valueOf(1);
  BigInteger y = BigInteger.valueOf(1);
  int required_term = Integer.parseInt(args[0]);
  int term = 0;
  boolean finished = false;
  while (!finished)
    {
    term++;
    if (term == required_term)
      {
      System.out.println(x);
      finished = true;
      }
    term++;
    if (term == required_term)
      {
      System.out.println(y);
      finished = true;
      }
    x = x.add(y);
    y = x.add(y);
    }
  }
}
andrew@UBUNTU:~/Java$ javac prog66.java
andrew@UBUNTU:~/Java$ java prog66 20
6765
andrew@UBUNTU:~/Java$
 

Then I ran the UNIX date command to check the time, calculated the 1,000,000th term in the Fibonacci sequence and ran the UNIX date command again. This showed that the program had taken less than 5 minutes to work out the answer:

andrew@UBUNTU:~/Java$ date;java prog66 1000000 > prog66.output;date
Sun Jan  4 19:31:40 GMT 2015
Sun Jan  4 19:36:23 GMT 2015
andrew@UBUNTU:~/Java$


I found a site which had the 1,000,000th Fibonacci number in a file called millionth-fibonacci-number.txt and downloaded it. Then I compared the first few digits in both files and saw that they were the same: 

andrew@UBUNTU:~/Java$ cat millionth-fibonacci-number.txt|more
1953282128707757731632014947596256332443542996591873396953405


andrew@UBUNTU:~/Java$ cat prog66.output|more
1953282128707757731632014947596256332443542996591873396953405

Saturday, 3 January 2015

Fibonacci Sequence (Part 2)

After some research I discovered how to use a BigInteger to calculate larger terms in the Fibonacci sequence as shown in prog65 below:

andrew@UBUNTU:~/Java$ cat prog65.java
import java.math.BigInteger;
public class prog65
{
public static void main (String args[])
  {
  BigInteger x = BigInteger.valueOf(1);
  BigInteger y = BigInteger.valueOf(1);
  int term;
  for (int z=1; z<=50; z++)
    {
    term = 2*z-1;
    System.out.println("Term " + term + " = " + x);
    term++;
    System.out.println("Term " + term + " = " + y);
    x = x.add(y);
    y = x.add(y);
    }
  }
}
andrew@UBUNTU:~/Java$ javac prog65.java
andrew@UBUNTU:~/Java$ java prog65
Term 1 = 1
Term 2 = 1
Term 3 = 2
Term 4 = 3
Term 5 = 5
Term 6 = 8
Term 7 = 13
Term 8 = 21
Term 9 = 34
Term 10 = 55
Term 11 = 89
Term 12 = 144
Term 13 = 233
Term 14 = 377
Term 15 = 610
Term 16 = 987
Term 17 = 1597
Term 18 = 2584
Term 19 = 4181
Term 20 = 6765
Term 21 = 10946
Term 22 = 17711
Term 23 = 28657
Term 24 = 46368
Term 25 = 75025
Term 26 = 121393
Term 27 = 196418
Term 28 = 317811
Term 29 = 514229
Term 30 = 832040
Term 31 = 1346269
Term 32 = 2178309
Term 33 = 3524578
Term 34 = 5702887
Term 35 = 9227465
Term 36 = 14930352
Term 37 = 24157817
Term 38 = 39088169
Term 39 = 63245986
Term 40 = 102334155
Term 41 = 165580141
Term 42 = 267914296
Term 43 = 433494437
Term 44 = 701408733
Term 45 = 1134903170
Term 46 = 1836311903
Term 47 = 2971215073
Term 48 = 4807526976
Term 49 = 7778742049
Term 50 = 12586269025
Term 51 = 20365011074
Term 52 = 32951280099
Term 53 = 53316291173
Term 54 = 86267571272
Term 55 = 139583862445
Term 56 = 225851433717
Term 57 = 365435296162
Term 58 = 591286729879
Term 59 = 956722026041
Term 60 = 1548008755920
Term 61 = 2504730781961
Term 62 = 4052739537881
Term 63 = 6557470319842
Term 64 = 10610209857723
Term 65 = 17167680177565
Term 66 = 27777890035288
Term 67 = 44945570212853
Term 68 = 72723460248141
Term 69 = 117669030460994
Term 70 = 190392490709135
Term 71 = 308061521170129
Term 72 = 498454011879264
Term 73 = 806515533049393
Term 74 = 1304969544928657
Term 75 = 2111485077978050
Term 76 = 3416454622906707
Term 77 = 5527939700884757
Term 78 = 8944394323791464
Term 79 = 14472334024676221
Term 80 = 23416728348467685
Term 81 = 37889062373143906
Term 82 = 61305790721611591
Term 83 = 99194853094755497
Term 84 = 160500643816367088
Term 85 = 259695496911122585
Term 86 = 420196140727489673
Term 87 = 679891637638612258
Term 88 = 1100087778366101931
Term 89 = 1779979416004714189
Term 90 = 2880067194370816120
Term 91 = 4660046610375530309
Term 92 = 7540113804746346429
Term 93 = 12200160415121876738
Term 94 = 19740274219868223167
Term 95 = 31940434634990099905
Term 96 = 51680708854858323072
Term 97 = 83621143489848422977
Term 98 = 135301852344706746049
Term 99 = 218922995834555169026
Term 100 = 354224848179261915075
andrew@UBUNTU:~/Java$

Friday, 2 January 2015

Fibonacci Sequence (Part 1)

Our younger son was given a Raspberry Pi for Christmas. He loaded Python onto it and started to work out terms in the Fibonacci sequence. To my surprise, the number of significant figures provided by integer addition in Python is limited only by the amount of available memory. He was therefore able to work out the millionth term of the series and tell me that it is over 200,000 digits long. I wondered if there was any way I could check this in Java. First I wrote a simple program to calculate up to the 100th term:

andrew@UBUNTU:~/Java$ cat prog64.java
public class prog64
{
public static void main (String args[])
  {
  int x = 1;
  int y = 1;
  int term;
  for (int z=1; z<=50; z++)
    {
    term = 2*z-1;
    System.out.println("Term " + term + " = " + x);
    term++;
    System.out.println("Term " + term + " = " + y);
    x = x + y;
    y = x + y;
    }
  }
}
andrew@UBUNTU:~/Java$ javac prog64.java
andrew@UBUNTU:~/Java$ java prog64
Term 1 = 1
Term 2 = 1
Term 3 = 2
Term 4 = 3
Term 5 = 5
Term 6 = 8
Term 7 = 13
Term 8 = 21
Term 9 = 34
Term 10 = 55
Term 11 = 89
Term 12 = 144
Term 13 = 233
Term 14 = 377
Term 15 = 610
Term 16 = 987
Term 17 = 1597
Term 18 = 2584
Term 19 = 4181
Term 20 = 6765
etc

etc

It calculated the first few terms without any difficulty but ran out of significant figures while working out term 47. To make matters worse, it then gave incorrect values and did not tell me it had gone wrong:

etc
etc
Term 45 = 1134903170
Term 46 = 1836311903
Term 47 = -1323752223
Term 48 = 512559680
Term 49 = -811192543
Term 50 = -298632863
Term 51 = -1109825406
Term 52 = -1408458269
Term 53 = 1776683621
Term 54 = 368225352
etc

etc

Time for some research, I think (more to follow).

Thursday, 1 January 2015

How to Increment a Variable in Java

There are a few ways to increment a variable in Java. You can see two in prog60:

andrew@UBUNTU:~/Java$ cat prog60.java
public class prog60
{
public static void main (String args[])
  {
  int a = 1;
  a = a + 1;
  System.out.println("a = " + a);
  int b = 1;
  b += 2;
  System.out.println("b = " + b);
  }
}
andrew@UBUNTU:~/Java$ javac prog60.java
andrew@UBUNTU:~/Java$ java prog60
a = 2
b = 3
andrew@UBUNTU:~/Java$


You can also use the ++ operator before or after the variable as shown in prog61: 

andrew@UBUNTU:~/Java$ cat prog61.java
public class prog61
{
public static void main (String args[])
  {
  int c = 1;
  c++;
  System.out.println("c = " + c);
  int d = 1;
  ++d;
  System.out.println("d = " + d);
  }
}
andrew@UBUNTU:~/Java$ javac prog61.java
andrew@UBUNTU:~/Java$ java prog61
c = 2
d = 2
andrew@UBUNTU:~/Java$


The two examples in prog61 produce the same result so you might ask what is the difference between putting the ++ operator before or after the variable. If you assign the result to a second variable, putting the ++ operator before the first variable increments it before assigning it to the second variable, as you can see in prog62 below:

andrew@UBUNTU:~/Java$ cat prog62.java
public class prog62
{
public static void main (String args[])
  {
  int e = 1;
  int f;
  f = ++e;
  System.out.println("e = " + e);
  System.out.println("f = " + f);
  }
}
andrew@UBUNTU:~/Java$ javac prog62.java
andrew@UBUNTU:~/Java$ java prog62
e = 2
f = 2
andrew@UBUNTU:~/Java$


However, if you put the ++ operator after the first variable, it is assigned to the second variable before it is incremented itself. You can see what I mean in prog63 below:

andrew@UBUNTU:~/Java$ cat prog63.java
public class prog63
{
public static void main (String args[])
  {
  int g = 1;
  int h;
  h = g++;
  System.out.println("g = " + g);
  System.out.println("h = " + h);
  }
}
andrew@UBUNTU:~/Java$ javac prog63.java
andrew@UBUNTU:~/Java$ java prog63
g = 2
h = 1
andrew@UBUNTU:~/Java$