Sie sind auf Seite 1von 20

Aims of the Java Basics course

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

Room B12 d.p.lonie@rgu.ac.uk


1

Java Basics: outline


Day 1: Day 2: Introduction to Java, Basic Input and Output in Java. The fundamental data types in Java. Decision Control Structures: Boolean expressions, if statements, if-else statements, switch statements. Control Structures for code repetition; forloops, while-loops, do-while-loops. Creation of basic menus. Object-oriented programming Classes and objects. Instance variables. Methods. Class variables. Class Methods. Using existing classes in Java from the Java API. String Class. Array class. Math class.
3

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:

Textbooks and Resources


DEITEL and DEITEL , 2011 Java How to Program, published by Pearson Education

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

Fundamental Programming Concepts


Program design involves data design + algorithm design
Data design

Fundamental Programming Concepts


At the Machine level instructions and data are stored in memory as:
bits: bytes: words: values 0 or 1 (bit = binary digit) values 00000000, ..., 11111111 (1 byte = 8 bits), (typically) 4 bytes = 32 bits or 8 bytes = 64 bits

Decisions relating to how different kinds of information will be represented in the program
Algorithm design

programs written in Assembly Languages


using sequences of very basic machine instructions which fetch, store and operate on bits, bytes or words to process data there is no universal standard for machine instructions; different manufacturers develop different instruction sets 8

Creating a sequence of instructions that the machine will follow to retrieve / manipulate / store data
7 7

Programming in machine language is slow, painstaking and error-prone


8

Fundamental Programming Concepts


Above the Machine level sits an operating system (e.g. Windows, Mac-OS or Linux) operating system is a collection of programs sitting at a level above the machine level which can:
hide the detail of machine-level operations handle input and output from devices manage secondary (disk) storage: use file systems e.g. Files and folders load and run application programs manage multiple tasks (programs)
9 9

Fundamental Programming Concepts


Using programs running on the Operating system, most programming is done using High-level languages e.g. Ada, Basic, C, FORTRAN, Java, C++, C#, Cobol, Pascal, Python, Visual Basic

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

Fundamental Programming Concepts


Object-Oriented languages use structures called Objects that consist of data and methods
Data describes the properties of objects Methods are actions that we can do to objects

Fundamental Programming Concepts


Programs written in a high level programming language must be translated into machine language. This is typically done: either using a compiler analyses the program and converts it into machine-specific binary that runs directly on the hardware or using an interpreter analyses and converts program into an intermediate level code that runs on another program that instructs hardware at machine level Code of high-level languages may be platform independent but the executable application must be compiled specifically for different platforms.
12

Advantages of Object-Orientation include:


Simplicity it is easy to model real world things and their interactions using objects and methods Extensibility new or improved functionality is easy by creating new objects or modifying/extending existing ones Efficiency (well designed) objects from one project can be re-used in others with minimal reprogramming Modularity each object is self-contained and internal working is hidden ideal for big projects and team programming
11

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

Java Virtual Machine


Java Program Java virtual machine Operating System "Real" machine

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

Why choose Java?


Java language has a relatively simple structure
So Java is relatively easy to learn

Java Development Kit


To run java programs the Java Runtime Environment (JRE) must be on the machine, this provides the (interpreter) JVM To develop java programs a Java Devlopment Kit (JDK) must be on the machine
it includes the JRE within it edition relevant to us is the Java Platform, Standard Edition (Java SE) currently at version 7 this is already installed on all the School of Computing machines

Java is intrinsically Object-Oriented Java is multi-purpose


its possible to do almost anything in Java

Java is platform-independent
so code written on one platform will work on many platforms

Java is relatively secure


Java has limited access to the system it runs on

Java has a huge set of existing packages available


so usable solutions exist to many common programming tasks

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

Java is free, widely used and strongly supported!


15

15

16 16

Editors and IDEs


It is possible to write Java code on any text editor and then compile and run the code from the command line But better to use one of the many Integrated Development Environments (IDE). An IDE
acts as the place where you actually write your Java code

Java Software Development Cycle


Design phase
Program design Pseudocode

Edit phase
editor

Compile phase
Java source Code Filename.java Java compiler

Network delivery phase (applets only)


Web browser or Applet viewer

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

bytecode verifier Java bytecode Filename.class JVM

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

Java Software Development Cycle


