A Introduction to Java - First Practical - into to Java programming language. PDF

Title A Introduction to Java - First Practical - into to Java programming language.
Course Foundations of Software Design and Development
Institution Edinburgh Napier University
Pages 16
File Size 1001.8 KB
File Type PDF
Total Downloads 61
Total Views 138

Summary

First Practical - into to Java programming language....


Description

SET07110 Foundations of Software Design and Development Introduction to Java Date: Sep/2016 Duration / Location

2 Hour Practical Session in the JKCC

Level

07 Introduce the Java Development Kit, Java Virtual Machine and Java Compiler

Aims Write Compile and Run a simple Java Program using the Windows Command Line Learning Outcomes

Equipment required

L02 – The session partially covers requirement for Learning Outcome 2 Windows 7 PC Java Development Kit Version 8 Text Editor

Description During this session, you will write, compile and execute programs using the Java programming language. You will be introduced to the Java Development Kit (JDK) and some of the tools that it contains. This session addresses part of Learning Outcome 2 -- Implement simple algorithms in Java. We will be writing, compiling and executing our first programs using a basic text editor, the Java Development Kit (JDK) and the Microsoft Windows command line environment. Later in the module, you will be using more sophisticated development environments.

SET07110 Foundations of Software Design and Development

There are three key stages to writing a Java application.   

Writing the source code Compiling the source code into a machine readable format Executing the program

Stage 1: Writing the Source Code Any text editor can be used to write Java source code.  

Notepad Notepad++

Simple text editor built in to Windows Sophisticated text editor with context aware formatting

Alternatively, an Integrated Development Environment (IDE) can be used     

JBuilder -- Commercial IDE eclipse -- Open Source, popular with professionals Dr Java -- Simple IDE, Popular with beginners ProgZoo.net -- Online learning environment Many others -https://en.wikibooks.org/wiki/Java_Programming/Java_IDEs

We will be using Notepad this week, then eclipse for the module

Stage 2: Compiling the Source Code We need the Java Development Kit (JDK) to compile java source code into a machine-readable format. This is freely available from http://www.java.com and should be preinstalled on the University’s computers. We will be using Java SE (standard edition) Version 8.

Stage 3: Executing a Java Program We need the Java Runtime Environment (JRE) to run programs. The Java Development Kit (JDK) includes the JRE.

SET07110 Foundations of Software Design and Development

Exercise 1: Hello World We will be writing, compiling and executing our first program using notepad, a basic text editor, the Java Development Kit (JDK) and the Microsoft Windows command line environment. If you are unfamiliar with the Microsoft Windows Command Line environment, some useful information can be found online at: 

https://technet.microsoft.com/enus/library/cc754340(v=ws.11).aspx

The following examples will familiarise you with some of the key commands available from the command line environment 

http://www.cs.princeton.edu/courses/archive/spr05/cos126/cmdprompt.html

Open the Microsoft Windows command prompt from the start menu by typing cmd into the run dialogue box

You will be presented with a command prompt where you can type commands

SET07110 Foundations of Software Design and Development

Useful Shortcuts The up and down arrow keys allow us to scroll through previously entered commands The tab key attempts to auto-complete filenames that exist in the current directory e.g. java H(tab) will fill in java HelloWorld.java if that file exists At the command prompt, change the current path to point at your “H” drive. This is your own network drive space and is available to you from any university computer To change the current drive – type the drive letter followed by a colon and press return  H:  h:

Change to the root directory of current drive –> cd space backslash

To change to the root directory of the current drive type:  cd \

SET07110 Foundations of Software Design and Development Make a new directory called SET07110

To make a directory called SET07110in the current location type:  md SET07110 or  mkdir SET07110

Change the current directory to point at the newly created directory

To change the current directory type:  cd SET SET07110 or  cd H:\ SET07110

To check the contents of a directory type dir. This will list the files and directories contained in the directory.

SET07110 Foundations of Software Design and Development

