Wednesday 31 December 2014

Java boolean Variable Default Value

I have read in a few places that the default value of a boolean variable is false so I decided to check for myself. My first attempt is shown in prog58 below:

andrew@UBUNTU:~/Java$ cat prog58.java
public class prog58
{
public static void main (String args[])
  {
  boolean b1;
  System.out.println("b1 is " + b1);
  }
}
andrew@UBUNTU:~/Java$ javac prog58.java
prog58.java:6: variable b1 might not have been initialized
  System.out.println("b1 is " + b1);
                                ^
1 error
andrew@UBUNTU:~/Java$


My second attempt is shown in prog59 below, which does suggest that the default value of a boolean variable is false:

andrew@UBUNTU:~/Java$ cat prog59.java
public class prog59
{
static boolean b1;
public static void main (String args[])
  {
  System.out.println("b1 is " + b1);
  }
}
andrew@UBUNTU:~/Java$ javac prog59.java
andrew@UBUNTU:~/Java$ java prog59
b1 is false
andrew@UBUNTU:~/Java$


The two programs are slightly different. Once I have worked out why one seems to work and the other does not, I will let you know.

Tuesday 30 December 2014

Java for Loop (again)

I have a book of 1001 numbered chess problems, which I work on at random. I needed a way to record which ones I had completed so I wrote the program below to print out all the numbers. I pasted them into a word processor document and printed a copy, which I keep with the book. Now, each time I solve one, I cross it off the list:

andrew@UBUNTU:~/Java$ cat prog57.java
public class prog57
{
public static void main (String args[])
  {
  int line_length = 0;
  for(int x=1;x<=1001;x++)
    {
    if (line_length > 70)
      {
      line_length = 0;
      System.out.println(x + " ");
      }
    else
      {
      System.out.print(x + " ");
      }
    if (x < 10)
      line_length += 2;
    else
      if (x < 100)
        line_length +=3;
      else
        if (x < 1000)
          line_length +=4;
        else
          line_length +=5;
    }
  System.out.println(" ");
  }
}
andrew@UBUNTU:~/Java$ javac prog57.java
andrew@UBUNTU:~/Java$ java prog57
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
1001 

andrew@UBUNTU:~/Java$

Saturday 27 December 2014

How to See the Length of an Array in Java

The simple example below creates an array of names then uses the .length method to see how long it is:

andrew@UBUNTU:~/Java$ cat prog56.java
public class prog56
{
public static void main (String args[])
  {
  String[] names =
  {"Andrew", "Brian", "Colin"};
  System.out.println
  ("names has " + names.length + " entries");
  }
}
andrew@UBUNTU:~/Java$ javac prog56.java
andrew@UBUNTU:~/Java$ java prog56
names has 3 entries
andrew@UBUNTU:~/Java$

Friday 26 December 2014

Joining Java Conditional Statements With & And &&

Program prog53 below checks whether string my_name is more than 6 characters long. If so, it then looks to see if the seventh character is an X. The two conditional statements are joined by && so the second test is only carried out if the first is true:

andrew@UBUNTU:~/Java$ cat prog53.java
public class prog53
{
public static void main (String args[])
  {
  String my_name = "Andrew";
  if ((my_name.length() > 6)
  &&  (my_name.charAt(6) == 'X'))
    System.out.println ("7th character = X");
  else
    System.out.println ("7th character not = X");
  }
}
andrew@UBUNTU:~/Java$ javac prog53.java
andrew@UBUNTU:~/Java$ java prog53
7th character not = X
andrew@UBUNTU:~/Java$


Program prog54 does the tests in the wrong order and produces a run-time error:

andrew@UBUNTU:~/Java$ cat prog54.java
public class prog54
{
public static void main (String args[])
  {
  String my_name = "Andrew";
  if ((my_name.charAt(6) == 'X')
  &&  (my_name.length() > 6))
    System.out.println ("7th character = X");
  else
    System.out.println ("7th character not = X");
  }
}
andrew@UBUNTU:~/Java$ javac prog54.java
andrew@UBUNTU:~/Java$ java prog54
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
    at java.lang.String.charAt(String.java:694)
    at prog54.main(prog54.java:6)
andrew@UBUNTU:~/Java$


Program prog55 is similar to prog53 but joins the two conditional statements with & (a single ampersand). This evaluates the 2nd conditional statement even if the first is false so it also produces a run-time error:

andrew@UBUNTU:~/Java$ cat prog55.java
public class prog55
{
public static void main (String args[])
  {
  String my_name = "Andrew";
  if ((my_name.length() > 6)
   &  (my_name.charAt(6) == 'X'))
    System.out.println ("7th character = X");
  else
    System.out.println ("7th character not = X");
  }
}
andrew@UBUNTU:~/Java$ javac prog55.java
andrew@UBUNTU:~/Java$ java prog55
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
    at java.lang.String.charAt(String.java:694)
    at prog55.main(prog55.java:6)
