Document Sample
lecture04 Powered By Docstoc
					Introduction to Java, Lecture 4

Topics to be covered

             Java language elements
             Fundamental Programming structures in Java
             Creating a simple Java Application


At this point we are assuming that the students are familiar with
          Java development environment
          Basic concepts of the OOP (class inheritance, object etc.)
          Familiarity with basic terms regarding HTML, Java virtual machine, applets and application
          Students are able to run simple applets or applications
          Have basic understanding about Java syntax and data types

If it is not a case, please take care to make your self-familiar with matter.

After finishing this session

             The students will get essential knowledge about basic concepts about
                   Java programming language
                   Basic programming structure

How to check your Progress?

             Finish your homework
             Answer to the skill testing questions
             Build by your self an application as it is suggested in the assignment

                                                                                                Page 1
Fundamental Programming Structures in Java


This session deals with basic Java program structures and elements.

Sort review

                                                Java Program

                                                     Java API

                                          Operating System

                                              Java Platform

Java programs are interpreted by JVM (Java Virtual Machine). Rather then running the program directly
on the native OS, the program is interpreted by JVM. That allows to the Java applications (or applets)
running regardless of the computer system where they are developed.

Java APIs are libraries of precompiled code (classes provided with the JDK) which are ready to use classes.
As we know those classes could be instantiated to the objects and directly put into the code. Example for
that is the push button object, instantiated from Button class.

A Java program has to be converted to the form the JVM can understand. Compiling Java source code
means taking the programmer readable text (Java programming language instruction code) to the byte code
which are platform independent instructions for JVM.

When the program compiles, the byte code is located in the file with CLASS extension. Running a Java
program means invoking the JVM, which will convert the byte code to the platform dependent machine
code, which can run in the native environment.

We can generate Java application or applet. The difference is that the applets are using HTML files and
WEB browser or Java applet viewer as a work-frame, whereas the applications builds their own work-

Compiling is the same in both cases:

        >javac MyProgram.java

Running the applet could be done using WEB browser or applet viewer.

NOTE: In both cases we are initializing HTML file (e.g. appletviewer MyProgram.HTML)
Running the application is possible starting the JVM from command line (or batch file)

        >java MyProgram

                                                                                                    Page 2
Simple Java program example

Here is the example of the simple Java program, which prints message to the console:

         public class SimpleExample
                  public static void main (String[], args)
                           System.out.println(“I am a simple program”);

As we know, public key word is access modifier, discussed in previous paragraphs.
Static means for the JVM to create just one (final) instance of the class.
When the program ends, does not return data to the JVM (void key-word)

The class System does not need to be explicitly created. That is true for all API’s.

 Please review applets example code from previous sessions.
 The applet starts using APPLET HTML tag, and not main() method.
 Therefore applet source code does not contain main() to define the entry point.


Could be same Java class interpreted at the same time as an applet and application?

Java methods

Methods access the data inside of the class. Depending of that if the data will be changed (updated) or just
transferred to the other method or object we could have mutator and accessor type of the method.


In this example we are going to have a static string (usually called member) accessed by the accessor
method getText().

class MethodExample {
        static String MyText = “Simple text”;

