Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, 2 October 2021

Fifteen (Part 1)

As a child I had a puzzle made of sliding plastic tiles in a 4x4 grid. I can no longer find it so I have to assume it has been lost, given away or broken and thrown away (I rarely throw things away if they aren't broken). Here is a picture of a similar puzzle, which I found elsewhere on the Internet:

This one retails at £270.92, which seems excessive but when I looked more closely I saw that it measures 50cm x 50cm x 5cm, which is much larger than normal and probably explains why it costs so much.

The objective of the puzzle is to slide the numbers around until they are in numerical order as shown below:

There are also several versions of this puzzle to play online. I have been teaching myself Java from a book for a while so I decided to create one of my own. I found the source code for a 3x3 version and tried it out. I found that I could not click on the X in the top right hand corner of the screen to close the application so I added code to do this. Then I changed it to a 4x4 version and mixed up the starting sequence of the numbers so that it looked like this:


If you would like to run it yourself, you will need a PC with Java installed. Copy the source code, which is at the end of this post, into a text file called Fifteen.java and run it like this:

andrew@ASUS-Laptop:~/Java$ javac Fifteen.java
andrew@ASUS-Laptop:~/Java$ java Fifteen

import java.awt.*;  
import java.awt.event.*;  
import javax.swing.JOptionPane;  
public class Fifteen extends Frame implements WindowListener, ActionListener
{  
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16;  
Fifteen()
    {  
    super("Fifteen");  
    b1=new Button();  
    b1.setBounds(50,100,40,40);  
    b2=new Button();  
    b2.setBounds(100,100,40,40);  
    b3=new Button();  
    b3.setBounds(150,100,40,40);  
    b4=new Button();  
    b4.setBounds(200,100,40,40);  
    b5=new Button();  
    b5.setBounds(50,150,40,40);  
    b6=new Button();  
    b6.setBounds(100,150,40,40);  
    b7=new Button();  
    b7.setBounds(150,150,40,40);  
    b8=new Button();  
    b8.setBounds(200,150,40,40);  
    b9=new Button();  
    b9.setBounds(50,200,40,40);  
    b10=new Button();  
    b10.setBounds(100,200,40,40);  
    b11=new Button();  
    b11.setBounds(150,200,40,40);  
    b12=new Button();  
    b12.setBounds(200,200,40,40);  
    b13=new Button();  
    b13.setBounds(50,250,40,40);  
    b14=new Button();  
    b14.setBounds(100,250,40,40);  
    b15=new Button();  
    b15.setBounds(150,250,40,40);  
    b16=new Button();  
    b16.setBounds(200,250,40,40);  

    b1.setLabel("6");
    b2.setLabel("7");
    b3.setLabel("4");
    b4.setLabel("11");
    b5.setLabel("2");
    b6.setLabel("1");
    b7.setLabel("15");
    b8.setLabel("10");
    b9.setLabel("13");
    b10.setLabel("5");
    b11.setLabel("");
    b12.setLabel("3");
    b13.setLabel("9");
    b14.setLabel("14");
    b15.setLabel("12");
    b16.setLabel("8");
      
    b1.addActionListener(this);  
    b2.addActionListener(this);  
    b3.addActionListener(this);  
    b4.addActionListener(this);  
    b5.addActionListener(this);  
    b6.addActionListener(this);  
    b7.addActionListener(this);  
    b8.addActionListener(this);  
    b9.addActionListener(this);  
    b10.addActionListener(this);  
    b11.addActionListener(this);  
    b12.addActionListener(this);  
    b13.addActionListener(this);  
    b14.addActionListener(this);  
    b15.addActionListener(this);  
    b16.addActionListener(this);  
      
    add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);  
    add(b9);add(b10);add(b11);add(b12);add(b13);add(b14);add(b15);add(b16);  
    setSize(400,400);  
    setLayout(null);  
    setVisible(true);  
    addWindowListener(this);
    }  
public void windowClosing(WindowEvent x)
    {
    dispose();
    System.exit(0);
    }
public void windowActivated(WindowEvent x) { }
public void windowDeactivated(WindowEvent x) { }
public void windowOpened(WindowEvent x) { }
public void windowClosed(WindowEvent x) { }
public void windowIconified(WindowEvent x) { }
public void windowDeiconified(WindowEvent x) { }
public void actionPerformed(ActionEvent e)
    {  
    if(e.getSource()==b1)
        {  
        String label=b1.getLabel();  
        if(b2.getLabel().equals(""))
            {  
            b2.setLabel(label);  
            b1.setLabel("");  
            }  
        if(b5.getLabel().equals(""))
            {  
            b5.setLabel(label);  
            b1.setLabel("");  
            }  
        }  
    if(e.getSource()==b2)
        {  
        String label=b2.getLabel();  
        if(b1.getLabel().equals(""))
            {  
            b1.setLabel(label);  
            b2.setLabel("");  
            }  
        if(b3.getLabel().equals(""))
            {  
            b3.setLabel(label);  
            b2.setLabel("");  
            }  
        if(b6.getLabel().equals(""))
            {  
            b6.setLabel(label);  
            b2.setLabel("");  
            }  
        }  
    if(e.getSource()==b3)
        {  
        String label=b3.getLabel();  
        if(b2.getLabel().equals(""))
            {  
            b2.setLabel(label);  
            b3.setLabel("");  
            }  
        if(b4.getLabel().equals(""))
            {  
            b4.setLabel(label);  
            b3.setLabel("");  
            }  
        if(b7.getLabel().equals(""))
            {  
            b7.setLabel(label);  
            b3.setLabel("");  
            }  
        }  
    if(e.getSource()==b4)
        {  
        String label=b4.getLabel();  
        if(b3.getLabel().equals(""))
            {  
            b3.setLabel(label);  
            b4.setLabel("");  
            }  
        if(b8.getLabel().equals(""))
            {  
            b8.setLabel(label);  
            b4.setLabel("");  
            }  
        }  
    if(e.getSource()==b5)
        {  
        String label=b5.getLabel();  
        if(b1.getLabel().equals(""))
            {  
            b1.setLabel(label);  
            b5.setLabel("");  
            }  
        if(b6.getLabel().equals(""))
            {  
            b6.setLabel(label);  
            b5.setLabel("");  
            }  
        if(b9.getLabel().equals(""))
            {  
            b9.setLabel(label);  
            b5.setLabel("");  
            }  
        }  
    if(e.getSource()==b6)
        {  
        String label=b6.getLabel();  
        if(b2.getLabel().equals(""))
            {  
            b2.setLabel(label);  
            b6.setLabel("");  
            }  
        if(b5.getLabel().equals(""))
            {  
            b5.setLabel(label);  
            b6.setLabel("");  
            }  
        if(b7.getLabel().equals(""))
            {  
            b7.setLabel(label);  
            b6.setLabel("");  
            }  
        if(b10.getLabel().equals(""))
            {  
            b10.setLabel(label);  
            b6.setLabel("");  
            }  
        }  
    if(e.getSource()==b7)
        {  
        String label=b7.getLabel();  
        if(b3.getLabel().equals(""))
            {  
            b3.setLabel(label);  
            b7.setLabel("");  
            }  
        if(b6.getLabel().equals(""))
            {  
            b6.setLabel(label);  
            b7.setLabel("");  
            }  
        if(b8.getLabel().equals(""))
            {  
            b8.setLabel(label);  
            b7.setLabel("");  
            }  
        if(b11.getLabel().equals(""))
            {  
            b11.setLabel(label);  
            b7.setLabel("");  
            }  
        }  
    if(e.getSource()==b8)
        {  
        String label=b8.getLabel();  
        if(b4.getLabel().equals(""))
            {  
            b4.setLabel(label);  
            b8.setLabel("");  
            }  
        if(b7.getLabel().equals(""))
            {  
            b7.setLabel(label);  
            b8.setLabel("");  
            }  
        if(b12.getLabel().equals(""))
            {  
            b12.setLabel(label);  
            b8.setLabel("");  
            }  
        }  
    if(e.getSource()==b9)
        {  
        String label=b9.getLabel();  
        if(b5.getLabel().equals(""))
            {  
            b5.setLabel(label);  
            b9.setLabel("");  
            }  
        if(b10.getLabel().equals(""))
            {  
            b10.setLabel(label);  
            b9.setLabel("");  
            }  
        if(b13.getLabel().equals(""))
            {  
            b13.setLabel(label);  
            b9.setLabel("");  
            }  
        }  
    if(e.getSource()==b10)
        {  
        String label=b10.getLabel();  
        if(b6.getLabel().equals(""))
            {  
            b6.setLabel(label);  
            b10.setLabel("");  
            }  
        if(b9.getLabel().equals(""))
            {  
            b9.setLabel(label);  
            b10.setLabel("");  
            }  
        if(b11.getLabel().equals(""))
            {  
            b11.setLabel(label);  
            b10.setLabel("");  
            }  
        if(b14.getLabel().equals(""))
            {  
            b14.setLabel(label);  
            b10.setLabel("");  
            }  
        }  
    if(e.getSource()==b11)
        {  
        String label=b11.getLabel();  
        if(b7.getLabel().equals(""))
            {  
            b7.setLabel(label);  
            b11.setLabel("");  
            }  
        if(b10.getLabel().equals(""))
            {  
            b10.setLabel(label);  
            b11.setLabel("");  
            }  
        if(b12.getLabel().equals(""))
            {  
            b12.setLabel(label);  
            b11.setLabel("");  
            }  
        if(b15.getLabel().equals(""))
            {  
            b15.setLabel(label);  
            b11.setLabel("");  
            }  
        }  
    if(e.getSource()==b12)
        {  
        String label=b12.getLabel();  
        if(b8.getLabel().equals(""))
            {  
            b8.setLabel(label);  
            b12.setLabel("");  
            }  
        if(b11.getLabel().equals(""))
            {  
            b11.setLabel(label);  
            b12.setLabel("");  
            }  
        if(b16.getLabel().equals(""))
            {  
            b16.setLabel(label);  
            b12.setLabel("");  
            }  
        }  
    if(e.getSource()==b13)
        {  
        String label=b13.getLabel();  
        if(b9.getLabel().equals(""))
            {  
            b9.setLabel(label);  
            b13.setLabel("");  
            }  
        if(b14.getLabel().equals(""))
            {  
            b14.setLabel(label);  
            b13.setLabel("");  
            }  
        }  
    if(e.getSource()==b14)
        {  
        String label=b14.getLabel();  
        if(b10.getLabel().equals(""))
            {  
            b10.setLabel(label);  
            b14.setLabel("");  
            }  
        if(b13.getLabel().equals(""))
            {  
            b13.setLabel(label);  
            b14.setLabel("");  
            }  
        if(b15.getLabel().equals(""))
            {  
            b15.setLabel(label);  
            b14.setLabel("");  
            }  
        }  
    if(e.getSource()==b15)
        {  
        String label=b15.getLabel();  
        if(b11.getLabel().equals(""))
            {  
            b11.setLabel(label);  
            b15.setLabel("");  
            }  
        if(b14.getLabel().equals(""))
            {  
            b14.setLabel(label);  
            b15.setLabel("");  
            }  
        if(b16.getLabel().equals(""))
            {  
            b16.setLabel(label);  
            b15.setLabel("");  
            }  
        }  
    if(e.getSource()==b16)
        {  
        String label=b16.getLabel();  
        if(b12.getLabel().equals(""))
            {  
            b12.setLabel(label);  
            b16.setLabel("");  
            }  
        if(b15.getLabel().equals(""))
            {  
            b15.setLabel(label);  
            b16.setLabel("");  
            }  
        }  
    // Check if game is complete:
    if(b1.getLabel().equals("1")&&b2.getLabel().equals("2")
        &&b3.getLabel().equals("3")&&b4.getLabel().equals("4")   
        &&b5.getLabel().equals("5")&&b6.getLabel().equals("6")
        &&b7.getLabel().equals("7")&&b8.getLabel().equals("8")    
        &&b9.getLabel().equals("9")&&b10.getLabel().equals("10")
        &&b11.getLabel().equals("11")&&b12.getLabel().equals("12")    
        &&b13.getLabel().equals("13")&&b14.getLabel().equals("14")
        &&b15.getLabel().equals("15"))  
        {
        JOptionPane.showMessageDialog(this,"Well done!");    
        }    
}  
public static void main(String[] args)
    {  
    new Fifteen();  
    }  
}

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, 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$

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$