andrew@UBUNTU:~/Java$

Wednesday 24 December 2014

Golden Ratio

Given a rectangle with sides of length a and b, where a > b, the ratio of its sides is a/b. If you join a square to it with sides of length a to create a new rectangle, the ratio of its sides will be (a+b)/a. If a/b = (a+b)/a, this is known as the golden ratio. Here is a picture, which I copied from Wikipedia, to illustrate the concept:
The program below starts off with 1.5 as an approximation to the golden ratio then uses iteration to get as close as possible to the true value:
 
Java > cat golden_ratio.java
public class golden_ratio
{
public static void main (String args[])
  {
  double ratio1;
  double ratio2;
  double ratio3 = 1.5d;
  double difference;
  double percentage_difference;
  int iterations = 0;
  do
    {
    ratio1 = ratio3;
    ratio2 = 1 / (ratio1 - 1);
    ratio3 = (ratio1 + ratio2) / 2d;
    difference = Math.abs (ratio3 - ratio1);
    percentage_difference = difference / ratio3 * 100d;
    iterations++;
    }
  while (percentage_difference > 0.0000000000001d);
  System.out.println ("Golden ratio is " + ratio3);
  System.out.println ("Iterations = " + iterations);
  }
}
Java > javac golden_ratio.java
Java > java golden_ratio
Golden ratio is 1.6180339887498956
Iterations = 155
Java >

Tuesday 23 December 2014

= and == in Java

In Java, the equals sign (=) is used to assign a value to a variable. Two consecutive equals signs (==) are used to check for equality. You can see what I mean in the example below:

andrew@UBUNTU:~/Java$ cat prog52.java
public class prog52
{
public static void main (String args[])
  {
  int one = 1;
  System.out.println ("one = " + one);
  int two = 2;
  if (two == 2)
    System.out.println ("two = 2");
  else
    System.out.println ("two does not equal 2");
  }
}
andrew@UBUNTU:~/Java$ javac prog52.java
andrew@UBUNTU:~/Java$ java prog52
one = 1
two = 2
andrew@UBUNTU:~/Java$

Sunday 21 December 2014

Precision in Floating Point Numbers in Java

A float is a single-precision floating-point number. A double is a double-precision floating-point number. I read somewhere that computers cannot store floating-point numbers precisely so I checked this out myself in program prog51:

andrew@UBUNTU:~/Java$ cat prog51.java
public class prog51
{
public static void main (String args[])
  {
  float f1 = 81.3f * 1.94f;
  System.out.println ("f1 = " + f1);
  double d1 = 81.3d * 1.94d;
  System.out.println ("d1 = " + d1);
  }
}
andrew@UBUNTU:~/Java$ javac prog51.java
andrew@UBUNTU:~/Java$ java prog51
f1 = 157.72202
d1 = 157.72199999999998
andrew@UBUNTU:~/Java$


Judging by this, neither of these data types would be suitable for applications where accuracy is important such as the production of bank statements. The only way I found to calculate the correct answer to the multiplication sum above was as shown in prog52:

andrew@UBUNTU:~/Java$ cat prog52.java
public class prog52
{
public static void main (String args[])
  {
  float f1 = 813f * 194f / 1000f;
  System.out.println ("f1 = " + f1);
  double d1 = 813d * 194d / 1000d;
  System.out.println ("d1 = " + d1);
  }
}
andrew@UBUNTU:~/Java$ javac prog52.java
andrew@UBUNTU:~/Java$ java prog52
f1 = 157.722
d1 = 157.722
andrew@UBUNTU:~/Java$


When I find a better way, I will let you know.

Saturday 20 December 2014

Java switch Statement

This is a variation on the previous post but using the switch statement instead of if / else if / else. You can use the switch statement to compare a variable with a series of fixed values preceded by the word case. Specific actions can be carried out after each case statement if the variable matches the value specified. The default statement at the end says what to do if the variable does not match any of the values provided: 

andrew@UBUNTU:~/Java$ cat prog50.java
import java.util.Random;
public class prog50
{
public static void main (String args[])
 {
 int zero = 0;
 int one = 0;
 int two = 0;
 Random random_number = new Random();
 int upper_limit = 3;
 int x;
 for(x=1;x<=30000;x++)
  {
  int y = random_number.nextInt(upper_limit);
  switch (y)
   {
   case 0:
    zero++;
    break;
   case 1:
    one++;
    break;
   case 2:
    two++;
    break;
   default:
    System.out.println("Program error");
    break;
   }
  }
 System.out.println("Number of 0's = " + zero);
 System.out.println("Number of 1's = " + one);
 System.out.println("Number of 2's = " + two);
 }
}
andrew@UBUNTU:~/Java$ javac prog50.java
andrew@UBUNTU:~/Java$ java prog50
Number of 0's = 9989
Number of 1's = 10109
Number of 2's = 9902
andrew@UBUNTU:~/Java$