         // Accessor method
         static String getText() {
                   return MyText;

         public static void main(String[] args) {
                  String retrievedString = getText();

                                                                                                        Page 3

What is the difference among static and non-static members?

A static member belongs to the class it self, and not to the instances of the class.
What does it mean? Let us use an example:


If we are initializing a class car, and we want to define number of passenger seats, in most cases it is 4.
If we are instantiating more objects of this class, the seat number we do not want to declare each time.
Therefore we will define the number of seat in class car as static.

class Car {
         public String manifacturer,
         public String model;
         public static numberOfPassengerSeats = 4;

                                                                 BMW, 328ti, 4

                Class Car

                                                                Ford, Mustang, 4

                                                               VW, bug, 4

                Instantiating the class car using static member “numberOfPassangerSeats”

Java Classes

A derived class is commonly referred as a subclass, while the class it is derived from is referred to as a


public class Car {
         // Member methods and variables

public class ClassicCar extends Car {
         // Member methods and variables

Car is superclass of the ClassicCar. ClassicCar is subclass of Car.

                                                                                                         Page 4
Java Constructors

Classes have a special method called constructor, which is invoked automatically when a class instance is
created. The constructor method always has
          the same name as the class
          does not have a return type


class Car {
         public String manifacturer,
         public String model;
         public static numberOfPassengerSeats = 4;

        // constructor
        public Car (String MadeBy, String ModelOfTheCar, int numOfPassSeats) {

                 // initialization of the class members
                 manifacturer         = MadeBy;
                 model                = ModelOfTheCar;

                 // note that the static class members are initialized conditionaly
                 if (numberOfPassengerSeats !=4 )
                           numberOfPassengerSeats = numOfPassSeats;

        // overloading the constructor
        public Car (String MadeBy, String ModelOfTheCar) {

                 // initialization of the class members
                 manifacturer         = MadeBy;
                 model                = ModelOfTheCar;

        // main program
        public static void main (String[], argv) {
                 // instantiatiate the class
                 Car MyCar = new Car (“VW”, “bug”);
                 Car MyBossCar = new Car(“Porshe”, “944”, 2);

Exercise: Walk through the code.

                                                                                                    Page 5
The super Variable.

Let us get back to the previous example where super classing has been presented.

public class Car {
         // a public constructor of the class Car
         public Car( String manufacturer, String model) {
                   // initialization code

public class ClassicCar extends Car {
         // a public constructor of the class ClassicCar
         public ClassicCar( String manufacturer, String model) {
                   super (manufacturer, model);

Because ClassicCar is derived from Car class, its inherits all of the functionality, including member
variables and the constructor. The super variable is referring to the parent class (Car) constructor.
Therefore in this case super (manufacturer, model); invokes the constructor of the super class.

The this Variable

All Java classes contain a hidden member variable called this. The this member can be used at run time to
reference the object it self. If we are focusing our attention back to the previous example, during the
construction of car object we have been pushed to use two different variables for the same concept.

For example we used two different names for variable which is passing value from constructor parameter
list to the instance variable of the class.

         Manufacturer = MadeBy

Using this member variable we could distinguish among instance variables and constructor parameters.


class Car {
         public String manifacturer,
         public String model;
         public static numberOfPassengerSeats = 4;

         // constructor
         public Car (String manifacturer, String model, int numberOfPassengerSeats) {

                    // initialization of the class members
                    this.manifacturer = manifacturer;
                    this.model           = model;

                    // note that the static class members are initialized conditionaly
                    if (numberOfPassengerSeats !=4 )
                              this.numberOfPassengerSeats = numberOfPassengerSeats;

                                                                                                        Page 6
Flow control in Java Applications
The flow control in Java is inherited from ANSI C.
There are just few main control sequences:

               Selection
               Iteration

Java Provides two alternative structures:

The if statement

if (condition is TRUE)
          { execute statement 1;}
          {execute statement2;}

The switch statement

switch (condition )
         case (match the condition 1) :
                  execute statement 1

            case (match the condition 2) :
                    execute statement 2

            case (match the condition 3) :
                    execute statement 3



Java provides three iteration statements:

 For                                         while      Do-while

 for (initialize; test; increment)           while      do
            { statement; }                   do-while   { statements}
                                                        while (condition)

                                                                            Page 7
Code Walkthrough
The main purpose of the code walkthrough is to emphasize the team work and to underline the skills
achieved during the current session.

Java Program Example 1 - Displays Date

public class DisplayDate {

        public static void main(String argv[]) {

    //Draw the top border
    for (int i = 0; i < 40; i++)

        //Display the time
        System.out.println("Milliseconds since January 1, 1970: " + System.currentTimeMillis());

         //Draw the bottom border
    for (int i = 0; i < 40; i++)

        //Closing remark
    System.out.println("End of printing");


                                                                                                     Page 8
Java Program Example 2 - Displays Persons Name and Account Number

public class Account {

    //variables for class Account
    String name;
    int accountNumber;
    float balance;

    //Method to print information on the screen
    void Printout() {
      System.out.println("Name:         " + name);
      System.out.println("Account Number: " + accountNumber);
      System.out.println("Balance:      $XXXXXX, Sorry that is classified");

    public static void main(String args[]) {
      //Create an instance of First
      First f = new First();

        //Add data to the variables in class First
        f.name = "John Smith";
        f.accountNumber = 235412345;
        f.balance = 25;

        //Draw the top border
        for (int i = 0; i < 40; i++)
        // Title
        System.out.println("       INFORMATION");

        // Call method to print the information

        //Draw bottom border
        for (int i = 0; i < 40; i++)

        //Ending remark
        System.out.println("End of printout");


                                                                               Page 9
Java Program Example 3 - Displays Persons Name and Account Number
Read list of arguments from command line

public class SayHello {

        public static void main(String args[]) {

    //Draw the top border
    for (int i = 0; i < 40; i++)

    //Check to see if no argument was passed
    if (args.length == 0)
       System.out.println("Please enter your name!");

    // Loop through and say hello to everyone
                 for (int i = 0; i < args.length; i++)
                            System.out.println("Hello " + args[i]);

    //Draw the bottom border
    for (int i = 0; i < 40; i++)

    System.out.println("End of printing");


Question 1. Yes

                                                                      Page 10
                                    Quiz Question Set 4

Question 1
A constructor is used to create new instances of a class.
How many instances of the particular class could be created using a constructor?

Question 2
What “this” variable is referring to?

                                                                                   Page 11
Question 3
Please analyze the flowing Java program code.
What would be displayed on the screen after running this program?

import java.io.*;

public class IntegerClassMember
         int x;
         static int y;

         public int x() { return x; }                             // get the instance variable
         public int y() { return y; }                             // get the class variable

         public void setX(int Xparam) { x = Xparam; }             // set the instance variable
         public void setY(int Yparam) { y = Yparam; }             // set the class variable

         // main program
         public static void main(String args[])
                  IntegerClassMember myFirstInteger = new IntegerClassMember();
                  IntegerClassMember mySecondInteger = new IntegerClassMember();

                     // set the first member variable using apropriate method
                     // set the second member variable using assignment
                     mySecondInteger.x = 2;

                     System.out.println("First X integer:" + myFirstInteger.x());
                     System.out.println("Second X integer:" + mySecondInteger.x());

                     // set the first CLASS member variable using apropriate method
                     // set the second CLASS member variable using assignment
                     mySecondInteger.y = 2;

                     System.out.println("First Y integer:" + myFirstInteger.y());
                     System.out.println("Second Y integer:" + mySecondInteger.y());

/** End of File */

Answer sheet:

First X integer:
Second X integer
First Y integer:
Second Y integer

                                                                                                 Page 12

Shared By: