Sunday, 15 February 2015

Java Program to Find Palindromes

A palindrome is a number which has the same value whether you read its digits forwards or backwards e.g. 8, 66, 525 etc. The program below shows how you can use Java to find them. It converts the number to a string, reverses the string then tests whether the reversed string is the same as the original:

andrew@UBUNTU:~/Java$ cat palindrome.java
class palindrome     
  {
  public static void main(String args[])
    {
    for (int a=1;a<1000;a++)
      {
      String s1 = String.valueOf(a);
      String s2 = new StringBuffer(s1).reverse().toString();
      if (s1.equals(s2))
        {
        System.out.println(a + " is a palindrome");
        }
      }
    }
  }
andrew@UBUNTU:~/Java$ javac palindrome.java

andrew@UBUNTU:~/Java$ java palindrome
1 is a palindrome
2 is a palindrome
3 is a palindrome
4 is a palindrome
5 is a palindrome
6 is a palindrome
7 is a palindrome
8 is a palindrome
9 is a palindrome
11 is a palindrome
22 is a palindrome
33 is a palindrome
44 is a palindrome
55 is a palindrome
66 is a palindrome
77 is a palindrome
88 is a palindrome
99 is a palindrome
101 is a palindrome
111 is a palindrome
121 is a palindrome
131 is a palindrome
141 is a palindrome
151 is a palindrome
161 is a palindrome
171 is a palindrome
181 is a palindrome
191 is a palindrome
202 is a palindrome
212 is a palindrome
222 is a palindrome
232 is a palindrome
242 is a palindrome
252 is a palindrome
262 is a palindrome
272 is a palindrome
282 is a palindrome
292 is a palindrome
303 is a palindrome
313 is a palindrome
323 is a palindrome
333 is a palindrome
343 is a palindrome
353 is a palindrome
363 is a palindrome
373 is a palindrome
383 is a palindrome
393 is a palindrome
404 is a palindrome
414 is a palindrome
424 is a palindrome
434 is a palindrome
444 is a palindrome
454 is a palindrome
464 is a palindrome
474 is a palindrome
484 is a palindrome
494 is a palindrome
505 is a palindrome
515 is a palindrome
525 is a palindrome
535 is a palindrome
545 is a palindrome
555 is a palindrome
565 is a palindrome
575 is a palindrome
585 is a palindrome
595 is a palindrome
606 is a palindrome
616 is a palindrome
626 is a palindrome
636 is a palindrome
646 is a palindrome
656 is a palindrome
666 is a palindrome
676 is a palindrome
686 is a palindrome
696 is a palindrome
707 is a palindrome
717 is a palindrome
727 is a palindrome
737 is a palindrome
747 is a palindrome
757 is a palindrome
767 is a palindrome
777 is a palindrome
787 is a palindrome
797 is a palindrome
808 is a palindrome
818 is a palindrome
828 is a palindrome
838 is a palindrome
848 is a palindrome
858 is a palindrome
868 is a palindrome
878 is a palindrome
888 is a palindrome
898 is a palindrome
909 is a palindrome
919 is a palindrome
929 is a palindrome
939 is a palindrome
949 is a palindrome
959 is a palindrome
969 is a palindrome
979 is a palindrome
989 is a palindrome
999 is a palindrome
andrew@UBUNTU:~/Java$

Saturday, 14 February 2015

Project Euler Problem 1

If you are starting to get to grips with Java and would like to use it to solve a mathematical problem, go to Project Euler I joined recently and have just solved problem 1. As usual, click on the image to enlarge it and bring it into focus if you need to:



Saturday, 7 February 2015

Java "this" Prefix

If you have a class and a constructor method with parameter(s), you might want to use the same names for the variables in the class as you use for the parameters passed to the method. To distinguish between the two, you can prefix the variables belonging to the class with the word this. In the example below, I create a class called Square. It has a variable called width. The constructor method accepts a parameter with the same name. It then displays the value of the parameter and the initial value of the class variable. After that, it assigns the parameter value to the class variable and redisplays the class variable to show that the assignment has worked: 

Java > cat Square.java
class Square
  {
  double width;
  Square (double width)
    {
    System.out.println("width = " + width);
    System.out.println("this.width = " + this.width);
    System.out.println("Assigning parameter value");
    this.width = width;
    System.out.println("this.width = " + this.width);
    }
  }
Java > javac Square.java
Java > cat SquareExample.java
public class SquareExample
  {
  public static void main(String args[])
    {
    Square s1 = new Square(5);
    }
  }
