So You Want to Build Software For a Living (Your First Programming Class)

In this post, I’m going to give you, the potential Computer Scientist, the information you’ll need to get through that first computer programming class.  This is not an infomercial and I’m not selling anything.  My goal is to try and help students who are not learning the material because their class size is astronomical or their instructor is disorganized, busy or complacent.

Let’s assume you know nothing about how a computer works.  You watched too many Hollywood movies and your idea of a computer is that it is a synthetic brain that can think on its own.  Now, let me correct your assumptions.  A computer is nothing more than a machine.  Literally, a computer is as smart as a toaster.  Yup, you heard that right.  It’s not any smarter than a coffee maker or a refrigerator.  It just does what it was designed to do, or in the case of a computer it does what you tell it to do.  So when you write a program, the program is nothing but a baby language that you must tediously type in step by step to instruct the computer to do “exactly” what you want it to do.  What do I mean by “exactly?”  I mean, you have to break your steps into tiny little steps, like what to print on the screen.  What to do when someone clicks on a button.  What to do when the program ends. 

So the first thing you’ll need to understand is that a program is executed from top to bottom.  Just like reading a book.  Most languages have a defined starting point and you’ll learn where that is.  From that starting point, the program will execute the line of code at the starting point, then it’ll move down to the next line and execute that line.  Then it will move to the next line.  Until it runs out of lines, or you put in a line of code that tells the computer to stop or end.

Compilers and Editors

Every language has a compiler and there are editors that you can use to create the text that represents your program.  For Java, the most common compiler/editor is the Eclipse IDE.  What does “IDE” stand for?  It just stands for Integrated Development Environment.  That means that you can type in your program like you’re typing a Microsoft Word document and then there is a button that runs your code and you can even use some built-in tools to test your program (more on this later).  I’ll be using Eclipse for my examples (you can download it free by clicking here).

Hello World

Every language out there has a “hello world” program.  It’s a demonstration of the simplest program you can write that does something.  So for Java, here’s a sample “hello world” program:

public class hello_world 
{
    public static void main(String[] args) 
    {
        System.out.println("Hello World!");
    }
}

That’s it.  That is the whole program.  All it does is print the sentence “Hello World!” in the output box.   So how does this program work?  Well, in Java, the program starts with a class.  In this example the class is called “hello_world” and the curly brackets (“{” and “}”) are used to group everything that is owned or contained in the class.  This part of the program can be ignored until you get to the lesson on what “objects” and “classes” are.  For now, just type it in like it’s shown.

The next line is the “main” (it’s shown as “public static void main(String[] args)).  This is the beginning of the first “method” or function call.  Basically your class can contain one or more of these methods which are used to group your program into “mini-programs” so you can break your problem into smaller chunks.  Again, you can just copy and paste this as-is for any of your intro programs.  In this case, you must keep the name “main”, otherwise Java doesn’t know where to start.

The next part of this program is the print line (shown as “System.out.println”).  The println or print line command will print one line of code.  It will print the text that is inside the double-quotes.

What About Those Brackets?

OK, let’s look at the curly brackets.  In order to group things together, you can use curly brackets (“{” and “}”).  In the hello world program, there is only one line of code so it doesn’t make a whole lot of sense to use the brackets.  For this sample program, the brackets are used to contain the code that is owned by the class and method.  The method called “main” is owned by the class called “hello_world” and the code that is executed (using the println command) is owned by the method called “main”.  Let’s look at another example program and brackets should become a little more clear:

public class hello_world  
{
    public static void main(String[] args) 
    {
        int myNumber = 5;
        
        if (myNumber == 5)
        {
            System.out.println("Hello World!");
        }
        else
        {
            System.out.println("Goodby Cruel World!");
            System.out.println("I'll miss you!");
        }
    }
}

This is a bigger program, and I’ve introduced some new “syntax”.  First, the “int” is a keyword for an integer variable.  Variables are a box where you can store something.  In this case, we’re creating a box named “myNumber” as an integer.  So the box can only hold an integer (which is a whole number, no decimal).  You can put one number in the box and if you read from the box you’ll get your number back.  The number will stay in the box until you change it.  In the above program, the box contains a 5.  Why?  Because I assigned the variable “myNumber” to 5 on the first executable line of code (int myNumber = 5;).  You’ll also notice the use of a semi-colon on many lines of code.  That just tells the computer that it’s the end of the line of code.  This semi-colon is part of the syntax of the Java language and you learn when to use a semi-colon and when not to use a semi-colon as you write programs and practice your syntax.  For now, all variable declarations end with a semi-colon.