It may take several cycles of the above sequence to get a program operating correctly, since errors can creep in at different stages of the cycle: compile phase may involve
Syntax Errors = mistakes in code construction, mistyping keywords the compiler provides of list of any syntax errors it finds

execution phase may involve


Runtime errors = errors that cause the program to end due to operations that are impossible to complete e.g. division by zero errors, user input of unexpected type e.g. string when number is expected 19 Logical Errors = errors due to faulty logic or code design, the code gives results, but the results are incorrect
19

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

Classes Definitions in Java


classes are defined in the following way: public class Nameofclass { statements defining class go here }
public and class are examples of java keywords class always introduces a class definition In this example the class name is Nameofclass, an identifier (i.e. a name) selected by the programmer. It is conventional to begin a class name with an Upper Case (capital) letter. classes must be public to be run or to be visible to other classes the statements and structures defining the class are enclosed within a pair of curly braces{} after the class name
25

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/

The most basic Java program


The most basic java programs consist of a single class containing a single method called main()
public class HelloWorld { public static void main (String[] args) { System.out.println("Hello"); } } The source code for this program must be saved in a file named HelloWorld.java matching the name of the class HelloWorld that contains the code Note that java is case sensitive
27

The most basic Java program


public class HelloWorld { public static void main (String[] args) { System.out.println("Hello"); } } Note that the program consists of a single class, and all the statements lie between the { } after the name of the class
28

27

28

The most basic Java program


public class HelloWorld { public static void main (String[] args) { System.out.println("Hello"); } } To be executable a java application must have a method called public static void main It is the label that the compiler looks for to tell it where the program code begins The instructions for main are placed between matching braces{}
29

The most basic Java program


public class HelloWorld { public static void main (String[] args) { System.out.println("Hello"); } } The only instruction that this program carries out is System.out.println("Hello"); which simply tells Java to print the text Hello to the systems default output
30

29

30

Comments in Java Code


Any part of a program between /* a line of code after // and */

Comments in Java Code


There are actually three syntax styles for creating comments: // single line comments follow a double forward-slash /* multi-line comments can be created * by enclosing the comment in this way * and this can continue over several lines */ /** a javadoc documentation comment which * can also continue over several lines * but which can also be used to generate * documentation using the javadoc utility */ Notes: (1) do not forget the */ at end of multiple line comments. (2) dont need a * at start of other lines, but it is conventional
32

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

Java program layout


The Java compiler (mostly) ignores "spacing" characters e.g. the space character, tab characters, new line characters So we can use "spaces" to make programs easier to read. There are program layout conventions, which we will introduce and follow as our knowledge of java syntax expands A syntax error will occur if unmatched left or right braces exist. To make errors easier to spot: Always align{ with its corresponding } Indent the code between {and corresponding } Leave vertical space between methods
33

Program Layout Conventions


/** File: HelloWorld * A simple program to say Hello */ public class HelloWorld { /** * main method @param args not used */ public static void main (String[] args) { System.out.println("Hello"); } }

33

Always indent sections of code between {and corresponding } 34

Always align{ with its corresponding }

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

Invalid identifiers stars***

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

Displaying Output in Java


System.out is the standard output object System.out is a pre-defined object in the Java language (automatically available to any Java application) System.out is coded so that it "knows" how to display information on a command / terminal window. We can call methods of the System.out class without worrying about how they work.
This is one principle of object-oriented programming because (wellwritten) classes define self-contained descriptions you can use them without knowing the internal details of how they work.
41

Displaying Output in Java


System.out.println("Hello"); The message println("Hello"); invokes a method that prints a line of text the brackets after the method name println enclose the parameter that is to be printed here the parameter "Hello" is a string constant Hint: you can also use println( ) statements to help to debug your programs. e.g. using println statements to tell you that the code has reached checkpoints and to print values of variables at those checkpoints. 42

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

Displaying Output in Java


print() is another method of the PrintStream class. this prints the contents of the parameter between () but does not force the output onto a new line System.out.print("Hello") ; System.out.print("world"); Produces: Helloworld

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

Data Types in Java


We noted that Program design involves data design + algorithm design Data design = Deciding how all the relevant information will be represented in the program Java uses software objects to model real world objects Different properties of objects can be represented by different data types Data types can be simple or as complex as necessary to replicate realworld behaviour But very often, properties are built out basic bits of data consisting of numbers or characters To represent these, Java has a set of pre-defined, so-called, primitive data types

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

Storing Data Values in a Java Program


