Lecture 2: INTRODUCTION  TO  JAVA

TOPICS


Overview of the Java Programming Language
The Java Programming Environment:
Getting Started: "Hello World!" in Java
Intro to Java:

Program Errors
Procedural Decomposition: Java Static Methods
Sample Programs

OUTLINE



1. Overview of the Java Programming Language

Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.. It allows you to build both applets (mini programs that can run only under a Web browser) and applications (stand-alone programs.) Applets are used to enhance the interactivity of a web page - can display graphics, accept input from GUI components, etc. Stand-alone applications can run as a console application (writing text to the screen), or they can have a GUI (a new window or dialog box.)

We will focus primarily upon stand-alone applications with Java --> first thing required: a Java compiler/interpreter. As with any application, you need to be sure that Java is properly installed on your computer.

No matter what environment you use, you will follow the same basic three steps when writing a program in Java:
1. Create (or edit) the program by typing it into a text editor and saving it to a file with the extension .java (Example: FirstProgram.java). Outcome: Edited the program,  got the source file.
2. Compile the program by typing "javac FirstProgram.java" in the terminal window. Outcome: The program you just typed, the text file with the .java extension was translated into a file with a .class extension. This file contains instructions (called bytecodes) that the Java Virtual Machine (JVM) can understand. Once your program compiled without errors, you can move to the next step.
3. Run (or execute) the program by typing "java FirstProgram" in the terminal window. Outcome: The Java application launcher tool (java) uses the JVM to run your application; if all goes well you will see the expected results.

2. The Java Programming Environment

Anybody learning a new programming language has to choose a programming environment that makes it possible to create and run programs. Programming environments can be divided into two very different types: integrated development environments (IDEs) and command-line environments. All programming environments for Java require some text editing capability, a Java compiler, and a way to run applets and stand-alone applications. An integrated development environment, or IDE, is a graphical user interface program that integrates all these aspects of programming and probably others (such as a debugger, a visual interface builder, and project management). A command-line environment is just a collection of commands that can be typed in to edit files, compile source code, and run programs. In this class we will use the DrJava Integrated Development Environment (IDE) for writing Java programs. DrJava is used to create, edit, compile, run, and debug Java programs.

3. Getting Started: "Hello World!" in Java

Before starting to discuss the Java language in details, let's get started with a full-fledged Java program. The first step in learning any new programming language is to write a simple program that prints the message "Hello, World!" on the screen (First "Hello, World!" program introduced by Kernighan and Ritchie in early 1970s, when they wrote the reference manual for the newly developed C language)

Some notes before getting started:
1. Java is a case-sensitive language. Be consistent with your lower cases/upper cases: HelloWorld is not the same as helloWorld.
2. Java programs are collections of classes and in Java everything must be defined inside of a class.
3. Java naming convention: start class names with a capital letter (easy to identify them).
4. The name of the source file must match the name of the class, so if the name of the class is HelloWorld, the name of the source file should be HelloWorld.java. When you compile HelloWorld.java the bytecode file will be named HelloWorld.class. This is the file to be executed (run) in order to see the output.
5. Every basic Java statement ends with a semicolon ( ; )
6. The contents of a class or method occur between curly braces, { and }
7. Don't expect to understand what's going on here just yet!

               public class HelloWorld {
              /* A program to display the message
                 "Hello World!" on standard output screen */
              public static void main(String[] args) {
                  System.out.println("Hello World!");
              }
          } // end of class HelloWorld

The command that actually displays the message is:

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

When you run this program, the message "Hello World!" (without the double quotes) will be displayed on your standard output screen.
What about other statements in this program? Some of them are comments. Comments in a program are entirely ignored by the computer; they are there for human readers only; without comments, a program can be very difficult to understand. Java has three types of comments. One type, used at the end of the above program, begins with // and extends to the end of a line. The computer ignores the // and everything that follows it on the same line. Another type of comment, found at the beginning of this program, can extend over many lines; this type of comment begins with /* and ends with */.
Remember that all programming in Java is done inside "classes." The first line in the above program says that this is a class named  HelloWorld. "HelloWorld," the name of the class, also serves as the name of the program (source file). In order to define a program, a class must include a method called main(), with a definition that looks like this:

                public static void main(String[] args) {
                statements
                ....
           }

When you tell the Java interpreter to run the program, the interpreter calls the main() method, and the statements that it contains are executed. The main() method can call other methods that are defined in the same class or even in other classes, but it is the main()method that determines how and in what order the other methods are used.

