Archive for the ‘Java’ Category

Java: An Object Is A Temporary Thing

Saturday, August 1st, 2009

The real-world (meaning the world outside computer programs) is filled with what we could call objects, such as shoes, elephants, pizzas, automobiles. And many of these objects can possess a certain set of behaviors. An elephant can eat peanuts, for instance.

The philosopher Plato once described how all objects in this world were reproductions of some ideal form of that thing, subsequently called the Platonic Form. The chair in your kitchen is a human-made object, based on the ideal idea of a chair.

Objects are also a useful way of thinking about how to write computer programs. This approach called object-oriented programming.

Objects are temporary things. They exist only at run-time. The computer builds them on the fly using something called the class as the blueprint. You could think of class as the Platonic Ideal of an object. In other words, an object is an instance of a class. In Java programming, “Object” and “instance” are interchangeable things.

An object is defined in terms of two things: Its state and its behaviors. The state is what data the object holds. The behaviors are the methods, or the things it can do the data.

To create an object in Java, you first create a class file. Then, within a class file, you make a special type of method, called a constructor.

A constructor is very similar to a standard method, though you do not specify a return type. The constructors appear below the main body of the program, and are called in much the same way as a method.

Here is a program that creates two objects, from a single class:

import java.util.Scanner;

public class elephant {

public static void main(String[] args){

Scanner input = new Scanner(System.in);

System.out.print(“Enter how many hundreds of peanuts you’d like the elephant #1 to eat:”);

int eat1 = input.nextInt();

System.out.print(“Enter how many hundreds of peanuts you’d like the elephant #2 to eat:”);

int eat2 = input.nextInt();

//**Called Operators, VARIABLES elephantEat1 and
//**elephantEat2 are declared to be a TYPE of
//**elephantBlueprint.

elephantBlueprint elephantEat1;

elephantBlueprint elephantEat2;

//**In the line below an OBJECT is created, given the name //**elephantEat1, which was was defined as a type of //**elephantParts above.
//**Since it is given a set of values
//**(in the variable “eat1″), it is an object. It is also, itself, a //**variable

elephantEat1 = new elephantBlueprint(eat1);

System.out.println(“Elephant #1 has eaten this many packages of peanuts: ” +
elephantEat1.peanutsEatenPounds);

//**Here is another peanut-eating elephant, which is to say //**object, created from the same class,
//**yet has different data.

elephantEat2 = new elephantBlueprint(eat2);

System.out.println(“Elephant #2 has eaten this many packages of peanuts: ” +
elephantEat2.peanutsEatenPounds);

}
}

//**Here is the Constructor that make the elephant**/

class elephantBlueprint {

int peanutsEatenPounds;

elephantBlueprint(int eat){
peanutsEatenPounds = (eat / 50) ;
}

}

* * *

Note: The source and a working version of this pogram can be downloaded here.

RANDOM NOTES: Variables can be objects. In the above example, the objects ElephantEat1 and elephantEat2 are variables.

A word on class modifiers: These are the statements that appear before the declaration of a class. “Public” is used if the class can be accessed form elsewhere in the program. Only one “Public” declaration can be made per class, and the name of the class being named public must be the same name as the class file itself.

Material taken (& probably abused) from the book, “Introduction to Java Programming” (7th edition), by Y. Daniel Liang.



All the mistakes, however, are my own…

–Joab Jackson





JAVA: Array Basics

Friday, July 24th, 2009

Arrays can be used to keep multiple variables under a single variable name.

Defining an array is very much like defining a variable, albeit with a few modifications.

Two steps are required to initialize an array for use. They can combined later, but you should understand them separately.

First you must DECLARE an array; Then you must DEFINE one. Two different steps, see?

The basic format for DECLARING an array is here:

datatype [] variableName

Note, this is just like declaring a variable, except there is a pair of brackets (after the datatype) to signify the array-ness of the variable. Any data type that you can use for a variable, you can use for an array (string, int, etc.).

Second step: DEFINE your array:

variableName = new Datatype[size of array];

The new tells the JVM to make space in memory for the array. The size of the array tells the JVM how many spaces (of that data type) to set aside.

Here is an example of the last two steps:

int elephantWeights [];
elephantWeights = new int[10];

Also, note, you can combine the declaring and defining of an array into one step:

int [] elephantWeights = new int [10] ;

NOTE: The two data types must be the same in the above construction.

* * *

To put numbers in an array you do much the same you would for assigning a value to a variable:

[arrayname] = {[Value 1], [Value 2], etc…};

* * *

To access a particular value in the array, you call the name of the array and put the number of the array location within the bracket:

elephantWeights[4]

…will give you the contents of the 5th element in the array (Keep in mind that when the JVM allocates the spaces for each element of an array, it numbers them sequentially, beginning with “0″ rather than “1″ ).

* * *

Putting this all together, here is the working code for a basic array program:

import java.util.Scanner;

public class ArrayMagic {

public static void main(String[] args){
Scanner input = new Scanner(System.in);

int arrayMagic[];
arrayMagic = new int[3];

System.out.println(“Enter first number in an array: “);
arrayMagic[0] = input.nextInt();

System.out.println(“Enter second number in an array: “);
arrayMagic[1] = input.nextInt();

System.out.println(“Enter first number in an array: “);
arrayMagic[2] = input.nextInt();

System.out.println(“Your array consists of numbers ” + arrayMagic[0] + ” and ” + arrayMagic[1]
+ ” and ” + arrayMagic[2]);
}
}

In this command-line-based program, three numbers are collected from the user. The program then stores each one in an array called arrayMagic. It then prints them back out, calling each element in the array.

Material learned from the book, “Introduction to Java Programming” (7th edition), by Y. Daniel Liang..


……as well as from the materials of a class I am taking. All mistakes are mine..


–Joab Jackson





Java: Making a Method

Thursday, July 2nd, 2009

A programming task that is somewhat generic and is done more than once can be abstracted into what is called, in Java, a method. (In other languages, it can be called a procedure, or a function).

The method itself is a standard block of Java code. You have to DEFINE the method correctly, though. Here is how you package it:

modifier returnDataType methodName(List of parameters) {code}

The methodName is the name of this method being created. The list of parameters are the list, one by one, of the names of the input variables, preceded by their data types. The returnDataType is the data type that the method will hand back, once its finished its chore (i.e. “int”). More on the modifier later…

O.K., with that in mind, here is how you call a method, from your code:

int nameOfResultVariable = nameOfMethod(parameter, parameter, …)

When the method is called, the control of the program is shifted to the method. When the method is finished doing its thing, control is returned to the rest of the program.

The call of the method can itself be treated as a value.

Here is some sample code:

public class MethodMan {

public static void main(String[] args) {
int a = 1;
int b = 2;
int c = total (a, b);
System.out.println(c);
}

public static int total(int firstNumber, int secondNumber){
int sum;

sum = firstNumber + secondNumber;

return sum;

}

}

In this method call, we add two numbers numbers together. The numbers are declared as variables a and b. We hand a and b to a function called “total,” which requires two integers as inputs.

The function renames a and b as firstNumber and secondNumber, respectively. It adds firstNumber and secondNumber together, calling the total “sum.” Sum is returned to retuned to the main program, which is renamed as “c” and printed.

Material taken (& probably abused) from the book, “Introduction to Java Programming” (7th edition), by Y. Daniel Liang.



…as well as from the materials of a class I am taking.–Joab Jackson





Java: Embedding Applets in a Web page

Saturday, June 27th, 2009

For most Java programming classes, the programs that students write are submitted as stand-alone executables. But how does one put them on the Web and offer them as a service for others to use?

You can make an applet. An applet is a Java program that can be run from within a Web browser (on a system that runs the Java Runtime Engine [JRE] that is, which, as of this writing, the iPhone doesn’t).

Pretty much anything you can do with the Java language you can do within an Applet. Both use the Java Virtual Machine (JVM). Though setting up the program to run as an Applet is a wee bit different than setting up as a stand-alone program.

Once, embedding an Applet on a Web page was easy. You’d simply use the <Applet> tag. That W3C has deprecated that tag, which means you shouldn’t use it any longer (Though it still works in most all browsers).

Instead, you have to use either the <embed> tag for Mozilla-based browsers, and the <object> tag for Internet Explorer browsers. And, realistically, if you’re planning to have any visitors at all, you should use both.

(Before we begin, you should test to see if you have Java properly installed on your machine, go here.)


First, here is the bare-bones markup you’d use to embed your applet using the <object> tag, for IE browsers. You can put this tag within the body of the html document:

<OBJECT
classid=”clsid:8AD9C840-044E-11D1-B3E9-00805F499D93″>
<PARAM name=”code” value=”[NAME OF THE YOUR PROGRAM].class”>
</OBJECT>

The markup above was derived from this Java documentation page.

The classid tells the browser what program (In this case, the JRE) on the user’s computer should run the code being pointed to (in this case the class file). The above series of numbers tells the browser to use the latest version of the JRE, though you can also specify some specific version (see documentation). You can also use optional attributes for setting height, width or other aspects of the applet. See a list of attributes here.


For the Mozilla family of browsers, you must use the embed tag. Embed is NOT supported by Internet Explorer and it is NOT recognized by the World Wide Web Consortium (W3C), but since Firefox et al do not support the Object tag, at least for Applets, you should use the embed tag. Here is the code for the Web page, again which can appear in the body:

<embed code=”[NAME OF YOUR PROGRAM].class”
type=”application/x-java-applet;version=1.6″>
</embed>

Again there are additional options you can add in.

It is worth noting for the beginner that with both the embed tag and the object tag, supplying the correct plug-in name is crucial. In this instance, for instance, “version=1.6.0″ would NOT work. If your Web page is not running the Applet by now, it may be due to you not using the correct name. Search the Web for answers!


If you put your Java Applet out on the Web, however, you have to prepare yourself for both types of browsers. This site helpfully demonstrates how to use both with an html document:

<object
classid=”clsid:8AD9C840-044E-11D1-B3E9-00805F499D93″>
<PARAM name=”code” value=”[NAME OF YOUR PROGRAM].class”>
<comment>
<embed code=”[NAME OF YOUR PROGRAM].class”
type=”application/x-java-applet;version=1.6″>
</embed>
</comment>


You can also post your program the old fashioned (i.e. deprecated) way, through the applet tag. Most browsers still recognize the applet tag, even though is not even supported in html 4.1 or even xhtml. Here’s how:

<body>
<applet code = “[NAME OF YOUR PROGRAM].class”>
</applet>

Please to note that all the description about the applet is actually in the opening tag. So you have to put a close bracket onto the end, and then you have to do a close applet (“</applet>”) tag as well.

Within the Applet tag, you can also specify attributes like width (“width = [fill in value here]“), height (“height =”), vertical margin (“vspace =”) horizontal margin (“hspace =”), alignment (“align =”) and others. Go here for a full list of optional attributes.


What about the code itself? You would build an Applet pretty much the same way you would build a stand-alone Java program.

Just like on the command line, what gets executed is a class file (a file with a .class extension), one that has been compiled from Java source code.

In the program code itself, there doesn’t have to be a “main” method, for instance. Instead, this subclass is used:

import javax.swing.*;
public class TestApplet2 extends JApplet {
public void init() {
add (new JLabel(“Hello World”, JLabel.CENTER));
}
}

After this, control of the applet is handed by “init” “start” “stop” and “destroy” control the applet.

For the user-interface, you can use some libraries, like Swing, but more on that later. If you don’t wish to test your code through a browser each time out, you can also use the Java Applet Viewer, which is in the SDK, and can be evoked from the command line.


All the code used in this entry, including Web pages for object, embed, applet and combined tagging, as well as a sample Java program, both before and after compilation, can be found in this zipped package. –Joab Jackson





Java: The Most Basic Java Program Possible

Friday, June 12th, 2009

This is the structure of a basic Java program. It can be written in notepad , or a text editor. and compiled at the command line with the Javac compiler, which is in the Java Development Kit (JDK):

public class BasicJavaProgram {

public static void main(String[] args) {
System.out.println(“I can haz a Javur Program too!”);
}
}

Note: A copy of the working program can be found here.

To be compiled, the name of the file must have the .java extension. It must also be the same name as the “public class” declaration. So in this case, it would be BasicJavaProgram.

To break it down some:

public class BasicJavaProgram

This is the declaration of a class, in this case, the main class of the program. Think of a class as a blueprint, from which individual “instance” objects can be created. A Java program must have at least one class. Since it is a public class, it can be called from code in other classes.

The guts of class itself is contained within the set of { and } — all the action happens in-between those brackets. In this program,there is one method, called “main.” Every java program must have a “main” method–that is what the compiler looks for to run. A method is a subroutine that does a task for the class. The “public” “static” and “void” are reserved keywords that help the compiler understand the method.

Like the class itself, the method is contained within { and the } brackets (They are embedded with the classes’ own { and } brackets, so there is some recursion going on here):

{ System.out.println(“I can haz a Javur Program too!”);}

This one has the command to print out a line of text out (“I can haz a Javur Program too!”), using the print function “println” from the System.Out library of Java.

Taken from the book, “Introduction to Java Programming” (7th edition), by Y. Daniel Liang.



…as well as from the materials of a class I am taking.–Joab Jackson