Our new directory shows 2 directories named “.” and “..” A single . refers to the current directory. Typing cd . does nothing A double .. refers to the parent directory. Typing cd .. should move up a directory to the root of your drive Go back into your new directory We can start a windows program (extensions .bat, .com, .exe) by typing its name (with or without the file extension) at the command prompt. The following command opens Notepad.exe and attempts to load a file named HelloWorld.java from the current directory. As the file does not exist, you will be prompted to create a new file (if it already existed it would be opened for editing). Run Notepad.exe, creating a new file by passing the filename as a parameter.  Notepad HelloWorld.java

You can of course create the file the conventional way by opening notepad and saving the file to the desired location. However, beware that notepad will attempt to use the .txt file extension. Note on Windows Filenames Windows does not typically distinguish between upper and lower case in file names To execute a windows application from the command prompt it is not necessary to provide the extension. Notepad.exe can be executed by typing any of the following    

notepad Notepad notepad.exe NotePAd.EXE

Although Windows is not case sensitive, other operating systems are and it is good practice to get into the habit of using proper naming conventions.

SET07110 Foundations of Software Design and Development Writing Source Code Type in following code and save the file.

Even a simple program can be confusing for anyone not familiar with programming. For now, we will accept much of the syntax, which will become clear during the course of the module as you practice writing programs.

For the time being, the following elements are described: 

The first line defines the name of our class (HelloWorld)



The “class” name must exactly match the filename prefix. This is case sensitive. For example a java source file defining a class named HelloWorld must be stored in a source file named HelloWorld.java A java source file defining a class named Person must be stored in a source file named Person.java



The program does one thing; outputs the text Hello World to the default system output. Can you identify the line of code that achieves this?

SET07110 Foundations of Software Design and Development

Note on Java Naming Conventions Java filenames must start with a letter, underscore or a dollar sign ($) otherwise, the java compiler will complain. However, $ and _ are discouraged and the convention is to start filenames with an upper case letter [A-Z]. Java source code files should be named using CamelCase where identifiers are constructed from multiple words (without spaces), each word starting with a capital letter. Source files should be named using the suffix .java Valid java source filenames that do follow recognised conventions include   

Student.java UndergraduateStudent.java PostgraduateStudent

Valid java source filenames that do not follow recognised conventions include   

student.java $tudent.txt _Undergraduatestudent.java

Invalid names include  

1Student.java Śtudent.java

Full details of the lexical structure of the Java language is available online at http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8

Compiling Source Code to Byte Code The Java compiler javac.exe, which is located in the bin directory of your JDK installation*, is used to convert Java source code to Java byte code Pass the name of the source file, including the filename extension, as a parameter to the compiler from the command line as shown below

SET07110 Foundations of Software Design and Development

*By default this is located at “C:\Program Files\Java\jdk1.8.0_11” for JDK version 1.8.0_11

You may need to enter the following command (check the location) at the command line first to tell windows where java is installed. The command window must be closed and reopened before continuing. setx path "%path%;C:\Program Files (x86)\Java\jdk1.8.0_91\bin" If no compilation errors occur then a file named HelloWorld.class will be generated in the current directory. Use the command dir to check the contents of the current directory If any compilation errors occur, a summary of these errors will be displayed. Try to resolve these yourself or discuss with your peers before asking for assistance. Most likely, you have typed the code wrong. As an example, the following error occurs due to the class name starting with a lowercase h but the code is stored in a file with the prefix HelloWorld.

SET07110 Foundations of Software Design and Development

Q: Which option from the choices below should be used to fix the compilation error in the example above?

A.

Change the file name to helloWorld.java

B.

Change the class name to HelloWorld

What is the reason for your answer?

Would the other option work also?

The following web page from the Java documentation highlights some common problems encountered by programmers. http://docs.oracle.com/javase/7/docs/webnotes/install/windows/jdk-installationwindows.html

SET07110 Foundations of Software Design and Development

Executing Our First Program If our code compiles to java bytecode correctly then it can then be executed on the JVM To achieve this simply type the following command at the terminal window java HelloWorld You should see the following output

Additional Tools There are many other useful tools provided with the JDK. A comprehensive list is available at http://docs.oracle.com/javase/8/docs/technotes/tools/ An example is the Java Decompiler (javap.exe) which can be used to provide useful information about class files (bytecode) when you don’t have access to the source code http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javap.html To execute the decompiler, pass the name of the file containing the byte code to the decompiler as a parameter at the command line 

