JAVA TUTORIAL
The Basics

Most Java programs are made up of classes, methods, variables, conditional statements and looping statements. In Smart Hello you've seen examples of 4 out of the 5 items. The only one you haven't seen is the looping construct. We'll cover each one seperately and only the basics at this time. We'll be expanding on this as we move through the tutorial.

Variables -

Basically variables are used to keep track of information as the program is running. There are many kinds of variables. Some are boolean (true/false), int (whole numbers), some designate the length, such as int, byte, short and long (all whole numbers - but can hold different sized numbers). When you say that a variable is boolean - you are "declaring it's type" as boolean and it can only be true or false. If you declare a variable as int - then you are saying that it must be a valid whole number between -2147483648 and 2147483647.

In Java, int, boolean, char, etc are commonly referred to as Primitive Types.

Type Contains Default Size Range
boolean true/false false 1 bit NA
char Unicode character \u0000 16 bits \u0000 to \uFFFF
byte Signed integer 0 8 bits -128 to 127
short Signed integer 0 16 bits -32768 to 32767
int Signed integer 0 32 bits -2147483648 to 2147483647
long Signed integer 0 64 bits -9223372036854775808 to 9223372036854775807
float Floating point* 0.0 32 bits +-1.4E-45 to +-3.4028235E+38
double Floating point* 0.0 64 bits +-4.9E-324 to +-1.7976931348623157E+308
*Floating points - these are numbers that contain decimals. Just remember that if you need to keep track of dollars and cents in a program - you need to use a float. Only use the double for very very large numbers.

When you declare a variable - you are basically saying that this variable will hold this type of information. Here is how you declare variables in Java -

int numOfDays, daysTillBirthday;
char middleInitial;
boolean skyIsBlue= True;

Here I've declared four different variables of three different types and initialized one. Boolean has a default value of false, which I didn't want - so I initialized it to be true. If you don't think the sky is blue - then you could leave it at it's default of false. Note: All Primitive Types are lower case - if you accidently declare middleInitial as Char instead of char - the compiler will complain. Remember to be careful with case.

Classes -

Okay, what the heck is a class? Since all Java programs need at least one public class - we need to go over it. But we won't get into the details until we talk about Object Oriented Programming (OOP) later on.

Let's look at the classes we used and created in SmartHello. First we created one class ourselves - the SmartHello class. This class had to match the filename we gave our program. We also used several Java classes. These included the GregorianCalendar and NumberFormat classes. Each of these classes then is used to define a unique object. It's almost like a blue print of a car and then making a car from it. The blue print defines the class (Pontiac TransAm, Dodge Daytona, Rolls Royce), whereas the actual car is an object and is different and unique from other cars on the road.

The class contains attributes (variables) that define certain traits and methods (types of things that can either be done to it or that it can do). For instance, the car has several attributes - weight, color, number of doors, mileage, etc. It then has methods - start, stop, brake, accelerate.

Basically all programs in Java are classes. We can not do anything with SmartHello.java until we declare an object that we can reference within the program. This is what SmartHello a_SmartHello=new SmartHello(); does.

The one thing to remember about classes, until we get further along, is that they MUST create an object and through this object we can access their attributes and methods. We can only access their interal functions through an object. That's why we had to say - GregorianCalendar todaysDate=new GregorianCalendar();. GregorianCalendar is the class - todaysDate is the object. The object, in this case todaysDate, takes on all the characteristics of GregorianCalendar, but is an unique object from say - tomorrowsDate, july4thDate or myBirthdate.

Methods -

Methods, commonly referred to as functions and procedures in other languages, are made up of code that is used to perform a paticular purpose. You can see various methods in the SmartHello program such as sayGoodMorning().

There are three key parts of a method that we want to go over here. Methods can return a value, have a name and can accept arguments. The methods we created in SmartHello were pretty basic and none of them returned a value. You can tell that none of them returned a value because the return type was declared as void. Let's disect this method - private void sayTime(int hour, int minute, int am_pm). We'll go over private later - when we talk about scope. The first item after private is void, this indicates that this method does not return a value. The next part, sayTime, is it's name and then finally within the paraenthesis are the arguments. Arguments are basically values that are passed into the method so it can use them. The method name and argument types make up what is known as the method's signature. We will discuss the signature further when talk about "overloading" a method.

You may be thinking that methods are just for organizing code and making it easier to read. That's only the tip of the iceberg. One of the main reasons to break code up into methods is that that section of code can then be called over and over again without having to cut and copy everywhere. It also has a big role to play in inheritance, polymorphism and encapsilation - which we will talk about when we discuss Object Oriented Programming.

Conditional Statements-

There are several conditional statements available in Java. These statements are used to conditionally execute a section of code.

The if statement you've already been introduced to in the SmartHello program. Let's look at one of these.

if (am_pm==0)
{  am_pm_string="AM";
}
else
{  am_pm_string="PM";
}

This snippet of code is first checking if am_pm is equal to 0. If it is, then it assigns "AM" to am_pm_string. If the the value is anything other than 0 - am_pm_string will be assigned "PM". Look at the other if statements in the SmartHello program and see the different formats. For instance, this example is the only one that contains an else statement in the SmartHello program. Some of the other if statements check multiple values in the parenthesis.

Other conditional statements include the switch statement, the conditional operator and the try...catch statement.

The conditional operator is a shorthanded if statement. Here is an example of the above if statement using the conditional operator.
am_pm_string= am_pm=0 ? "AM" : "PM"

It's saying the exact same thing as the if statement - if am_pm equals zero then assign "AM" to am_pm_string, otherwise assign "PM" to am_pm_string. I don't usually use the conditional operator. I prefer the more English-like if statement.

The switch statement is used when you have a variable that you want to check against a number of values and based on those values perform some operation. WARNING: Java's switch statement does not work the same as in other languages. There are a lot of restrictions in how it can be used.

The try...catch statement is basically used when you need to make sure that a section of code executes properly. If it doesn't, then the block of code under the catch statement is executed. This is the most complicated conditional statement for people to learn. We'll go over it more when we discuss error checking and throwing exceptions.

Looping Statements -

Looping statements are actually conditional statements with one added benefit - they repeat the statements until the statement becomes false. Right now I'll just mention the different statements briefly. The looping statements include, the for statement, the while statement and the do statement.

The for statement and the while statement are the most common of the three. The for statement is generally used to execute a section of code a certain number of times.

The while statement evaluates an expression - if it's true then that section of code in the while block is executed. It will continue to loop through this code until the expression becomes false. NOTE: All for statments can be written using the while statement, but you really shouldn't. They both serve a particular purpose.

The do statement is similar to the while loop. The only difference is that the evaluation comes after the group of repeating statements. This guarantees that the statement will be executed at least once, whereas the statement block in the while loop may never be executed.

WARNING: If the looping statement's expression never becomes false the statement will end up being in what is commonly referred to as an infinite loop. If this happens you need to manually stop the program. In MsDOS/Windows this is accomplished by pressing Ctrl-C while in the MsDOS window.

 

Okay, let's take a break here from terms, defintions and concepts and look at another program. We'll be looking at this program from the ground up, starting with defining the problem and then ending up with a working program..

YearToRomanNumerals Problem ->
<-Java Tutorial - Code Style

Again if you have any questions, suggestions or problems - e-mail me at rrosetta@hsonline.net.