Beruflich Dokumente
Kultur Dokumente
Day 1 topics: 1. Fundamental Programming Concepts 2. Introduction to Java Programming Language 3. Introduction to Java Applications 4. Fundamental Data types in Java 5. Input and Output
This short course is intended either as a refresher course for people who have programmed in Java before, or an introduction to the Java programming language for those with programming experience but who are new to Java. The course will run over 5 days. Each day will involve around 3 hours, a mixture of Lectures covering basic theory and programming syntax programming lab exercises to reinforce the theoretical aspects by giving practical programming experience.
2
Dr David Lonie
Objectives
Learn, or be reminded of, the syntax of Java Understand key concepts of OOP Become familiar with Java Application Programming Interface (API) Practice skills in analysing, designing and implementing OO programs All to a level where you are confident and prepared for the module CMM504: Object Oriented Programming
4
Day 3:
Day 4:
Day 5:
Java Basics
Topic 1 - Fundamental Programming Concepts
What is a Program?
CORNELL AND HORSTMANN, 2008. Core Java 2 - Volume 1 Fundamentals published by Prentice Hall The official online documentation from Oracle http://docs.oracle.com/javase/ http://docs.oracle.com/javase/7/docs/index.html http://docs.oracle.com/javase/7/docs/api/index.html
5
DEFINITION: A program is a collection of instructions and data that can be executed on a computer or network of computers for: Retrieving or inputting data, Manipulating or transforming data, Storing or displaying data
6
Decisions relating to how different kinds of information will be represented in the program
Algorithm design
Creating a sequence of instructions that the machine will follow to retrieve / manipulate / store data
7 7
High-level languages allow programmers to write code in a platform independent way represent a wide and meaningful range of data types:
boolean values: (true/false), integer values, floating point values character values, string (text) values, aggregate values
perform a wide range of data processing operations: invent new kinds of data and design operations for processing data, e.g. in some languages, using classes, objects and methods 10
10
11
12
Java Basics
Topic 2 - Introduction to the Java Programming Language
Java is a widely adopted high level language using a clever mixture of the compiling/interpreting ideas Java is extremely platform-independent because The java compiler does not translate java source code directly to machine code instead it translates to an intermediate, universal machine language called: BYTECODE java programs are interpreted by a program called the java virtual machine (JVM) that runs on the operating system
13
In this way, levels of software hide the technical details of lower layers; providing an easier to understand, and easier to use, "viewpoint" from which to control the layers below.
14 14
Java is platform-independent
so code written on one platform will work on many platforms
Consider installing the JDK on your own PC or laptop too The Kit and extensive online documentation are freely available from
http://www.oracle.com/technetwork/java/javase/downloads/index.html
15
16 16
Edit phase
editor
Compile phase
Java source Code Filename.java Java compiler
Execution phase
class loader
Syntax error
interacts with the JDK on your behalf to Compile and Run your code and generate executable files Several IDEs are installed on the Schools PCs, including: Textpad and Notepad++ (editors, basic debugging help, compile, run) Netbeans and Eclipse (editors with autocomplete features, contextual help, compile, run, easy to 17 manage packages, extensive debugger, app viewer, documentation generation, etc.)
17
Logical error, Runtime errors
To compile Java source code on the command line use: javac Filename.java That creates the bytecode in the file called Filename.class To execute Java source code on the command line use: java Filename 18
18
20
Java Basics
Topic 3 - Introduction to Java Applications
Classes in Java
Object Oriented Programming: is a programming methodology in which programs are organised as interacting collections of objects Class: a template specifying the data structure, and behaviour, of things sharing a common structure and behaviour Object: an particular instance of a class An Object-Oriented program is a collection of classes.
21 22
Classes in Java
A class should define
Data stored in objects that define the object Operations (methods) that can be done by objects
class = data + operations
Classes in Java
A Java application can consist of
A single class, or Multiple classes that interact If a program uses many classes it can be organised into a package Every java program has at least one class definition The classes used in a java program can be a combination of
Classes defined by the programmer, and/or Classes from the existing set of predefined classes in the Java API
Object variables
Local variables
Object methods
Memory
Machine instructions
Classes can have variables that contain data relevant to the object Classes can have multiple methods. Methods can use local variables not visible outside the class
23 23
24
Keywords in Java
Keywords have special meaning to the compiler and are reserved by the java language. Programmers cannot use reserved words for naming classes, variables, methods etc. There are 50 Java reserved keywords: abstract case continue enum float instanceof new return switch transient boolean char do final if interface private static synchronized this try void assert catch default extends goto int package short break class double finally implements long protected strictfp throw volatile byte const else for import native public super throws while
25
26
We shall see some of these in this 5-day short course, for details on the others 26 consult http://docs.oracle.com/javase/
27
28
29
30
are ignored by the Java compiler and so can be used to create comments to document and explain the program switching-off sections of code e.g. while testing
31 31
32
33
34
Identifiers
An identifier is a programmer-selected name given to a program entity (class, variable, method). Valid identifiers consist of strings of characters, which may be: alphabetic A .. Z, a .. z numeric digit 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 dollar sign $ underscore _ Space characters ARE NOT allowed in an identifier. Identifier CANNOT begin with a digit.
Methods
Methods are the operations that can be performed by a class or by an object of the class. In the simple program earlier the only method was public static void main (String[] args) { System.out.println("Hello"); } the brackets ( ) after main identify this as a method Methods have a body, comprising a sequence of java statements between the enclosing { and the final enclosing }
Valid identifiers
abc
my_name my name
Year2000 2000Year
35 35
the particular method name main() identifies this method as the start point for execution of the java application
36
the first instruction contained in the body of main() is the first instruction of the java program to be executed
36
Methods
public static void are all reserved words of java that can qualify the definition of any method the main()method is always qualified by public static void we will say more about the keyword static later, but in brief, a static method (also called a class method) can be called without having to create an instance (object) of the class it belongs to In this case it means we can run HelloWorld.main() without having to create a particular HelloWorld object
37
Methods
the keyword void indicates that a method does not return any value after it finishes its operation the brackets after the method name main() delimit arguments (parameters) that can be passed to main() main() always has the argument String[] args (which can be used if we want to pass values into the program when calling it from the command line
37 38
38
Java Statements
instructions that make up the body of any method are enclosed between punctuation marks { and } In our simple program the only instruction was System.out.println("Hello"); but for most methods the instructions with comprise a sequence of individual java instructions (statements) Java statements typically get data, or set data, or manipulate data, or decide what instruction (statement) to execute next all simple java statements are terminated by semicolon ; there are several types of simple java statement Compound java statements begin with { and are terminated with } it is a common syntax error to forget the terminating ;
39 39
System.out.println("Hello");
This is a message expression. A message expression comprises: <target object> . <method call> System.out is the target object . is the messaging operator println("Hello") is a method call or "message" request The "message" must use a method belonging to the target object's class. In this example System.out belongs to a (pre-defined) class PrintStream println is a method of the PrintStream class that prints a line of text on a new line
40
41
42
String Constants
a string constant is any string of characters enclosed between a pair of e.g. "abcdef" double quotes " " "abc def" "abc123_<>? " "Welcome to RGU" String constants can also contain special characters designated by an escape sequence \n new line character \t tab character \\ to print a single backslash \ \" to print a double quote " \r to print a carriage return \' to print a single quote ' \b to print a backspace e.g. System.out.println("Hello\n world"); displays Hello world
43 43
e.g.
printf() is another method of the PrintStream class. This also prints the contents of the parameter between () but gives extra control through formatting instructions, for more information see
http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
44
44
Java Basics
Topic 4 - Fundamental Data types in Java
The 8 primitive Java variable types Integer Arithmetic Floating Point Variables
45
46
Primitive Variables
Variables are named program elements which enable the program to keep track of, and manipulate, data. Different types of variables store different types of data. Java has 8 primitive variable types: byte numerical data types short int storing integer values long float double char boolean numerical data types storing floating point values storing single text characters storing logical (true or false) values
47
num2
??????
declaration instructs the compiler to reserve a memory location for each variable The "size" (in bits or bytes) of memory location is determined by the data type (e.g. int needs 32 bits of memory; other data types may need more/less memory) each variable must have a name (identifier) unique to the method in which it is declared At this declaration stage the initial variable value (content of memory location) is undefined
50
name of variable
Assignment operator =
value
statement terminator
double length = 5.43, height = 2.666 ; boolean answer ; // declares a boolean variables answer = true ; // assigns value true to answer double pi ; pi = 3.1415 ; char letter ; letter = Y ;
// declares a double variables // assigns value 3.1415 to pi // declares a character variables // assigns value Y to letter
51 52
boolean answer1 = true, answer2 = false; char letter = 'c', value = '4', star = '*' ;
Assignment Instructions
An assignment instruction "moves" data into a variable (memory location) overwriting any previous contents of the variable a variable must be assigned before it its contents can be "used"
// assignment num1 = 1234 ; num2 = -987 ;
Integer Variables
We will return to char and boolean data types in more detail in later lectures Today we will concentrate on int (most commonly used integer data type, and double (most commonly used floating point data type The int data type holds whole numbers no fractional part, no decimal point Integer values can be either positive, zero or negative 1234 0 -4321 e.g.
54
num2
-987
java assignment operator is = = is a binary operator = operates on two "pieces" of information (called operands) on right of = is a value/expression/variable on left of = is a reference to a variable (i.e. variables name)
53
Integers in Java
Primitive types. The are actually four types of integers in Java: byte, short, int, long int is the most commonly used All primitive integers types are (for the technically minded) stored in signed, two's-complement, format.
Data type byte short int
long
Bits, n 8 16 32
64
A separate operator % is used to access the remainder part rem = num1 % num2 ; // both operands are int System.out.println(rem) ; Displays: 4 since 123/7 = 17 * 7 + 4
e.g. // println( )can print integer constants System.out.println(1234) ; // println( ) can print integer variables System.out.println(quotient) ; // println( ) can display results of // evaluating arithmetic expression System.out.println( num1 + num2 ) ; // println( ) can display text and // results of arithmetic expressions System.out.println("result = " + (num1 + num2)) ;
i.e. Java follows the usual mathematical rules of arithmetic in that contents of brackets are done first, then multiplication/division, then addition/subtraction If operators have equal precedence then order is determined by associativity rules
59
60
Coding Conventions
declare all local variables at the beginning of a method give variables meaningful names related to their context e.g. xCoord heightOfTriangle kilometresPerMile noOfDays variable names conventionally begin with lower case letter For readability if a variable name consists of several words use capitals as in the examples above spaces not allowed in variable names, but underscores are e.g. x_distance is ok, x distance is not
62
not every real number has a precise representation as a double value (the 16 digit accuracy limit causes rounding/precision errors) The likelihood of precision errors means that, when we start to use conditions, it is a logical error to compare two double values for equality e.g. if (x == 1.2345678) { <statement> }; // possible error // <statement> might never be executed
The float type stores numbers in only 4 bytes so has a smaller range: 1.40e-45 to 3.40e+38
63
It is safe(r) to compare double values using relational operators <, >, <=, >=
64
Type promotion
In Java, Arithmetic operations can only be evaluated between operands of the same data type. So whenever an arithmetic expression involves operands of different types, the Java compiler performs automatic type promotion e.g. If any variable in an expression is a double the others will be treated as double and the result will be a double Example of data type promotion: 101.0 / 5 will yield result 20.2 int number = 5; double average, total = 101.0 ; average = total / number ;
Java Basics
Topic 5 - Input and Output
double
65
66
In Java, Strings are objects of the String class However, because strings are used so often, a special case is made and declaring and initialising strings does not have to follow the usual syntax that applies to all other objects Strings can be declared/initialised as if they were variables
68
System.out.println( str3 + " welcome to " + str4 + " in " + str2 + " at " + str1 +
// strings can be joined (concatenated) // using the + operator
69
70
Whereas
import java.util.Scanner; // just imports the // Scanner class, not the whole package
71
72
import javax.swing.* ;
73 74
String myString ;
/* use showMessageDialog method to read in String variable */
Method name
Parameter list
This generates the following pop-up window: User input is stored is returned as a String
76
int n = Integer.parseInt(myString);
// to convert a String variable to an double
char c = myString.charAt(0);
77
Summary
Input/Output interaction with the user can be achieved in several ways: Input and Output can be done in the java application console Using System.out to print things to the console Using System.in together with a Scanner object, to accept user input from the console Input and Output can be done with pop-up windows Using JOptionPane.showMessageDialog to display messages Using JOptionPane.showInputDialog to display messages and accept user responses
79