Friday 19 December 2014

Combining Java Conditional Statements With Else

The program below uses IF, ELSE IF and ELSE to test the distribution of random numbers produced by Java: 

Java > cat prog49.java
public class prog49
{
public static void main (String args[])
 {
 int one = 0;
 int two = 0;
 int three = 0;
 int x;
 for(x=1;x<=30000;x++)
  {
  int random1 = (int)(Math.random()*3)+1;
  if (random1 == 1)
   one++;
  else
  if (random1 == 2)
    two++;
   else
    if (random1 == 3)
     three++;
    else
     System.out.println("Program error");
  }
 System.out.println("Number of 1's = " + one);
 System.out.println("Number of 2's = " + two);
 System.out.println("Number of 3's = " + three);
 }
}
Java > javac prog49.java
Java > java prog49
Number of 1's = 9986
Number of 2's = 10053
Number of 3's = 9961
Java >

Another Way to Seed the Random Number Generator

You can also seed the random number generator by using the setSeed method as shown below. This way makes it easy to create a given set of random numbers more than once in the same program run:

Java > cat prog48.java
import java.util.Random;
public class prog48
{
public static void main (String args[])
 {
 Random random_number = new Random();
 System.out.println("Seeding random_number");
 random_number.setSeed(123);
 System.out.println("Random number 1 = "
 + random_number.nextInt());
 System.out.println("Random number 2 = "
 + random_number.nextInt());
 System.out.println("Random number 3 = "
 + random_number.nextInt());
 System.out.println("Reseeding random_number");
 random_number.setSeed(123);
 System.out.println("Random number 4 = "
 + random_number.nextInt());
 System.out.println("Random number 5 = "
 + random_number.nextInt());
 System.out.println("Random number 6 = "
 + random_number.nextInt());
 }
}
Java > javac prog48.java
Java > java prog48
Seeding random_number
Random number 1 = -1188957731
Random number 2 = 1018954901
Random number 3 = -39088943
Reseeding random_number
Random number 4 = -1188957731
Random number 5 = 1018954901
Random number 6 = -39088943
Java >

Wednesday 17 December 2014

How to Seed the Random Number Generator in Java

When you use a computer to produce random numbers, they are not really random in the way that tossing a coin or throwing a dice are. They are just a sequence of pseudo-random numbers generated by a function.

You can produce random numbers as shown in prog45 below. The random number generator then decides for itself where to start in the sequence so a different set of random numbers is produced each time you run the program:

andrew@UBUNTU:~/Java$ cat prog45.java
import java.util.Random;
public class prog45
{
public static void main (String args[])
 {
 Random random1 = new Random();
 System.out.println("Random number 1: "
 + random1.nextDouble());
 System.out.println("Random number 2: "
 + random1.nextDouble());
 }
}
andrew@UBUNTU:~/Java$ javac prog45.java
andrew@UBUNTU:~/Java$ java prog45
Random number 1: 0.9759678541914762
Random number 2: 0.03779439928385264
andrew@UBUNTU:~/Java$ java prog45
Random number 1: 0.16178369817427063
Random number 2: 0.6776376518531995
andrew@UBUNTU:~/Java$ java prog45
Random number 1: 0.9896967917912625
Random number 2: 0.2914450715965342
andrew@UBUNTU:~/Java$


Alternatively, you can seed the random number generator when you create a variable as shown in bold in prog46. This tells Java where to start in the sequence so it produces the same set of random numbers each time you run the program:

andrew@UBUNTU:~/Java$ cat prog46.java
import java.util.Random;
public class prog46
{
public static void main (String args[])
 {
 Random random1 = new Random(1);
 System.out.println("Random number 1: "
 + random1.nextDouble());
 System.out.println("Random number 2: "
 + random1.nextDouble());
 }
}
andrew@UBUNTU:~/Java$ javac prog46.java
andrew@UBUNTU:~/Java$ java prog46
Random number 1: 0.7308781907032909
Random number 2: 0.41008081149220166
andrew@UBUNTU:~/Java$ java prog46
Random number 1: 0.7308781907032909
Random number 2: 0.41008081149220166
andrew@UBUNTU:~/Java$


If you use a different number to seed the random number generator, you get a different series of random numbers:

andrew@UBUNTU:~/Java$ cat prog47.java
import java.util.Random;
public class prog47
{
public static void main (String args[])
 {
 Random random1 = new Random(999);
 System.out.println("Random number 1: "
 + random1.nextDouble());
 System.out.println("Random number 2: "
 + random1.nextDouble());
 }
}
andrew@UBUNTU:~/Java$ javac prog47.java
andrew@UBUNTU:~/Java$ java prog47
Random number 1: 0.7106328293942568
Random number 2: 0.7271143712820883
andrew@UBUNTU:~/Java$ java prog47
Random number 1: 0.7106328293942568
Random number 2: 0.7271143712820883
andrew@UBUNTU:~/Java
$