07163833 Topic 1 Introduction Tojava

download 07163833 Topic 1 Introduction Tojava

of 15

Transcript of 07163833 Topic 1 Introduction Tojava

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    1/15

    X INTRODUCTION

    Starting from a failed project, Java has emerged as a popular programminglanguage within a short period of time. JavaSoft Sun MicroSystems hadsuccessfully signed up 38 licences in only one year after Java technology wasannounced. Besides that, it also successfully attracted 6000 programmers to

    attend the first seminar JavaOne Developer ConferenceTM-in 1996.

    What is so special about Java that computer industries and businesses are able toaccept it within a very short period of time compared to other new technologiesin computer history? The answer to this question is provided in subtopic 1.2:Characteristics of Java. We will now look at an overview of Java.

    JAVA ENVIRONMENT

    In the traditional language environment such as C, C++ and Pascal, source codecompilation will generate the object code in binary file format, as shown inFigure 1.1. This binary file is specific for the machine that generates it; in otherwords, it cannot be executed directly on other machines. For example, the binaryfile generated by the SPARC machine cannot be executed on a Pentium machine.

    1.1

    TTooppiicc11

    X Introduction toava

    LEARNING OUTCOMES

    By the end of this topic, you should be able to:

    1. Describe the Java environment;

    2. Outline the strengths of Java;

    3. Explain the types of Java programs; and

    4. Compile and execute a Java program.

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    2/15

    X TOPIC 1 MANUFACTURING SYSTEMS2

    To execute the program on another machine, the program source code must berecompiled on that machine. The traditional programming environment dependsheavily on this computer architecture.

    Figure 1.1: Traditional language environmentFigure 1.2 illustrates the Java programming environment. The output of a Javaprogram compilation is in the form of bytecode. Java bytecode is a set ofinstructions that is quite similar to the machine code instructions or native codefor a machine. The difference is that the bytecode is not specific to any processor.The result of a compilation can be implemented by a Java Virtual Machine (JVM),any machine that will interpret the bytecode.

    Figure 1.2:Java language environmentIf we want to implement a Java program on a Pentium machine, then we need aninterpreter or JVM for the Pentium machine. The same applies for the SPARCmachine. However, unlike traditional languages such as C and Pascal, a Javaprogram does not have to be recompiled to enable it to run on another machine.

    Lcxc"Rtq tco" Lcxc"Eqo kngt Lcxc"

    Lcxc"Kpvgtrtgvgt

    *Rgpvkwo+

    Lcxc"Kpvgtrtgvgt"*Rqygt"RE+

    Lcxc"Kpvgtrtgvgt"*URCTE+

    Uqwteg"eqfg"Hkng

    Dkpct{ Hkng Rgpvkwo

    Dkpct{"Hkng" RqygtRE

    Dkpct{"Hkng" URCTE

    Eqorkngt RqygtRE

    Eqorkngt Rgpvkwo

    Eqorkngt URCTE

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    3/15

    TOPIC 1 MANUFACTURING SYSTEMS W 3

    What are the Advantages of Using Bytecode?There are advantages in using bytecode as an intermediate and not allowingpeople to compile it into the machine language of whatever computer theywant to run. A compiler has to understand Java in order to compile it. Acompiler is a complex program, while a Java bytecode interpreter is a simpleprogram. This makes it easy to write a bytecode interpreter for a new type ofcomputer; once that is done, that computer can run any compiled Javaprogram. It would be much more difficult to write a Java compiler for the samecomputer.

    CHARACTERISTICS OF JAVA

    Java technology provides a neat development platform based on objects. Javaenvironment provides class library, which contains various classes that havealready been tested. This class library can be accessed by the programmer whowants to use it in his/her program development; furthermore, this library can beextended by the programmer according to his/her requirements. Other maincharacteristics of Java are highlighted below:

    (a) SimpleJava has the functionalities needed to implement its rich feature set. It does

    not add lots of syntactic structure or unnecessary features.

    (b) Object-OrientedThis is the core concept in Java. Almost everything in Java is either a class,an interface, a method or an object.

    (c) Platform IndependentJava programs are compiled to a bytecode format that can be read and runby interpreters on many platforms including Windows 95, Windows NT,and Solaris 2.3 and later versions.

    (d) SafeJava code can be executed in an environment that prohibits it fromintroducing viruses, deleting or modifying files, or otherwise performingdata destroying and computer crashing operations.

    (e) High PerformanceJava can be compiled on the fly with a Just-In-Time compiler (JIT) thatrivals C++ in speed.

    1.2

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    4/15

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    5/15

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    6/15

    X TOPIC 1 MANUFACTURING SYSTEMS6

    Program 1.1 shows an example of text-based application written using astructured approach.

    Program 1.1: Hello.javaLine Number

    1 // this program displays Hello world2 class Hello{3 public static void main (String args[]) {4 System.out.println(Hello world!);5 }6 }

    In structured approach, all the statements and instructions are dumped into the

    main method. Sometimes, extra methods are added to perform specific tasks.No object(s) is/are created when writing Java programs using the structuredapproach. Program 1.1 is described below:

    Line 1Line 1 in the program is a comment written by the programmer. It helps others tounderstand the nature of the program. Thus, the program becomes more readable.

    Line 2Line 2 declares the name of the class as Hello.

    Line 3Line 3 is where the program starts to execute. In this class, a method called main()contains the statements to display the Hello world! string. The main() methodmust be present in all Java applications because it is the first method that will beexecuted when an application runs (i.e. it is the where the program starts to execute).The Java technology interpreter must find this defined exactly as given or it refusesto run the program. The following describes each element of line 3:

    public: The method main() can be accessed by anything, including the Javainterpreter.

    static: This keyword tells the compiler that the main() method is usable inthe context of the class Hello. No object is needed to execute static methods.We will learn about object in Topic 5.

    void: This keyword indicates that the method main() does not return anyvalues (i.e. there is no return keyword in the main() method).

    String[ ] args: This method declares the single parameter to the main()method. The name of the parameter is args with the type of String array.

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    7/15

    TOPIC 1 MANUFACTURING SYSTEMS W 7

    Line 4The statement System.out.println(Hello world!) in the body of themethod will instruct the computer to display the message Hello world! upon

    execution.

    Lines 5 and 6Lines 5 and 6 contain two braces to close the method main() and class Hellorespectively.

    How Do We Compile and Execute a Java Application?The following activity will guide you to compile and execute Program 1.1.

    Note: Before doing this activity, please download Java DevelopmentKit (JDK) which is downloadable from myVLE (click eServices Resources for IT). The JDK version available in myVLE is version 6.0(1.6; jdk1.6.0 update 24).

    The purpose of this exercise is for you to compile and execute Program1.1. It is compulsory for you to follow all the steps to ensure that youlearn how to compile and execute a Java program using JDK.

    STEP 1By using Notepad in Windows, type program 1.1. Then, save it in afile with the name Hello.java in the jdk1.6.0_24/bin directory. (Inthis example, the Java file is saved in the C:\jdk1.6.0_24/bindirectory. You may have different directory for jdk1.6.0. Check yourcorrect jdk directory from the Windows Explorer).STEP 2aNow lauch the Command Prompt from the Start button of yourWindows by typing cmd without the quotes and then press

    as shown below.

    ACTIVITY 1.1

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    8/15

    X TOPIC 1 MANUFACTURING SYSTEMS8

    STEP 2bIn your command prompt, type cd:\ to enter the directory C:\ as shown

    below:

    Then, you need to enter the directory that stores the Java program that youhave typed in Step 1. Use the command cd to enter the correct thatdirectory as shown below:

    C:\jdk1.6.0_24\bin>cd jdk1.6.0_24/bin

    (In this example, the Java file is saved in the C:\jdk1.6.0_24/bin directory.You may have different directory name. Check your correct jdk directoryfrom the Windows Explorer).STEP 3Compile the Java program using the instruction javac Hello.java in theDOS environment. The example is shown below:

    C:\jdk1.6.0_24\bin>javac Hello.java

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    9/15

    TOPIC 1 MANUFACTURING SYSTEMS W 9

    If the error message is displayed, go to Step 4. If the error message is notdisplayed, go to Step 5.

    STEP 4Go back to Notepad and open the file that you have typed in Step 1;however, do not close the DOS window. Do the necessary correction inyour program. Make sure you save your file after the corrections. Now go

    back to the DOS window and repeat Step 3.

    STEP 5If there is no error, the compiler will generate the bytecode file that isHello.class. Now you are ready to execute your program. In order to dothis, type the command java Hello in the eDOS Window as shown below:

    C:\jdk1.6.0_24\bin>java Hello

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    10/15

    X TOPIC 1 MANUFACTURING SYSTEMS10

    1.4.2 Writing Text-based Application Using Object-Oriented Approach

    In this section, we will discuss how we can rewrite Program 1.1 using an object-oriented approach. Unlike text-based applications written in a structuredmanner, text-based applications written in an object-oriented approach need twoprograms, namely:

    x Class definition program; and

    x Class program that has main() method for execution.

    Note: The above two programs can be merged into a single program. We are notgoing to adopt this approach as this may lead to confusion.

    Now we will focus on class definition. Program 1.2 is an example of a classdefinition.

    Take note that this instruction consists of two parts. The first part ( ava)refers to the Java runtime interpreter. The second part (Hello) refers to the

    class name which has the main() method that is to be executed by theinterpreter.

    The program generates the output given below. It displays the string sent asa parameter to the System.out.println()method the first statement

    in the main() method.

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    11/15

    TOPIC 1 MANUFACTURING SYSTEMS W 11

    Program 1.2: Hello2.java (Class definition)Line Number

    1 // this program displays Hello world2 class Hello2{3 public void display(){4 System.out.println(Hello world!);5 }6 }

    Observe that there is no main() method in the above program. Below is theexplanation for Program 1.2.

    Line 1Line 1 in the program is the comment written by the programmer. It helps othersto understand the nature of the program. Thus, the program becomes morereadable.

    Line 2Line 2 declares the name of the class as Hello2.

    Lines 3 and 4Lines 3 and 4 show the declaration of a method that has name display0 Thismethod has the public keyword. It means this method can be accessed

    anywhere in this program or from other programs. Since this method does notreturn any value, void is used as the return type. The statementSystem.out.println(Hello world!) in the body of the method willinstruct the computer to display the message"Hello world!fi when the methodis called.

    Lines 5 and 6Lines 5 and 6 contain two braces to close the method display() and class Hello2respectively.

    Compile this program using steps shown in Activity 1.1. Remember that youcannot execute the program. Do you know why? This is because Program 1.2 is

    just a class definition and does not have the main() method. You may recall thatthe Java interpreter must locate the main() method in order to execute theprogram. That is why we need to have another program that will have themain() method to execute Program 1.2. The second program is discussed

    below.

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    12/15

    X TOPIC 1 MANUFACTURING SYSTEMS12

    Program 1.3: DisplayHello.java (Class program that has the main() method)Line Number

    1 // this program displays Hello world2 class DisplayHello{3 public static void main (String args[]) {4 Hello2 hello = new Hello2();5 hello.display();6 }7 }

    The detailed description for Program 1.3 is as below.

    Line 1Line 1 in the program is a comment written by the programmer. It helps others tounderstand the nature of the program. Thus, the program becomes morereadable.

    Line 2Line 2 declares the name of the class as DisplayHello0

    Line 3Line 3 is where the program starts to execute. In this class, a method called

    main() contains the statements to display the Hello world! string. The main()method must be present in all Java applications because it is the first method thatwill be executed when an application runs (i.e. it is where the program starts toexecute). The Java technology interpreter must find this defined exactly as givenor it refuses to run the program. The following describes each element of line 3:

    public: The method main() can be accessed by anything, including the Javainterpreter.

    static: This keyword tells the compiler that the main() method is usable inthe context of the class Hello. No instance of the class is needed to executestatic methods.

    void: This keyword indicates that the method main() does not return anyvalues (i.e. there is no return keyword in the main() method).

    String[ ] args: This method declares the single parameter to the main()method. The name of the parameter is args with the type of String array.

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    13/15

    TOPIC 1 MANUFACTURING SYSTEMS W 13

    Line 4This line shows how to create an object. The new Hello2 syntax instructs the

    Java interpreter to construct a new object of Hello2. hello is the object of the

    class Hello2.

    Line 5Line 5 shows the object hello calling the method display available in the classHello2.

    Lines 6 and 7Lines 6 and 7 contain two braces to close the method main() and classDisplayHello respectively.

    Compile Program 1.3 using the steps shown in Activity 1.1. Now you can executeProgram 1.3 as it has the main() method. The output will be like this:

    WRITING APPLETS

    An applet program is a Java program that can be executed from the web browser.Java Applet also supports GUI components. How do we differentiate an appletfrom an application? It is very simple. All applet programs must start withthe heading that ends with the extends JApplet keywords as shown in thefollowing program:

    Program 1.4: TestButton.java (Applet program)

    public class myApplet extends JApplet {

    public void paint(Graphics g){g.drawString(Hello world!, 50,50);

    }}

    1.5

    All applet programs must have these keywords

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    14/15

  • 7/27/2019 07163833 Topic 1 Introduction Tojava

    15/15

    TOPIC 1 MANUFACTURING SYSTEMS W 15

    x Starting from a failed project, Java has emerged as a popular programminglanguage within a short period of time.

    x The strength of Java lies in its object-oriented paradigm, which hascontributed to its success.

    x The object-oriented paradigm in Java makes it easy to reuse the applications.

    x In addition, different types of Java programs were discussed in this topic.

    x It is important to understand the types of Java programs and be able to

    compile and execute those programs.

    x Below is a summary of Java applications and applets as discussed:

    Type of Java program How it can be written Where the output willbe producedText-basedApplication

    Structured OR Object-oriented (OO)

    Command Prompt

    Frame Object-oriented Windows of the users

    PC operating systemApplet Object-oriented Web browsers

    (Internet Explorer,Netscape, etc)

    Applet

    BytecodeFrame

    Object-Oriented Programming

    Text-based Application