Java > javac SquareExample.java
Java > java SquareExample
width = 5.0
this.width = 0.0
Assigning parameter value
this.width = 5.0
Java >

Wednesday, 4 February 2015

Overloaded Java Constructors

The example below shows a class with an overloaded constructor:

Java > cat Rectangle.java
class Rectangle
  {
  double width;
  double height;
  Rectangle()
    {
    width = 2;
    height = 3;
    }
  Rectangle(double w, double h)
    {
    width = w;
    height = h;
    }
  }
Java > javac Rectangle.java
Java >

If you have a class like this, when you create members, you have a choice. You can accept the default settings or you can override them by supplying parameters. In the example below, r1 takes the default settings whereas r2 uses parameters to change the width to 4 and the height to 5:

Java > cat RectangleExample.java
public class RectangleExample
  {
  public static void main(String args[])
    {
    Rectangle r1 = new Rectangle();
    System.out.println("r1 width = " + r1.width);
    System.out.println("r1 height = " + r1.height);
    Rectangle r2 = new Rectangle(4,5);
    System.out.println("r2 width = " + r2.width);
    System.out.println("r2 height = " + r2.height);
    }
  }
Java > javac RectangleExample.java
Java > java RectangleExample
r1 width = 2.0
r1 height = 3.0
r2 width = 4.0
r2 height = 5.0
Java >

Tuesday, 3 February 2015

Java Constructors

If you have a class called, for example, Rectangle, you can add a method to it with the same name as the class. This method must have no return type, not even void. It is called a constructor. Here is an example:

Java > cat Rectangle.java
class Rectangle
  {
  double width;
  double height;
  Rectangle()
    {
    width = 2;
    height = 3;
    }
  }
Java > javac Rectangle.java
Java >

The purpose of a constructor is to give default values to a class member when it is created. You can see what I mean below, where an instance of Rectangle is created. It automatically has a width of 2 and a height of 3:

Java > cat RectangleExample.java
public class RectangleExample
  {
  public static void main(String args[])
    {
    Rectangle r1 = new Rectangle();
    System.out.println("width = " + r1.width);
    System.out.println("height = " + r1.height);
    }
  }
Java > javac RectangleExample.java
Java > java RectangleExample
width = 2.0
height = 3.0
Java >

Monday, 2 February 2015

Java Curly Braces

I wanted to produce the output below 5 times:

Flip
Flop

So I tried to do it like this:

andrew@UBUNTU:~/Java$ cat Curly_Braces1.java
class Curly_Braces1
  {
  public static void main(String args[])
    {
    for (int x=1; x<=5; x++)
      System.out.println("Flip");
      System.out.println("Flop");
    }
  }
andrew@UBUNTU:~/Java$ javac Curly_Braces1.java
andrew@UBUNTU:~/Java$ java Curly_Braces1
Flip
Flip
Flip
Flip
Flip
Flop
andrew@UBUNTU:~/Java$


Java only executes one line of code each time a for loop executes. The line displaying Flop was therefore only executed once, after the for loop had finished.

To achieve the desired effect, I started the code to be executed with a left-hand curly brace and finished it with a right-hand curly brace. Java then treated the two lines as a single block of code and executed them both for every iteration of the loop:

andrew@UBUNTU:~/Java$ cat Curly_Braces2.java
class Curly_Braces2
  {
  public static void main(String args[])
    {
    for (int x=1; x<=5; x++)
      {
      System.out.println("Flip");
      System.out.println("Flop");
      }
    }
  }
andrew@UBUNTU:~/Java$ javac Curly_Braces2.java
andrew@UBUNTU:~/Java$ java Curly_Braces2
Flip
Flop
Flip
Flop
Flip
Flop
Flip
Flop
Flip
Flop
andrew@UBUNTU:~/Java$

Sunday, 1 February 2015

Java is Case Sensitive

Java is case sensitive so you can have two different variables in a program, one called xyz and another called XYZ. You can see what I mean in the example below:

andrew@UBUNTU:~/Java$ cat Case_Sensitive.java
class Case_Sensitive   
  {
  public static void main(String args[])
    {
    int xyz = 123;
    int XYZ = 234;
    System.out.println("xyz = " + xyz);
    System.out.println("XYZ = " + XYZ);
    }
  }
andrew@UBUNTU:~/Java$ javac Case_Sensitive.java
andrew@UBUNTU:~/Java$ java Case_Sensitive
xyz = 123
XYZ = 234
andrew@UBUNTU:~/Java$

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 >