The word "public" in the first line of main() means that this method can be called from outside the program (available to anyone to use). This is essential because the main() method is called by the Java interpreter. The remainder of the first line of the method is harder to explain at the moment; for now, just think of it as part of the required syntax. The definition of the method (the instructions that say what it does) consists of the sequence of "statements" enclosed between curly braces, { and }.  The curly braces are used to group together related lines of code.

As mentioned before, a method can't exist by itself; it has to be part of a "class". A program is defined by a public class that takes the form:

                    public class program-name {
                optional variable declarations and methods
                public static void main(String[] args) {
                    statements
                }
                  optional variable declarations and methods
           }

Note 1: The name on the first line is the name of the program, as well as the name of the class.
Note 2: A minimal Java program has just a main() method. Note that according to the above syntax specification, a program can contain other methods besides main(), as well as "variable declarations." You will learn more about these later.
Note 3: If the name of the class is HelloWorld, then the class should be saved in a file called HelloWorld.java. When this file is compiled, another file named HelloWorld.class will be produced. This class file, HelloWorld.class, contains the Java bytecode that is executed by a Java interpreter. HelloWorld.java is called the source code for the program. To run/execute the program, you only need the compiled class file, not the source code.

4. Intro to Java

a. Java Program Structure: An executable Java program consists of a class, which contains at least a method named main, which contains the statements (commands) to be executed.
Program sample (a variation of HelloWorld):

          public class HelloWorld2 {
              public static void main(String[] args) {
                  System.out.println("Hello World!");
                  System.out.println();
                  System.out.println("Have a nice day!");
                  System.out.println();
                  System.out.println();
                  System.out.println("Good bye!");
              }
          } // end of class HelloWorld2

b. Java Identifiers - used by programmers to name classes, methods or data objects in programs (variables or constants).

c.  Java Comments: A note written in a program to make the code easier to read and understand. Comments are not executed when the program runs. Most Java editors show your comments with a special color. Make your comments clear and easy to see. Java supports three types of comments:

d.  Java String Literals: Sequences of text characters that can be printed or manipulated in a program (also called just "strings").

e.  Java Screen Output: System.out.println - A statement to instruct the computer to print a line of output on the console (pronounced "print-linn")
Two ways to use
System.out.println:

System.out.println("Some Message"); // Prints the given message as a line of text on the console.
System.out.println(); // Prints a blank line on the console.

Take a look at the System.out.println statements in the program HelloWorld2

f.  Java Escape Sequences: Formed by a backslash followed by one or more additional characters between double quotes (strings). Used for the representation of some non-graphic characters as well as the single quote, double quote, and backslash characters. Java escape sequences:

          \n           Linefeed (Newline)
          \t           Horizontal tab
          \b           Backspace
          \f           Form feed
          \r           Carriage return
          \\           Backslash
          \           Single quote (apostrophe)
          \           Double quote (quotation mark)
          \uDDDD       Character from the Unicode character set (DDDD is four hex digits)

5. Program Errors

Programming language = a set of strict grammar rules, symbols, and special words used to construct a computer program. There are syntax rules (grammar: how valid instructions are written, what combinations of symbols can be used) and semantic rules (meaning of written instructions). Note: The computer is a mindless machine - it follows instructions to the letter and has no ability to know what was intended. You should understand that syntax and semantic rules are very strict. Pay attention!
Most program errors are easily fixed by carefully examining the program as we create it. Types of errors:
1. Compile-time errors. These errors are caught by the system when we compile the program, because they prevent the compiler from doing the translation (so it issues an error message explaining what was wrong). Also called syntax errors (the equivalent of bad grammar - misspelled words). The compiler indicates the line number on which the error was found, but error messages don't always help the programmer understand what was wrong.
2. Run-time errors. These errors are caught by the system when we execute the program, because the program tries to perform an invalid operation (Example: division by zero).
3. Logical errors (bugs). These errors should be caught by the programmer when the program executed produces an unexpected output. Logical errors are more difficult to fix; should focus on the right algorithm/solution during the design and analysis stage.

The very first skill that you will learn is to identify errors; next you will be careful enough to avoid many of them.

6. Procedural Decomposition

In computer science, decomposition refers to the process by which a complex problem is broken down into parts that are easier to conceive, understand, program, and maintain.
Decomposition in structured programming means something slightly different than the decomposition practiced in the object-oriented world. A procedural (structured) program divides the problem into its component tasks (in other words, breaks a process down into well-defined steps); these tasks/steps are implemented as separate functions, each of which is potentially further subdivided into smaller functions. An object oriented program is divided in classes, which then separate their operations into methods. Instead of thinking of a problem as a series of actions to be performed, we think of it as a collection of objects that have to interact.
Procedural decomposition: 2 strategies

