Core Java 2 - Volume I - Fundamentals, 5th Ed.

Fundamental Programming Structures

 Comments | Variables | Assignments and Inits | Operators | Strings | Control Flow | Big Numbers | Arrays

A Simple Java Program

As is the norm the book starts out with a "hello world" and describes it as best they can with the limited knowledge you're supposed to have at this point

public class FirstSample
  {
    public static void main(String[] args)
    {
       System.out.println("We will not use 'Hello World');
    }
  }

 They point out that Java is case sensitive, everything is inside a class in Java (as opposed to C++) and the code must be kept in a file named FirstSample.java to be compiled correctly.  So far this isn't brain surgery.  We'll get to the rest later, but for right now just consider the above a single line program with a print statement in it. 

Comments

You can use the // just like you do in C++.  You can also use /* */ if you want to create a comment block.  Lastly, you can use /** and */ if you want to take advantage of the automatic documentation generation feature, but that's in chapter four.  For now use //...  ;-)

Data Types

Now we're making progress.  There are eight primitive types in Java.  Java is very strongly typed.   All variables must  be declared with a type.  There are four kinds of integers, two kinds of floats, a char and a Boolean.

Integers types

int - 4 bytes

short - 2 bytes

long - 8 bytes

byte - 1 byte

You do the binary arithmetic if you want to puzzle out the ranges.  You know the deal.  If it's a variable for someone's age than byte will handle it (-128 thru 127), but if it's normal just use int.  If you know you're dealing with a monster number but won't need floating point operations then use long.

Now, this stuff is NOT platform dependant.  It does not matter what system you're on, if it's Java then the above holds true (this is different from C++ which uses whatever the proc maker denotes for these values, some ints are 8 bytes and some are 4, go figure)

longs have a suffix of L, and if you wanna get nutty you can prefix a number with 0x for a hexadecimal and 0 for an octal.  We'll worry about these guys later.

Floating Point Types

float - 4 bytes, 6-7 decimals of precision

double - 8 bytes, 15 decimals of precision

These are the guys you want to use for decimal mathematics.  Unless you're doing weather simulations you rarely have to worry about double, but show offs use it anyway.  In Java it's used because a float var ends in F, while a double has no suffix, but you can supply the D if you like.

Be aware of the IEEE (did you pay your dues) spec 754 and the three special types, positive infinity, negative infinity, and NaN (not-a-number) for 0/0 or square rooting negatives.

Character type

Just a single char denoted by single quotes ' '.  Not to be confused with a single character String type, (not a primitive but an instance of the String class, more later) denoted by double quotes " ".  The chars denote characters in the Unicode encoding scheme.  Unicode is a 2 byte scheme (like ASCII but you have another byte) so you can represent all characters around the world.  Unless you write programs for international use don't go nuts about not knowing Unicode.  There are also special characters that all the C people will recognize \b, \t, \n, etc...

Boolean Type

True or false.  That's it.  One byte.  NOT THE SAME AS C++.  In Java, unlike C/C++, you can't test everything and it's mother for truth.  If you test x=0 in Java the compiler will look at you like you have five heads.  This feature lets the compiler catch (x=0) when you meant (x==0) and keeps your x variable from being assigned a donut accidentally.  You use a Boolean to test logical conditions and assign variables using "true" or "false". 

Variables

Every variable needs a type, must start with a letter, must not be a Java keyword, and is essentially unlimited in length (make it readable though, huh?).  Remember that we're dealing with Unicode here so a var like 

MetalBand  MÖTLEY_CRÜE;

is tres doable with the umlauts, but you usually wouldn't run into this.  Don't use operators or copyright symbols, just make sure it's something that's used as a letter in a language somewhere.

You can have multiple declarations on one line...

int  Num1, Num2, Num3;

but the authors recommend against it and I kinda agree.  Makes a prog more readable to give each variable it's own line and gives you the option to toss in a comment.

Good idea to use a naming convention so you don't come back to the code a year from now and have no clue what things are.  Go learn what Hungarian notation is (this is a Windows thing so the Sun boys won't mention it) and use that, trust me it helps.

And be descriptive.  Num1 = Num2 + Bob; is a recipe for confusion.  Salary = bonus + wage; butters the biscuit much more smoothly, eh?

Assignments and Initializations

Real easy.  

int vacationdays;  // this is a declaration
vacationdays = 12;  // this is an assignment

Java, like C++, lets you do both at the same time.

int vacationdays = 12;

You can declare and assign a variable anywhere in your code.

Constants

Use the keyword final

final double CM_PER_INCH;

Don't mistake this for a class constant.  You use static for this.

const is a keyword in Java but it's no longer used for anything.

Operators

Arithmetic - + , - , * , / , %

Increment & Decrement - ++,-- (post and pre)

Relational and Boolean - ==, !=, >, <, <=, >=, &&, ||, plus ternary ?

Bitwise - &, |, ^ (xor), ~(not) plus shifts <<, >>

Mathematical Functions and Constants

the Math class uses a host of functions to help you along.

Math.sqrt(), Math.pow() + trig, Math.sin(), Math.cos(), etc...

plus the constants - Math.PI & Math.E (pretty cool)

See book for legal conversions into other types.

Casting works like old pre ansi C++

int nx = (int) x;

but you lose data.  There's a better way that's discussed later.

Check out the Precedence page for operator precedence.

Strings

Strings are just a sequence of characters.  They are not a built in type but the Java library includes a String class so you grab an instance of it for your strings.  DO NOT THINK OF STRINGS IN JAVA AS STRINGS IN C++!! They are more like char pointers then an array.  Strings in Java are immutable.  Check out the API for all the functions you can use for concatenation, substrings, the + operator, and extraction.  

Never use the == to see if two strings are equal! Use the String.equals() method of the String class.  The == compares pointers so if they're in the same location (impossible unless an object var holding the location of your instance) then you'll return true.  Just think of String names as pointers and you'll be OK.  Think of it as using the ansi C++ string class but you can't change individual chars. ( you can always create a new one the way you want it so calm down)

We read input with 

String input =  JOptionPane.showInputDialog("blah, blah");
int age = Integer.parseInt(input);

so far.  You'll understand this better later.  It creates a dialog box that takes a string then you take the string and make it a variable for computations.  Ain't programmin fun?  I did this from the book...

// Core Java One book.  Chapter 2
// Just getting some sea legs...

package MyJava;
import javax.swing.*;

public class InputTest
{
    public static void main(String[] args)
    {
        // get the first input....java's easy
        String name = JOptionPane.showInputDialog("What is your name?:");
        
        // get the second input
        String input = JOptionPane.showInputDialog("What is your age?:");
        
        // convert the age string to an interger
        int age = Integer.parseInt(input);
        
        // display to the console
        System.out.println("Hello, " + name + ". Next year you will be " + ++age + " years old!");
        
        // out
        System.exit(0);
    }
}

Nothing special as you can see.  Not hard, right?

Also be aware of the NumberFormat class in the java.text package.  Used for numbers, currency, etc.

Control Flow

Block scope.  Ready for this...

public static void main(String[] args)
  {
     int n;
       . . .
       {
        int k;
        int n // NOT ALLOWED!!!
       }
  }      

How's that grab you?  Not allowed to redefine vars inside a block.  This is obviously NOT LIKE C++!  You will throw an error if you try it.  Variables lose scope after the block completes just like C++ though.

Conditional flow controls

Same as C++.

if .. else (yes, you can nest to your heart's content.)

while .. do

do .. while

for ( counter declr; condition; change counter) 

This code shows how to use the indeterminate while loop...

package MyJava;

import javax.swing.*;

public class Retirement
{
    public static void main(String[] args)
     {
        // read inputs
        String input = JOptionPane.showInputDialog
                       ("How much do you need to retire? : ");
        double goal = Double.parseDouble(input);
        
        input = JOptionPane.showInputDialog
                       ("How much will you contribute each year? : ");
        double contrib = Double.parseDouble(input);
        
        input = JOptionPane.showInputDialog
                       ("Interest rate in % : ");
        double rate = Double.parseDouble(input);
        
        double balance = 0;
        int years = 0;
        
        // update the balance while the goal isn't reached
        
        while (balance < goal)
        {
            // add this year's payment and interest
            
            balance += contrib;
            double interest = balance * rate / 100;
            balance += interest;
            System.out.println(" Balance is " + balance + " for year " + years);
            
            years++;
            
        }
        
        System.out.println("You can retire in " + years + " years.");
        System.exit(0);
    }
}

Again, nothing to write home about...

You also have a switch statement with the exact syntax as C++.

You don't have a goto (if you need one go become a plumber) but you do have a break that can go to a label and not just end a block.  You also have a continue.

Big Numbers

Just be aware that if you need an integer that's out of this world the java.math package can help you with two classes called BigInteger and BigDecimal.  They're for numbers with arbitrarily looong digit sequences and it's here we discover that java has NO OPERATOR OVERLOADING.  Always a little over estimated in my view anyway, so just use the add() and multiply() and other methods provided by these classes.  Nuff said.

Arrays

Don't let arrays drive you nuts.  Simple arrays hold collections of data of the same type.  You access each individual data item with an integer index.  You declare them like this

int[] a;  // you can also declare it like this...  int a[]  Java don't care!

Voila, but that's not it!  Now you have an array variable.  Now you have to give it an array!

int[] a = new int[100];

Now you have an array with 100 elements.  Remember, you're a computer geek so start counting with 0 and not 1.  Java has very strict bounds checking so you'll throw an error (runtime) if you try to go out of bounds.  If you're a C++ person then you like this a lot. 

you can use 

a.length; 

to find out the length of your array, but you should know.  All arrays lengths are unchangeable after you declare them.  If you want a dynamic array check out the array list data structure later in the show.

You can init an array like you do in C++ 

int[] a = { 1,2,3,4,5,6 };

and the length is 6 (0-5).

If you want to copy an array don't just use an assignment.  Think of it as a pointer.  You'll just have two variables that point to the same thing.  Use the System.arraycopy() function.

Multi-Dimensional arrays are easy too...

int[][]  a;  // you init like this (int[][] a = { {1,2}, {3,4}, {4,5} }

Voila.  Technically it's just an array of arrays, so if you need a ragged array you could hop in a loop and use the new to allocate what you need where you need it.

Command line parameters - Now you know enough to puzzle out that (String[] args) stuff in your main method.  This is so you can pass parameters from the command line invocation of your program into an array called args!  Unlike C++, the first element is not the name of the program but actual data...

In Java - java testprog -h One Two

Give you a value of "-h" in args[0] while in C++ it would have been "testprog".

There's also a class, Arrays, that has a whole slew of useful methods, like sort().

Here's a prog that fills an array with random numbers for a lotto drawing...

package MyJava;

import java.util.*;
import javax.swing.*;

public class LotteryDrawing
{
    public static void main(String[] args)
    {
        String input = JOptionPane.showInputDialog("How many numbers do you need to draw? : ");
        int k = Integer.parseInt(input);
        
        input = JOptionPane.showInputDialog("What is the highest number you can draw? : ");
        int n = Integer.parseInt(input);
        
        // fill an array with the numbers
        int[] numbers = new int[n];
        for (int i = 0; i < numbers.length; i++) numbers[i] = i + 1;
        
        // draw k numbers and put them in a second array
        int[] result = new int[k];
        for (int i = 0; i < result.length; i++ ) 
         {
            // make a random index between 0 and n-1
            int r = (int)(Math.random() * n);
            
            // pick the number at the random location
            result[i] = numbers[r];
            
            // move the last element into the random location
            numbers[r] = numbers[n-1];
            n--;
         }
        
        // now print the sorted array...
        
        Arrays.sort(result);
        System.out.println("Bet the following combo and get rich!!");
        for (int i = 0; i < result.length; i++ ) System.out.println( result[i] );
        
        System.exit(0);
        
    }
}   

Pretty good example of all the stuff we're dealing with in this chapter, eh?  Time to move on to classes and some OOP...

Go back to the top

Send mail to lars@sorcon.com with questions or comments about this web site.
Copyright © 2004 Sorensen Consulting