java compiler must be informed that storage for any variable is required i.e. each variable must be declared before it can be used java compiler arranges this storage by allocating machine memory In Java each variable must have data type (e.g. int, double) each variable must have a unique name (identifier) so the programmer and compiler can refer to the memory location The variable name becomes a reference to the memory location Once the variable has been declared, values can be allocated to it
48

Syntax of Variable Declarations


int num1 , num2 ; // declares 2 integer variables

Variable declaration (conceptual viewpoint)


// declaration int num1, num2 ;

memory locations num1


??????

num2
??????

separator data type names of variables statement terminator

boolean answer ; // declares a boolean variable double x, y, z ; // declares 3 double variables


49

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

Syntax of Variable Assignment


int num ; // declares an integer variables
num = 25 ; // assigns value 25 to num

Syntax of Variable Assignment


For convenience, variables can be declared and assigned in one step, e.g. int num1 = 1234, num2 = 7 ;

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

memory locations num1


1234

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

Example: Integer Arithmetic in a Java Program


public class IntegerCalc { public static void main(String[] args) { // declare temporary local variables int x = 1234, y = 7 ; int sum, diff, product, quotient, rem ; // do some arithmetic calculations and display results System.out.println( "x = " + x + "\n" + "y = " + y) ; sum = x + y ; System.out.println("x + y = " + sum ) ; diff = x - y ; System.out.println("x - y = " + diff ) ; prod = x * y ; System.out.println("x * y = " + prod ) ; quot = x / y ; System.out.println("whole part of x/y = " + quot ) ; rem = x % y ; System.out.println("remainder of x/y = " + rem) ; } 55 }

Range of Possible Integer Values


There are limits to the maximum and minimum integer values that can be stored in Java. These limits can be accessed using the following constants: Integer.MAX_VALUE Integer.MIN_VALUE Note: convention constant identifiers use upper case only. e.g. Instructions to print max and min possible int values System.out.print( "biggest integer = " ); System.out.println( Integer.MAX_VALUE ); System.out.print( "smallest integer = " ); System.out.println( Integer.MIN_VALUE ); Outputs: biggest integer = 2147483647 smallest integer = -2147483648 Other data types (i.e. byte, short,int,long, float,double) have analogous MAX_VALUE and a MIN_VALUE
56

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

Notes on Division Operator


When applied to two integers the division operator / does integer division i.e. gives the whole part of the answer and discards any fractional part. int num1 = 123, num2 =7, quot, rem ; quotient = num1 / num2 ; // both operands are int System.out.println(quotient) ; Displays: 17 even though 123/7 = 17.57142857.

Bits, n 8 16 32
64

Distinct values, 2n 256 65,536 4,294,967,296


1.8 1019

Range 128 to 127 32768 to 32767 2,147,483,648 to 2,147,483,647


9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
57

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

Warning: dividing by zero is a program error (but is not a syntax error)


58

Displaying Results of Arithmetic Precedence and Associativity Rules


Operator(s) () * + / % Precedence highest medium lowest Associativity left to right left to right left to right

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

Displaying Results of Arithmetic


Note that: System.out.println("result = " + (num1 + num2)) ; is used rather than System.out.println("result = " + num1 + num2) ; Because "result = " + num1 + num2 is not an integer, it is a string. e.g. if num1 = 4, num2 = 5 then string printed by "result = " + num1 + num2 will be: result = 45 To get the result of the addition we have to use brackets: "result = " + (num1 + num2) to get result = 9 This is because it is a "feature" of java that when one of the operands of + operator is a string then all operands are converted to strings and concatenated concatenated means joined together
61

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

double data type


Variables of type double represent floating-point values i.e. numeric values with whole number and fractional parts Examples of Java constants of the type double: 1.234 -4.321 0.0 1.234E6 (representing 1.234x106) 7.65E-12 (representing 7.65x10-12) In Java, the double type used 8 bytes to store a number, resulting in a range of values that can be stored of:
4.94 x 10-324 to 1.798 x 10308 float double

Notes on data type double


Main advantage of double over float is not the range of values, but the accuracy of number storage type gives approx 8 decimal digit accuracy type gives approx 16 decimal digit accuracy

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

Command Line Scanner objects JOptionPane methods

double

floating point division

int is promoted to double

Contrast that with integer division: 101 / 5 gives 20

65

66

Java Input via the Command Window


To "interact" with users, programs need input and/or output operations e.g. get data from an input device (e.g. keyboard) into memory display data on output device (e.g. the screen) When a Java application runs a window called the console or command window appears on the screen. Weve seen already that System.out.println() method prints things to the console. output operations to the command window can be "delegated" to a predefined output. e.g. System.out is the standard output object input operations from the command window can be "delegated" to a predefined input. e.g. System.in is the standard input object
67

Some notes on Strings in Java


In Java, Strings are used to contain, manipulate and output textual data In Java Strings are not one of the primitive data types
(since Strings can be of any length, so the amount of memory needed to store them cant be specified at the declaration stage)

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

Some notes on Strings in Java


String str1, str2;
// declares 2 string references

Getting user input via the Console


System.out.print() or System.out.println() are convenient for generating output for user There is not a similar input command However to achieve user-input, direct from the command window, we can use the Scanner class which is part of a package called util If using a Scanner object we do need to beware of potential problems if user enters wrong type of input e.g. a run-time error if code expects an integer but gets a String

str1 = "The Robert Gordon University"; str2 = "MSc in Software Technology";


// stores text in the strings

String str3 = "Hello", str4 = "CMM001";


// declares/initialises 2 string objects in one line

System.out.println( str3 + " welcome to " + str4 + " in " + str2 + " at " + str1 +
// strings can be joined (concatenated) // using the + operator

69

70

Using existing packages


A package is an existing bundle of classes, containing useful methods that extend the basic functionality of Java To use a method from a package we must first import it at the head of the code file in which we will need the methods We can load entire packages, or just individual methods
import java.util.*; // loads entire util package // when placed at very beginning of program before public Class MyProgram { }

Example of use of Scanner


import java.util.*; // loads all Methods in util package // needs to be at very beginning of program before // create a Scanner object to read keyboard input Scanner sc = new Scanner(System.in); // to input users next keyboard input into variable num System.out.print("Enter an integer:"); int num = sc.nextInt(); // sc is the scanner object // .nextInt() method converts next input to an integer

Whereas
import java.util.Scanner; // just imports the // Scanner class, not the whole package
71

72

Example of use of Scanner


// .nextDouble() method converts next input to a double System.out.print(Enter a floating-point number:); double x = sc.nextDouble(); // .next() method converts the next input to a String System.out.print(Enter your name:); String name = sc.next(); // .next().charAt(0) method converts the first // character of next input into a char System.out.print(Enter a letter or number:); char ch = sc.next().charAt(0);

Using the JOptionPane Class


System.in and System.out interact in a rather basic way via command window. For a more sophisticated feel to user interaction it would be nice to have pop-up messages or pop-up windows asking for user input. A pre-existing class of object that we can be used is the JOptionPane class from the swing package JOptionPane is a predefined classes, with useful methods for performing input and output operations JOptionPane methods are defined in a package ("library") called javax.swing Again the Java compiler needs to be told where to find JOptionPane So at the very start of the program code (i.e. before the public class filename declaration) we need to include the following import statement

import javax.swing.* ;
73 74

Some Methods defined in JOptionPane class


public String showInputDialog(String message );

Example of Input Using showInputDialog


// Declare a String variable to store user input

String myString ;
/* use showMessageDialog method to read in String variable */

Means method is visible outside the class

This is the return type

Method name

Parameter list

myString = JOptionPane.showInputDialog( "Enter integer value ) ;


public void showMessageDialog(null, String message ); This (loosely) is how the methods are defined inside the package that we load. Examples of how we use the methods once the package has been loaded with import javax.swing.* ; are given on the next pages
75

This generates the following pop-up window: User input is stored is returned as a String
76

Processing Output from showInputDialog


The showInputDialog method returns a String! If we want the input to represent a number then we have to convert the String to the appropriate data type Numerical data types have method that parse string to extract any numerical value. These are called as follows:
// to convert a String variable to an integer

Example of Output Using showMessageDialog


JOptionPane.showMessageDialog(null, "This is the text to be displayed" );
/* The second parameter is the string containing the message. The first parameter tells the method where to position the window. If we use null it will just centre the message in the centre of the screen */ This generates the following pop-up window:
78

int n = Integer.parseInt(myString);
// to convert a String variable to an double

double x = Double.parseDouble(myString); To extract a character variable then use charAt(0):


// storing the first character of a String in a char

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

Das könnte Ihnen auch gefallen