Java - uses mostly the object-oriented decomposition. This class will start first with procedural decomposition and will move to the object-oriented decomposition later.

Static methods:

public class RedundantCode {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        System.out.println("How are you today?");
        System.out.println();
        System.out.println("Hello World!");
        System.out.println("How are you today?");
        System.out.println();
        System.out.println("Hello World!");
        System.out.println("How are you today?");
        System.out.println();
    }
}


       
  public static void <method name> () {//method header
        //method body
        <statement>;
        <statement>;
        ...
        <statement>;
     }

public static void printHello(){
    System.out.println("Hello World!");
    System.out.println("How are you today?");
    System.out.println();
}


       
<method name> ();


    printHello();

public class MethodExample {
    public static void main(String[] args) {
        printHello();
        printHello();
        printHello();
    }

    public static void printHello(){
        System.out.println("Hello World!");
        System.out.println("How are you today?");
        System.out.println();
    }
}

7. Sample Programs
The output:

Description: C:\Courses-NOW\Webpage\236\LectureNotes\L2-drawing.JPG

First version: no static methods

// This program prints several assorted figures.
//
public class Drawing1 {
    public static void main(String[] args) {
        System.out.println("   -------");
        System.out.println("  /       \\");
        System.out.println(" /         \\");
        System.out.println(" \\         /");
        System.out.println("  \\       /");
        System.out.println("   -------" );
        System.out.println();
        System.out.println(" -----------");
        System.out.println(" \\         /");
        System.out.println("  \\       /");
        System.out.println("   -------" );
        System.out.println();
        System.out.println("   -------");
        System.out.println("  /       \\");
        System.out.println(" /         \\");
        System.out.println(" -----------");
        System.out.println("|   STOP    |");
        System.out.println(" -----------");
        System.out.println(" \\         /");
        System.out.println("  \\       /");
        System.out.println("   -------" );
        System.out.println();
        System.out.println("   -------");
        System.out.println("  /       \\");
        System.out.println(" /         \\");
        System.out.println(" -----------");
        System.out.println();
    }
}

Second version: structured with redundancy

// Prints several assorted figures, with methods for structure.
//
public class Drawing2 {
    public static void main(String[] args) {
        drawHex();
        drawHalfUp();
        drawStopSign();
        drawHalfDown();
    }

    public static void drawHex() {
        System.out.println("   -------");
        System.out.println("  /       \\");
        System.out.println(" /         \\");
        System.out.println(" \\         /");
        System.out.println("  \\       /");
        System.out.println("   -------" );
        System.out.println();
    }

    public static void drawHalfUp() {
        System.out.println(" -----------");
        System.out.println(" \\         /");
        System.out.println("  \\       /");
        System.out.println("   -------" );
        System.out.println();
    }

    public static void drawStopSign() {
        System.out.println("   -------");
        System.out.println("  /       \\");
        System.out.println(" /         \\");
        System.out.println(" -----------");
        System.out.println("|   STOP    |");
        System.out.println(" -----------");
        System.out.println(" \\         /");
        System.out.println("  \\       /");
        System.out.println("   -------" );
        System.out.println();
    }

     public static void drawHalfDown() {
        System.out.println("   -------");
        System.out.println("  /       \\");
        System.out.println(" /         \\");
        System.out.println(" -----------");
        System.out.println();
    }
}

Third version: structured, no redundancy

// Prints several figures, with methods for structure
//  no redundancy.

public class Drawing3 {
    public static void main(String[] args) {
        drawHex();
        drawLine();
        drawHalfUp();
        drawStopSign();
        drawHalfDown();
        drawLine();
    }

    public static void drawLine() {
        System.out.println(" -----------");
    }

    public static void drawHalfUp() {
        System.out.println(" \\         /");
        System.out.println("  \\       /");
        System.out.println("   -------" );
    }

    public static void drawHalfDown() {
        System.out.println("   -------");
        System.out.println("  /       \\");
        System.out.println(" /         \\");
    }

    public static void drawHex() {
        drawHalfDown();
        drawHalfUp();
        System.out.println();
    }

    public static void drawStopSign() {
        drawHalfDown();
        drawLine();
        System.out.println("|   STOP    |");
        drawLine();
        drawHalfUp();
        System.out.println();
    }
}


Additional Resources:
1. (Oracle) The Java Tutorials: A Closer Look at the "Hello World!" Application:  http://docs.oracle.com/javase/tutorial/getStarted/cupojava/win32.html
2. (Oracle) The Java Tutorials: Variables  http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html


References:
Building Java Programs: A Back to Basics Approach, by Stuart Reges, and Marty Stepp, Addison Wesley, 2008.