The next line is blank.  That blank line of white-space does nothing.  Don’t expect the computer to do anything with this line.  It’ll see that there is no command on that line and go “Nothing to see here, movin’ on…”.  The purpose of white space is for readability.  You use spacing to make your program easy to read.  Indenting lines of code is used for readability too.  Because Java doesn’t care about white space, you can write a program that crams everything together like this:

public class hello_world{public static void main(String[] args){int myNumber=5;if(myNumber==5){System.out.println("Hello World!");}else{System.out.println("Goodby Cruel World!");System.out.println("I'll miss you!");}}}

Do you know what the above program will do?  Same as the previous program.  The computer will execute it just the same.  The problem is that nobody can read that!

OK, back to the “readable” program.  After the blank line there is an “if” statement.  This is known as a conditional statement.  When the computer comes to this line it will evaluate what is inside the parenthesis and compute a true or false result.  In this example “myNumber == 5” is tested to see if the box “myNumber” is equal to 5.  It is, so true is returned to the “if” statement.  Why use double “=” signs?  Here’s the problem: The equal sign is used to signify “assignment”.  As the first line of code showed, a “5” is “assigned” to the box or variable named “myNumber”.  So the difference between assign and equal is that the equal comparison operator uses a double-equal sign.

Again, you’ll get used to the “syntax” of Java as you write more and more programs.  Java is not the only language that uses the double-equal.  C, C++ and C# also use this syntax, and the reason is that they all came from the same language, which is C.

Back to the “if” statement.  The “if” statement will evaluate to a boolean or true/false result.  If the result is true, then the next line is executed.  If false, then the “else” statement is executed.  In cases where you don’t have code in your “else” statement, you can leave off the entire else part.  For now, just understand that the “If” statement has two possible paths to follow.  Since the result is true, we see that there is a curly bracket in the next line.  This bracket matches the closing curly bracket and every line of code in-between is grouped together and executed one line at a time.  There is only one line of code between the brackets.  That is the line of code that prints “Hello world!”, then the program will skip over the “else” part (the else will only execute if the result was false).  After the else part of the program, there is no more code to execute, so the program stops.

Now, let’s change the variable to 6:

public class hello_world  
{
    public static void main(String[] args) 
    {
        int myNumber = 6;
        
        if (myNumber == 5)
        {
            System.out.println("Hello World!");
        }
        else
        {
            System.out.println("Goodby Cruel World!");
            System.out.println("I'll miss you!");
        }
    }
}

In this example, the “myNumber” box or variable is set to 6.  The “if” statement will evaluate to a false because 6 is not equal to 5.  Therefore the “Hello World!” line is skipped over and the else block of code is executed.  The first line of code between the brackets prints “Goodby Cruel World!” and then the next line of code will print “I’ll miss you!”.  Then the program ends because there is nothing more to execute.

Some Programming Etiquette

I’ve already described the usefulness of the curly brackets.  The next thing you need to pay attention to is the cleanliness of your code.  Indentation is very important for readability.  Here’s an example of poor indentation:

public class hello_world  
{
    public static void main(String[] args) 
    {
        int myNumber = 6;
        
        if (myNumber == 5)
        {
            System.out.println("Hello World!");
             }
             else
             {
        System.out.println("Goodby Cruel World!");
        System.out.println("I'll miss you!");
        }
    }
}

The problem with the appearance is that it doesn’t match the functionality of the program itself.  The “else” should always line up with the “if” statement.  Each open curly bracket (“{“) should line up vertically with the close bracket (“}”).  This is for your own good.  Follow this practice, even when you are just typing in a line of test code.  Keep it clean at all times.  Otherwise, you’ll pull your hair out trying to figure out what is wrong with your program when the problem is buried inside an improperly nested section of code.

Some practices break the open and close curly brackets on different lines, like this:

public class hello_world {
    public static void main(String[] args) {
        int myNumber = 6;
        
        if (myNumber == 5) {
            System.out.println("Hello World!");
        }
        else {
            System.out.println("Goodby Cruel World!");
            System.out.println("I'll miss you!");
        }
    }
}

Don’t do it!  It’s difficult to visualize where your blocks of code start and where they end.  It’s much easier to visually line up the brackets so you can see which brackets match.

