• UNIT 10: INTRODUCTION TO JAVA

    Key Unit Competency:
    to be able to create, build and run a java console program

    Introductory activity

    1. Explain the following terms in computer programming:

    a) Computer Programming           b) Programming language

    c) High-level language                 d) Low-level language

    e) Programming paradigms

    2. Discuss the following OOP concepts:

    a) Abstraction               c) Encapsulation

    b) Polymorphism          d) Inheritance

    3. Explain the following concepts in programming

    a) Compile and run program

    b) Programming Environment        c) Basic Syntax      d) Data Types

    d) Variables                                     e) Keywords           f ) Basic Operators

    g) Decision Making         h) Loops

    10.1. Concepts of Java Programming

    Learning Activity 10.1

    1. Define a java in Programming language

    2. Discuss on invention and advantages of java.

    10.1.1. Definition

    Java is a computer programming language. It enables programmers to write computer instructions using English-based commands instead of having to write in numeric codes. It is known as a high-level language because it can be read and written easily by humans

    10.1.2. Invention

    Java is a general purpose, high-level programming language developed by Sun Microsystems. The Java programming language was developed by a small team of engineers, known as the Green Team, who initiated the language in 1991. The Java language was originally called OAK, and at the time it was designed for handheld devices and set-top boxes. OAK was unsuccessful and in 1995 Sun Microsystems changed the name to Java, which has built-in support to create programs with a Graphical User Interface (GUI), utilizes the Internet, creates client-server solutions, and modified the language to take advantage of the burgeoning (developing quickly) World Wide Web. The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications. The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is
    guaranteed to be Write Once, Run Anywhere. A variant of Java programs called applets can be embedded inside a web page and execute on the computer that is viewing the page, automatically and in a secure environment.

    10.1.3. Advantages of Java

    Application Activity 10.1.

    Discuss the difference between Java Programming and C/C++ programming languages in
    terms of advantages.

    10.2. Platforms of JAVA Program

    Learning Activity 10.2.

    Search and discuss about the following in Java Environment:

    1. Platform and Platform independent

    2. Java Virtual Machine (JVM)

    3. Java Runtime Environment (JRE) vs. Java Development Kit (JDK)

    10.2.1 JRE & JDK & JVM

    The Java platform is the name given to the computing platform from Oracle that helps users to run and develop Java applications. The platform does not just enable a user to run and develop a Java application, but also features a wide variety of tools that can help developers work efficiently with the Java programming language.

    The platform consists of two essential pieces of software:

    Java Runtime Environment (JRE): Thisis the environment within which
    the java virtual machine runs. JRE contains Java virtual Machine (JVM),
    class libraries, and other files excluding development tools such as compiler
    and debugger. Note: The JRE takes care of running the Java code on
    multiple platforms, however as developers, we are interested in writing
    pure code in Java which can then be converted into Java byte-code for
    mass deployment
    Java Development Kit (JDK), which is needed to develop those Java applications and applets( a small dynamic Java program that can be transferred via the Internet and run by a Java-compatible Web browser). If you have installed the JDK, you should know that it comes equipped with a JRE as well. JDK contains everything that JRE has along with development tools Such as compiler debugger etc.

    • The Java platform consists of the Java Application Programming Interfaces (APIs) and the Java Virtual Machine (JVM). Java APIs are libraries of compiled code that you can use in your programs.

    • They let the programmers add ready-made and customizable functionality to save them programming time.

    • Any program uses Java API to print a line of text to the console.

    • The console printing capability is provided in the API ready for programmers to use; programmers supply the text to be printed. Java programs are run (or interpreted) by another program called the Java VM, for the native operating system. Any computer system with the Java VM installed
    can run Java programs regardless of the computer system on which the
    applications were originally developed. For example, a Java program developed on a Personal Computer (PC) with the Windows NT operating system should run equally well without modification on
    Macntosh computer running Mac OSx operating system, and vice versa.

    Application activity 10.2.

    Discuss the difference between JVM vs JRE vs JDK

    10.3 Write, Compile and run a java Program

    Learning Activity 10.3.

    1. Using internet, Search and install step by step the environment of java.

    2. Observe and interpret the following picture:

    10.3.1 Create a java program

    Before writing and running the simple Java program, there is a needto install and to configure
    the Java platform. Which is available free of charge from the Java web site.(for example
    NetBeans IDE 8.0 or NetBeans IDE 8.2 )
    The first application, HelloWorldApp, will simply display the greeting “Hello World!” To create
    this program, the following steps must be respected

    Create an IDE (Integrated Development Environment) project: Creating an IDE project means creating an environment in which to build and run the applications. Using IDE projects eliminates configuration issues normally associated with developing on the command line. Build or running an application can be done by choosing a single menu item within the IDE.

    a) Launch the NetBeans IDE.

    • On Microsoft Windows systems, use the NetBeans IDE item in the Start menu.

    • On Solaris OS and Linux systems, execute the IDE launcher script by
    navigating to the IDE’s bin directory and typing. /netbeans.

    • On Mac OS X systems, click the NetBeans IDE application icon.


    In the New Project wizard, expand the Java category and select Java Application as shown
    in the following figure:

    In the Name and Location page of the wizard, do the following (as shown in the figure
    below):

    • In the Project Name field, type HelloWorldApp.

    • In the Create Main Class field, type helloworldapp.HelloWorldApp.

    • Then click the button Finish in the figure below.

    The project is created and opened in the IDE. In the next figure, there are the main components
    of the environment
    • The Projects window, which contains a tree view of the components of the project, including source files, libraries that the code depends on, and so on.

    • The Source Editor window with a file called HelloWorldApp.java open.

    • The Navigator window, used to quickly navigate between elements within the selected class.

    Add Code to the Generated Source File: A source file contains code, written in the Java
    programming language, that programmers can understand. As part of creating an IDE project,
    a skeleton source file is automatically generated and the source file is then modified to add the “Hello World!” message. When this project was created, the Create Main Class checkbox was left selected in the New Project wizard. The IDE has therefore created a skeleton class for the programmer. The «Hello World!» message is added to the skeleton code by replacing the line:
    // TODO code application logic here
    With the line:

    These four lines are a code comment and are not affecting how the program runs. Later
    sections of this unit explain the use and format of code comments.
    Notice that Java programming is case sensitive. It means that “a” is different from “A”, helloWorldApp
    is also different fromHelloWorldApp.

    After adding the code, the remaining action is to Save the changes by choosing
    File | Save.

    The file should look something like the following:

    10.4. Compile the Source File into a .class File

    The IDE invokes the Java programming language compiler (javac), which takes the source
    file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this file are known as byte codes.To compile the source file, choose Run | Build Project (Hello World App) from the IDE›s main menu. The Output window opens and displays output similar to what is seen in the following figure:

    program is successfully compiled. If the build output concludes with the statement BUILD
    FAILED, there is probably a syntax error in the code. Errors are reported in the Output window as hyperlinked text. To navigate to the source of an error, double-click such a hyperlink. After fixing the error, once again choose Run | Build Project.

    10.5 Running the Program

    The IDE invokes the Java application launcher tool(java), which uses the Java virtual machine
    to run your application. From the IDE’s menu bar, choose Run | Run Main Project.
    The result is displayed in the next figure.

    10.5.1 Syntax of a java program
    class class_name
    {
    public static void main(String[] args)
    {
    // java code goes here
    }
    }
    Explanation of the syntax

    i. class : class keyword is used to declare classes in Java

    ii. public : It is an access specifier. Public means this function is visible to all.

    iii. static : static is again a keyword used to make a function static. To execute a static function you do not have to create an Object of the class. The main() method here is called by JVM, without creating any object for class.

    iv. void : It is the return type, meaning this function will not return anything.

    v. main : main() method is the most important method in a Java program. This is the method which is executed, hence all the logic must be inside the main() method. If a java class is not having a main() method, it causes compilation error.

    vi. String[] args : This represents an array whose type is String and name is args. We will discuss more about array in Java Array section.

    Application activity 10.3

    1. Type The program prints “Hello World!”, then compile and run it.

    2. Add a print statement to display the sentence “How are you?” Compile and run the program again.

    3. Add a comment to the program (anywhere), recompile, and run it again. The new comment should not affect the result.

    4. Write a program in Java that after compilation and execution will display the messages: “Unity and Peace are the engines of development in Rwanda” and “Rwanda is a Knowledge Based Society”.

    10.5.2 Variables and Data types in Java

    Learning activity 10.4.

    1. Discuss about data type in term of Definition and Classification

    2. Using internet search a variable in java and how is declared.

    3. Given two integer x= 5; y= 4; write a java program which is calculate and display the sum of these two integers.

    The declaration of variables necessitates always specifying their types. Variables cannot exist without types and vice versa. One of the most powerful features of a programming language is the ability to define, declare and to manipulate variables.
    For example, String message;
    This statement is a declaration, because it declares that the variable named message is of type String. Each variable has a type that determines what kind of values it can store

    A. Data type

    Data type is a classification of data which tells the compiler or interpreter how
    the programmer intends to use the data. Most programming languages support
    various types of data, for example: real, integer or Boolean.

    Classification of Java Data type

    i. Primitive Java Data Types

    There are eight primitive data types supported by Java and are predefined by the language
    and named by a keyword. They are presented in the following table.

    ii. Reference Data types or Objects

    Reference variables are created using defined constructors of the classes. They are used to
    access objects. These variables are declared to be of a specific type that cannot be changed.
    For example, employee, puppy, etc.

    • Class objects and various types of array variables come under reference data type.

    • Default value of any reference variable is null.

    • A reference variable can be used to refer any object of the declared type or any compatible type.

    Example: Animal animal = new Animal(“giraffe”);

    B. Variable in Java

    A variable is a storage location (like a house, a pigeon hole, a letter box) that stores a piece
    of data for processing. It is called variable because you can change the value stored inside.
    More precisely, a variable is a named storage location, that stores a value of a particular
    data type.

    The syntax for declaration of variable is as follow:
    data_type variable_name;

    Examples

    To declare an integer variable named x, simply type:
    int x
    String message = “Hello!”;
    int hour = 11;
    int minute = 59;
    Normally, the used names for variables should help to guess what will be the different values
    to assign to them.
    Example
    String firstName, lastName;
    int hour, minute;
    Sometimes a variable is initialized by assigned to it for the first time value before it can be used or it a variable can be assigned assign a value later, as in the previous example. It is also possible to declare and initialize on the same line.

    Printing variables

    The value of a variable can be displayed by using the functions print or println. The following
    statements declare a variable named firstLine, assign it the value “Hello, again!”, and

    The output of this program is: The current time is 11:59.

    Application activity 10.4

    Write a program where you declare the variables firstname, lastname, age, level
    and com bination. This program should display like this: John Ntwali is 18
    years old and in senior 5 of MPC

    10.5.3 Types of Variables in Java

    Learning activity 10.5

    1. Is a variable declared visible always in all parts of the program? Explain
    why and give the different types.

    2. Discuss about Java Expression.

    In terms of visibility of variables in a program, there are three types of in Java namely local variable, instance variable and class variable.
    1. Local Variables

    This type of variable has the following characteristics:
    • Local variables are declared in methods, constructors, or blocks.

    Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.

    • Access modifiers cannot be used for local variables.

    • Local variables are visible only within the declared method, constructor, or block.

    • Local variables are implemented at stack level internally.

    • There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use. Example: Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method.

    2. Instance Variables

    The variables defined within a class or method is called instance variables because each instance
    of the class (that is, each object of the class) contains its own copy of these variables. Thus, the data for one object is separate and unique from the data for another. An instance variable can be declared public or private or default (no modifier).To avoid that the variable’s value is changed out-side its class, it should be declared as private. Public variables can be accessed and changed from outside of the class. The syntax is shown below given below:

    private int doors;

    Whereby:

    “private” is an access modifier
    “int” is data type
    doors is an identifier
    These variables belong to the instance of a class, thus an object. And every instance of thatclass (object) has it’s own copy of that variable. Changes made to the variable don’t reflect in other instances of that class.

    3. Class or static variables

    These are also known as static member variables and there›s only one copy of that variable that is shared with all instances of that class. If changes are made to that variable, all other instances will see the effect of the changes.
    Public class Product{
    Public static int Barcode;
    }

    10.5.4 Java keywords

    Keywords are words that have already been defined for Java compiler. They have special meaning for the compiler. Java Keywords must be in your information because you cannot use them as a variable, class or a method name. Java keywords are categorized as datatypes and access modifiers

    A. Data types

    All predefined datatypes in java are keywords eg. int, char, bool, double, float, and String

    B. Java access modifiers

    Modifiers are keywords that are added to change meaning of a definition. In Java, modifiers are categorized into two types,

    • Access control modifier

    • Non Access Modifier

    1) Access control modifier

    Java language has four access modifiers to control access levels for classes, variable methods
    and constructors.

    • Default : Default has scope only inside the same package

    • Public : Public has scope that is visible everywhere

    • Protected : Protected has scope within the package and all sub classes

    • Private : Private has scope only within the classes

    2) Non-access Modifier

    Non-access modifiers do not change the accessibility of variables and methods, but they do
    provide them special properties. Non-access modifiers are of 5 types,

    • Final

    • Static

    • Transient

    • Synchronized

    • Volatile
    1) Final: Final modifier is used to declare a field as final i.e. it prevents its content from being modified. Final field must be initialized when it is declared. Final keyword can be used with a variable, a method or a class.

    2) Static Modifier: Static Modifiers are used to create class variable and class methods which can be accessed without instance of a class.

    3) Synchronized modifier: When a method is synchronized it can be accessed by only one thread at a time.

    4) Volatile modifier: Volatile modifier tells the compiler that the volatile variable can be changed unexpectedly by other parts of the program. Volatile variables are used in case of multithreading program. volatile keyword cannot be used with a method or a class. It canbe only used with a variable.

    5) Transient modifier: When an instance variable is declared as transient, then its value
    doesn’t persist when an object is serialized

    10.5.6 Java Expressions

    Expressions are essential building blocks of any Java program, usually created to produce
    a new value, although sometimes an expression simply assigns a value to a variable.
    Expressions are built using values, variables, operators and method calls.

    Types of Expressions

    While an expression frequently produces a result, it doesn’t always. There are three types of
    expressions in Java:

    • Those that produce a value, i.e. the result of (1 + 1), Expressions that produce a value use a wide range of Java arithmetic, comparison or conditional operators.
    For example, arithmetic operators include +, *, /, <, >, ++ and %.

    • Those that assign a variable, for example v = 10

    • Those that have no result but might have a “side effect” because an expression can include a wide range of elements such as method invocations or increment operators that modify the state (i.e. memory) of a program. Example: This program here contains plenty of expressions

    Application Activity 10.5

    Look at the following three groups of statements and predict the outputs

    10.6. Elements of Java source file

    Learning Activity 10.6.


    1. Refer to the numbers in above figure; explain the different parts of this program.

    2. Following the above figure, write a program with a class that has more than one property.

    UNIT 9: VARIABLES, OPERATORS, EXPRESSIONS AND CONTROL STRUCTURES.Unit11: OOP AND JAVA