Tuesday, July 27, 2010

Java Learning Vids

Lesson 1

Lesson 2

Lesson 3

Lesson 4

Hello World

Mr Techednet/ First Java App

Variables, Data Types



Classes and Objects

Monday, July 26, 2010

Java Practice

Here I've compiled a few Java beginner level exercises to practice with. At the end of the post are also links to other pages with beginner level exercises. I will continue to add on more as I progress in my studies.

Level: Beginner

Focus: Basic concepts, runtime errors

Here’s a piece of code that has been saved in a file called "JollyMessage.java":

// A jolly message is written to the screen!
class Jollymessage

public static void main(String[] args) {

//Write the message to the terminal window
System.out.println("Ho Ho Ho!");


The above code will produce a runtime error message. To put it another way, a mistake has been made but it won’t be picked up when the program is compiled, only when it is run. What is the mistake and what error will be returned when the compiled code is executed?

* * * * * * *

Focus: Wrapper Classes, Primitive Data Types
Playing With Wrappers Question

Every primitive data type has a corresponding wrapper class. These classes are handy if you need to make the primitive data type into an object. However, it's important to remember that the wrapper classes are not the same as primitive data types and will act differently in certain circumstances.

In the following lines of code I've been playing with wrapper classes. The question is can you figure out what the values of the wrapper objects will be?

Boolean eminem = new Boolean("yes");

Boolean lLCoolJ = new Boolean("true");

Integer mosDef = new Integer(Integer.MAX_VALUE+1);

Long queenLatifah = new Long(Integer.MAX_VALUE+1);

Long iceCube = new Long((long)Integer.MAX_VALUE + 1);

Long jayZ = new Long(iceCube++);

Long kanyeWest = new Long(++iceCube);

Character snoopDogg = new Character("c".replace("c", "d").toCharArray()[0]);

Double theGame = new Double(Double.POSITIVE_INFINITY);

Double common = new Double (Math.round(Double.POSITIVE_INFINITY));

Integer nas = 10444;
Integer trickTrick = 10444;
Boolean lilWayne = (nas == trickTrick);

Boolean bowWow = (nas.equals(trickTrick));

* * * * * * *

Focus: Loops, Wrapper Classes, Condition Statements, Converting Strings

String Conversion Question

This programming question is all about converting Strings to numbers. The Double and Integer wrapper objects both have methods that are capable of converting a String value and you will need to employ those methods to produce the correct results.

Write a Java program that

* inputs a String from a user. Expect the String to be a series of numbers each separated by a space (e.g., "11 2 36.4 4 8.9 7.6 3 256").
* converts the String into the series of numbers that it represents.
* adds the numbers together.
* displays the result to the user.

To make things a little more interesting allow for the String to include octal and hexadecimal literals (e.g., "11 2 0xEF 36.4 4 8.9 0647 7.6 3 256").

To test the program calculate the total for the following String: "56.7 0.8 345 0xEFF 8.99 126 0647 73 5.67".

* * * * * * *

Focus: Loops
Counting Rabbits Question

In a Fibonacci sequence each number is the sum of the previous two numbers (i.e., it starts with 0,1,1,2,3,5,8 and continues on). The sequence is the result of Fibonacci's attempt in 1202 to find out how many rabbits you get after a certain number of generations. Each number represents how many pairs of rabbits there would be when they are breeding under ideal circumstances. The task is to write a program that calculates and displays the first 22 numbers of a Fibonacci sequence.

Your code will display Fibonacci's hypothesis for 20 generations of rabbits (the first two numbers represent the start of the population and the maturing of the first pair of rabbits).

* * * * * * *

Focus: Loops, Break Statement
Breaking Out Question

The focus of this programming question is on jumping out of loops. Almost always it's possible to write loops without the need for a break statement but sometimes it's convenient to do so. The following program does not contain examples of well written loops or ones that need a break statement. It's purpose is to get you thinking about how the break statement changes the logical flow of the code:

public class BreakingLoop {

public static void main(String[] args) {

int count = 0;
for (int k=5;k < 100;k++)
for (int j=3; j < 100; j++)
if (j % 2 == 0)
if (k == 67)
break loop_one;
count ++;

There are two break statements in the program, one with a label and one without. The question is for each break statement what is the next line to be executed and what is the final total of the variable count?

* * * * * * *

Focus: Binary Numbers, Bitwise Operators, Formatting Numbers
Shifting Bits Question

This programming exercise is a test of your skills at formatting binary numbers combined with using bitwise operators.

Bitwise operators interact directly with the underlying bits of a number. For example, the number 16 is the binary equivalent of 10000. The binary shift operators can be used to shift the bit pattern of a number either to the right (i.e., use the >> operator) or to the left (i.e., use the << operator). So,

int bitShift = 16;
bitShift = bitShift >> 1;

will shift the binary pattern 10000 of 16 one place to the right. The new bit pattern 1000 means the value of the variable bitShift is now 8.

The task is to write is an interactive bit shifter. The program must accept a binary number written as a String. It should then display the value of the number in denary and its binary pattern, followed by a menu of options. The menu should allow the user to:

1. Shift bits to the right
2. Shift bits to the left
3. Stop shifting

If the user picks option 1 or 2 the corresponding bit shift should occur on the number. The new value and bit pattern should be displayed to the user followed by the menu. Option 3 should stop the program. To make things a little more interesting the bit pattern must be displayed as an 8 bit number (i.e., the binary number 101 should be formatted to have 5 leading zeros 00000101).

To test the program, use the binary number 1011 as the starting value and perform one bit shift to the right followed by four bit shifts to the left. What is the final denary value and bit pattern?

* * * * * * *

Focus: Logic, Arrays, Methods
Odd Magic Square Question

I'm not really sure who first came up with a magic square. There is a story about a huge flood in China a long time ago. The people were worried they would be washed away and tried to appease the river god by making sacrifices. Nothing seemed to work until a child noticed a turtle sporting a magic square on its back that kept circling the sacrifice. The square told the people how big their sacrifice needed to be in order to save themselves. Since then magic squares have been the height of fashion for any discerning turtle.

In case you've never come across one before, a magic square is an arrangement of sequential numbers in a square so that the rows, columns and diagonals all add up to the same number. For instance, a 3x3 magic square is:

8 1 6
3 5 7
4 9 2

Each row, column and diagonal adds up to 15.

This programming exercise is concerned with creating odd sized magic squares (i.e., the size of the square can only be an odd number, 3x3, 5x5, 7x7, 9x9, and so on). The trick with making such a square is to place the number 1 in the first row and middle column. To find where to place the next number, move diagonally upwards to the right (i.e., one row up, one column across). If such a move means you fall off the square, wrap around to the row or column on the opposite side. Finally, if the move takes you to a square that is already filled, go back to the original square and move downwards by one. Repeat the process until all the squares are filled.

For example, a 3x3 magic square would start like so:

0 1 0
0 0 0
0 0 0

A move diagonally upwards means we wrap around to the bottom of the square:

0 1 0
0 0 0
0 0 2

Likewise the next diagonal move upwards means we wrap around to the first column:

0 1 0
3 0 0
0 0 2

Now the diagonal move upwards results in a square that is already filled, so we go back to where we came from and drop down a row:

0 1 0
3 0 0
4 0 2

and it continues on and on until all the squares are full.
Program Requirements:

* a user must be able to enter in the size of the magic square.
* they must only be allowed to enter in an odd number.
* use a method to create the magic square.
* use a method to display the magic square.

The question is can your program create a 5x5 magic square like the one below?

17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

Hint: Apart from the programming aspects of this exercise it's also a test of logic. Take each step of creating the magic square in turn and figure how it can be done with a two dimensional array.

* * * * * * *

* * * * * * *




Friday, July 16, 2010

Getting Started With Java

Getting Started -- Before you begin
by Peter Smaith

1. You will need a text editor to write your code. Simple editors such as gedit (on Linux) or notepad (on MS Windows) will be adequate to get you started.

2. You will need the Java development kit (JDK) to compile your code.

3. You will need the Java run-time environment installed to run your programs.

4. Alternatively you can use an integrated development environment (IDE) such as NetBeans or Eclipse. In the case of NetBeans the necessary compiler and run-time environment will be setup on your system.

Your First Java Program


This is a very simple Java program


class First


public static void main(String[] args)


System.out.println("Hello World");



To use this source code cut and paste it into your text editor and save the file as "First.java". To compile the program use the javac compiler. This translates the source code into byte code suitable for execution by the java run time environment. You need only compile the program once (after each modification). To run the program use the java command. So, to compile and run from the command line:

$javac First.java

$java First

Hello World



1. The Java compiler, javac, expects the file name with the extension java.

2. The file name must match the class name within the code (in this case First).

3. Java is case sensitive, First is different to first.

4. The java command does not expect a file extension.

Program elements


Comments are placed in the source code for the benefit of the developers and maintainers of the code. They are not executed at run time. Java supports three types of comment.

1. /* Comment style 1. These can be multiline. This type of comment is shown in the example above. */

2. /** Comment style 2 These can be multiline and are used as part of the code documentation system.*/

3. //Comment style 3. These are singe line.

The class statement

Java programs are made up of units called classes. The classes contain variables and methods to manipulate those or other variables. The example above has one class called "First". First contains one method called "main".

The main method

Every Java application has a method called main (although it is hidden in system code in many cases). The main method is the entry point of the program, that is, it is the method that is executed when the program is started. The main method is always declared public void static. This has the following effects:

* The public keyword means the method can executed from outside the class containing it.

* The void keyword means the method returns no data.

* Roughly speaking, the static keyword makes the accompanying method or variable an intrinsic property of the class. For example, an intrinsic property of a square is that it has four sides. Every square by definition has four sides. The numerical length of the sides of square is not intrinsic, different instances of a square have different sizes.

A text string is a sequence of characters, for example the text you are reading is a string. A String in Java is an object for storing and manipulating text strings. The String object stores the text as unicode characters. An array is a list of similar data items (in this case Strings) that can be accessed and manipulated by a integer index. Arrays in Java are indicated by the square brackets, "[]". A method gets information from the method that called it via its parameters. In the case of the main method the only parameter is "String[] args" this is an array of Strings called "args". In the above example we ignore parameter passed to main.

The action of our main method In the program First.java the main method simply prints the literal text string "Hello World". This is achieved by executing the "println" method in the object "out". The object "out" is a field of the class "System". Note the syntax used in the program for expressing this arrangement.


* A Java program is complied using the javac command and once compiled it can run using the java command.
* A Java program is composed of classes.
* A Java program has a method called main which is executed when the program starts.
* The main method is declared as "public static void" and takes one, argument an array of strings.

Peter Smaith has over 2o years experience in the computer industry, having worked as software engineer, manager and consultant. Peter is an occasional reviewer at http://www.review-pc.com.

Article Source: http://EzineArticles.com/?expert=Peter_Smaith