Another bad practice, which is legal syntax is to not use brackets for one line of code under an “if” or “else” statement.  Here’s an example:

public class hello_world  
{
    public static void main(String[] args) 
    {
        int myNumber = 6;
        
        if (myNumber == 5)
            System.out.println("Hello World!");
        else
        {
            System.out.println("Goodby Cruel World!");
            System.out.println("I'll miss you!");
        }
    }
}

This program works exactly as above.  Why?  Because the “If” statement always executes one statement after it, if the statement evaluates to true.  The same with the else part, except we have two statements in the else part, so brackets need to be used.  This syntax is legal and the computer doesn’t care.  However, if you are working on a program and you later go back and add a line under the “if” statement, you might not realize that there are no brackets and indent your program correclty, only to find out that it doesn’t work.  Like this:

public class hello_world  
{
    public static void main(String[] args) 
    {
        int myNumber = 5;
        
        if (myNumber == 5)
            System.out.println("Hello World!");
            System.out.println("Line 2!"); 
        else
        {
            System.out.println("Goodby Cruel World!");
            System.out.println("I'll miss you!");
        }
    }
}

What will this program do?  It will complain about the “else” statement:

 Yikes!

Any time you use an “if” statement, put in the curly brackets.  This practice should become habit.  Also, any time you type an open bracket, type in the close bracket, then move the cursor to the inside and type in your code.  Nothing is worse than forgetting a bracket and then trying to figure out where the missing bracket is.

About Those Semi-Colons

Remember the semi-colon that you used to end the “myNumber” variable assignment line?  Notice how there is no semi-colon at the end of the “if” statement.  If you put a semi-colon at the end of the “if” statement, the computer will educate you on the nuance of Java syntax.  In this example:

public class hello_world  
{
    public static void main(String[] args) 
    {
        int myNumber = 6;
        
        if (myNumber == 5);
        {
            System.out.println("Hello World!");
        }
        else
        {
            System.out.println("Goodby Cruel World!");
            System.out.println("I'll miss you!");
        }
    }
}

You’ll get the same error as above “Syntax error on token “else”, delete this token”.  Not a helpful error message, since the real error is that tiny little semi-colon at the end of the if statement.  The problem is even worse if you have code that does not have an “else” part.  Like this:

public class hello_world  
{
    public static void main(String[] args) 
    {
        int myNumber = 6;
        
        if (myNumber == 5);
        {
            System.out.println("Hello World!");
        }
    }
}

Guess what that code does!  It prints “Hello World!”.  If you look closely, you’ll see that “myNumber” is assigned the number 6 and is not equal to 5.  A false should skip over the next block of code which prints the “Hello World!”.  If you change the “myNumber” variable to 5, this program will still print “Hello World!”.  In fact, the “if” statement only excecutes the next line which is the semi-colon, then it moves on to the block of code that prints “Hello World!”.

Troubleshooting this is difficult because you don’t get any error at all.  The program just doesn’t do what you expected.  This is what we call a “bug”, or a run-time error.  Because the error only occurs when the program is run and doesn’t occur at compile time like the earlier errors.

Debugging

Five seconds after you write your first program, you’ll need to learn how to debug it, or fix it to make it perform the way you expected it to perform.  Debugging is the process of removing bugs.  Compile time bugs are immediate and they must be fixed before the program will run.  You can usually gain some information from the error message that is presented, but sometimes that can be obscure.  Sometimes the computer doesn’t recognize that there is a bug until several lines of code down the line.  Which is what happened earlier with the bug being reported at the “else” statement, even though both bugs I introduced were a the “if” statement. 

Here’s a simple example bug:

public class hello_world  
{
    public static void main(String[] args) 
    {
        int myNumber = "a";
    }
}

You’ll see a red circle to the left of the “myNumber” declaration:

 

Hold your mouse over the red circle or over the red underlined section of code.  You’ll get the following error:

What this error means is that you are trying to save a string into an int or integer value.  A string contains letters, but an int can only contain an integer or whole number.  In order to fix this problem, you’ll need to change your variable type to a “String” or change the value you are trying to assign to an integer.

Break Points

You put a break point in your program.  Basically, you can right-click on the vertical bar on the left side of the editor, next to the line of code you want to stop at, then toggle-breakpoint.  This will put a little blue circle on the bar.  Then you run your code in debug mode by clicking on the “debug” button:

A bunch of other window panes will show and you can see your variables (in this case there are two variables, your “myNumber” variable and the “args” variable which you can ignore).  The program will stop on your line of code that has the break-point and wait for you to tell it to continue.

You can see the green line where my program is waiting.  The variables window looks like this:

Notice how the “myNumber” variable already contains a “5”.  Now you can step to the next line of code using the “Step Over” command.  You can also use the “Step Into” for this sample, but it has another use that does not apply to this simple program.  The “Step Over” button looks like this:

Notice how the program prints “Hello World!” right after you step over the print command.  You can use the step commands to observe exactly how your program is executing your code.  This can be helpful when you can’t figure out why your program is going into your “if” statement or not.

How to Get Started on Your Class Assignment

OK, your teacher has given you an assignment, you read through the instructions and nothing comes to mind!  What do you do?  The first thing you need to do is break the problem down.  Inside the description of your problem will be individual pieces that you can probably write in code.  Create an empty program.  Put in one or two lines of code and run it.  See if it does what you expect it to do.  Maybe the assignment expects you to read in a number.  Look through your school notes and find out how to read from the input.  You can also check with Google.  I can assure you that someone out there has read something into their program using the Java language.

Type in enough code to read something in.  Put a break-point in your program and debug to the input statement.  Type something into the keyboard.  Step to the next line.  Check to see if your variable contains the input you typed in.  Now go to the next part of your assignment.

Even though your are taking your first class and it should be an exercise in syntax, you can’t create a program with just syntax and no algorithm.  So you’ll have to learn a simple algorithm.  Some instructors will give you the algorithm, some will give the name of the algorithm to use.  You can lookup the algorithm on-line and see how it is performed.  Let’s pretend you are given the task of writing a program that prints the maximum of two integers.  Your input requires you to input two integer numbers and then you must print whichever number is the largest.

First of all, how would you do it if you didn’t have a computer?  I’m sure you can do it in your head, but this is a simple example.  Get out a piece of paper and write down two boxes.  Name them input1 and input2.  Now, put a number in input1 and a different number in input2.  What computer statement would you use to determine which number is larger?  The “if” statement comes to mind.  At this point, you should be able to create a program that reads in two variables and then compares the two with an “if” statement using a greater than symbol:

if (input1 > input2)
{
            
}
else
{
            
}

You can run this program and it will not print anything, but you’re almost there.  You just need to add the print statements.  Inside the if brackets, you’ll need to print the number from input1.  Why?  Because you’ll get a true if input1 is larger than input2.  The else statement should print the value of input2.

Yes, this is a very trivial example, and it doesn’t handle the case where the values are equal.  The purpose of showing this is that you need to break your problem down into tiny little baby steps.  If you can’t get your brain wrapped around the problem, break it down.  If you can’t get the computer to perform your algorithm or you don’t know how to code it, do it on paper by hand.  Once you figure out how to do the algorithm by hand, you can write a program to perform the same steps.

Where to Get More Help

First of all, you should start writing your program as soon as your assignment is available.  It will take you a long time to write a program at first.  You don’t know the syntax or any algorithms so you need to stumble around and figure stuff out.  After you’ve written a program or two, you might be thinking that you need more practice with writing programs.  This is correct.  You should go to places like hackerrank and do some practice problems:

Go here: https://www.hackerrank.com/domains 

Select Java, and start at the top.  Solve some problems.  The hackerrank system will give you immediate feedback on your solution.  You can submit your problem as many times as it takes to get it accepted.  This is where you will get practice.  Like learning to play a musical instrument.  Practice!

You can also go to Coursera and do a Java course.  I would recommend doing a course before you start school or do it on a weekend if you have the available time.  You’ll get duplicate information, but there will be items that don’t overlap due to differences in teaching methods.  There are other on-line courses that you can take.  Some cost money, some are free.

Buy a book or check out a book from the library.  Make sure the book is an entry level book and doesn’t dive into something too complicated.  Type in some of the book code samples and step through them.

The Internet is full of information on programming.  When I graduated from college the internet was just getting started.  Google wasn’t invented yet.  My resources while I was taking classes involved using FTP to known code sites or using AOL or Compuserve.  Now I find a lot of stuff on Stack Overflow (though their answers are sometimes beyond the expected answer for an entry level class, buyer beware) and Google.

Good luck with your programming.

Leave a Reply