Examine your HelloWorld.class file using the Java Decompiler

SET07110 Foundations of Software Design and Development

A Closer Look at the HelloWorld Application

Read the short web page at https://docs.oracle.com/javase/tutorial/getStarted/application/index.html Note the use of comments within the code. It is essential to include comments that describe key features of your code that could be difficult for another programmer to understand.

Java applications consist of one or more classes. The class containing the entry point to a java program (the code we wish to execute first) must contain a “main method” with the signature public static void main (String[] args) The signature of a method defines its accessibility, return type, name and expected input parameters 

Access The keyword public indicates that the method can be accessed from outside the defining class. The keyword static indicates that the method can be accessed without first creating an instance of the class (more on this in future weeks)



Return Type The keyword void indicates that the method does not return anything. Methods could return a value, some text or any other type that we can define ourselves, or any type that is predefined in the Java language.



Method Name main is the name of the method



Parameters (String[] args) indicates the parameters that are expected as input to the method. The main method requires an Array of Strings which is named args (arguments).

SET07110 Foundations of Software Design and Development

Data types and arrays will be covered in more detail next week. For now, we only need to know that we can pass a list of words into our program from the command line in the same way that we passed parameters to the Java compiler, the JVM and the Java decompiler. When you typed “javac HelloWorld.java” at the command line you were passing the String “HelloWorld.java” to the windows executable program javac.exe Methods can have any number of parameters including none An array is a list of items of the same data type and is defined using square brackets after the data type e.g. String[] myList = new String[10]; This defines a list of Strings called myList of length 10. When created the list contains 10 empty strings (a string of length 0 or “”) To access the individual elements of an array we provide an index myList[0] accesses the first element of the array myList[1] accesses the second element and so on. System.out.println(myList[0]); will print the first element of the list to the console terminal. Note that the first element of the list uses index 0. For an array containing n elements the individual elements are accessed using indices 0 to n-1. When we start the HelloWorld application from the command line we can also pass a list of words (separated by spaces) to the application. e.g. If we start our program using the command java HelloWorld my name is John Doe the (String[] args) will be populated as follows args[0] -> my args[1] -> name args[2] -> is args[3] -> John args[4] -> Doe

Exercise 2 Modify your HelloWorld source code to output the text “Hello ” followed by your forename and surname which should be passed from the command line to the program as parameters

Remember to recompile your modified code

SET07110 Foundations of Software Design and Development

Questions The questions provided here will allow you to assess your understanding of this week’s material.

Q 1:

What is the function of the program (javac.exe)?

Q 2:

What is the function of the JVM (java.exe)?

SET07110 Foundations of Software Design and Development

Q 3:

What is the function of the java decompiler (javap.exe)?

eclipse For the remainder of the module we will predominantly be using the Integrated Development Environment eclipse. A walkthrough for beginners to eclipse is provided on Moodle in the Week 1 practical folder. You should attempt to repeat this week’s “HelloWorld” exercise in eclipse before next week. More information on the topics covered this week (and some additional related topics) is available at http://chortle.ccsu.edu/Java5/index.html You should read chapters 3-5 in your own time if you cannot complete this during the practical session

SET07110 Foundations of Software Design and Development

Additional Exercises for the Technically Adventurous Each week, additional exercises will be provided for those already familiar with programming. If you are new to programming, you are not expected to complete these at this time. You may find the exercises useful in subsequent weeks as you become more familiar with programming concepts.

Project Euler Project Euler is an online repository of coding challenges designed to promote your problem solving skills. Can you design an algorithm using pseudocode for the first of these challenges in small groups of 2 or 3. Those of you with programming experience may like to design an algorithm in Java for solving the problem.

Multiples of 3 and 5 Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

ProgZoo ProgZoo is an online learning environment that includes tutorials and exercises designed to give you practical experience of coding in Java Complete the introductory tutorial at http://progzoo.net/wiki/Flags_Tutorial...


Similar Free PDFs