java chapter 2 basic applications - overview

34
Basic Applications - Overview Demo A simple application The System object Statements The swing library Message boxes and input windows Literals, Identifiers and variables Using arithmetic expressions Operators, assignments and variables Creating Decision statements Relational operators

Upload: keelie-bruce

Post on 30-Dec-2015

24 views

Category:

Documents


0 download

DESCRIPTION

Java Chapter 2 Basic Applications - Overview. Demo A simple application The System object Statements The swing library Message boxes and input windows Literals, Identifiers and variables Using arithmetic expressions Operators, assignments and variables Creating Decision statements - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Java Chapter 2 Basic Applications - Overview

Java Chapter 2Basic Applications - Overview

Demo A simple applicationThe System objectStatementsThe swing library

Message boxes and input windows

Literals, Identifiers and variablesUsing arithmetic expressions

Operators, assignments and variables

Creating Decision statementsRelational operators

Page 2: Java Chapter 2 Basic Applications - Overview

Printing a line of text

// This program prints aline of text// by: Terry Clayton// Aug 25, 2003public class HelloWorld { public static void main( String args[] ) { System.out.println("Hello\n"); }}

So what are the parts?

Page 3: Java Chapter 2 Basic Applications - Overview

Java Comments// single line comments

/* multiple line comments more here */

Why comments? Convey clearer understanding of a class or

method. Do not over comment Provide information on authors, dates and history

of changes

Page 4: Java Chapter 2 Basic Applications - Overview

Making programs readable

Use “white” blank spaces before each class and method definitionUse indentation after each parenthesisPlace comments at beginning of class and method definitions

Page 5: Java Chapter 2 Basic Applications - Overview

Defining a class

public class HelloWorldNotice the user-defined class name “HelloWorld” User defined names in Java are called

identifiers

The words public and class are Java reserved words or key words.The public class name must be the same as the java file name. HelloWorld.java

Page 6: Java Chapter 2 Basic Applications - Overview

Identifiers

Are created by the programmer for class method and variable names.They are case sensitive in Java. Hello and hello are different.

Avoid special characters like $%^ in names.Can not contain spacesUse “_” or capitalization to introduce word breaks. HelloWorld or Hello_World

Page 7: Java Chapter 2 Basic Applications - Overview

The main method

This method is the starting point for a java applicationAll Java applications have a main method it must be declared like this: public static void main( String args[] )

Page 8: Java Chapter 2 Basic Applications - Overview

Calling a method from another object

We can call and use many different methods. Some will be user defined and other will be part of the Java API System.out.println("Hello\n");

This is calling the system output stream to print the message “Hello” The \n is a new line control character. Others are \r \t \\ \”

This output goes to the command window. (your DOS window)“Hello” is a string literal they must be in double quotesAll together this forms a statement

Page 9: Java Chapter 2 Basic Applications - Overview

Statements in Java

Are the commands to perform a single task.Calling methods in one form of statement.Executing arithmetic expressions is another form of statement.Statements must end with a “;” semicolon or the compiler will report an error.

Page 10: Java Chapter 2 Basic Applications - Overview

Errors!!!

When we type our programs in we will no doubt enter it 100% correctly.NOT!!!So errors are likely.Syntax error are the most common errors. They are reported by the compiler.Others error can occur while the program is running (we will talk about these later)

Page 11: Java Chapter 2 Basic Applications - Overview

Compiling the program

Open a dos windowSet the pathChange to the drive and directory where your program is storedType: javac HelloWorld.javaThis will produce a HelloWorld.class file if it is a clean compile.Otherwise you will get a list of errors to debug

Page 12: Java Chapter 2 Basic Applications - Overview

Once compiled we can Run

To run the Java programType: Java HelloWorld in our command window.

Page 13: Java Chapter 2 Basic Applications - Overview

Adding to and changing a program

Reopen the source(.java) file with an editor.Add another print statement.SaveCompileAnd run

Page 14: Java Chapter 2 Basic Applications - Overview

Let’s fancy our Java up with a window.

// Welcome.javaimport javax.swing.*;public class Welcome { public static void main ( String arg[]) { JOptionPane.showMessageDialog(null,"Welcome\n");

// This is required with windows based java applications // it terminates the application // without this the program will hang up in older

versions System.exit(0); }}

Page 15: Java Chapter 2 Basic Applications - Overview

The import statement

Tells the compiler where to find library files.In this case in the javax.swing package (library)The java API is huge you can find documentation on it at java.sun.com/j2se/1.4/docs/api/index.html

If we forget the import statement we will get errors.Lets demonstrate!!!

Page 16: Java Chapter 2 Basic Applications - Overview

Calling a method with arguments

JOptionPane.showMessageDialog(null,"Welcome\n");

This statement calls a method that requires 2 arguments.Arguments are information passed into a method call.The first one is null this is a place holder for an argument that we will not use.The second is a message for our output window.

Page 17: Java Chapter 2 Basic Applications - Overview

Structured programming

Remember all structured programming languages have these parts Sequence - Flow of instructions Iteration – Repeating instructions Selection – Conditional statements

Key elements Variables and expressions Support for modularization

Page 18: Java Chapter 2 Basic Applications - Overview

Now for something less trivial

A program to add integersimport javax.swing.*;

public class addint {

public static void main (String arg[]) {

String fnum; String snum;

int num1,num2,sum;

fnum = JOptionPane.showInputDialog("Enter First Number?"); snum = JOptionPane.showInputDialog("Enter Second Number?"); num1=Integer.parseInt(fnum); num2=Integer.parseInt(snum);

sum = num1+num2;

JOptionPane.showMessageDialog(null,"The sum is"+sum,"Results", JOptionPane.PLAIN_MESSAGE);

System.exit(0); }

}

Page 19: Java Chapter 2 Basic Applications - Overview

Keywords or Reserved words

importpublicsuperwhilecharfloatdoublereturnclass

forintifelseextendsvoid….

Can not be used as programmer declared identifier.

Page 20: Java Chapter 2 Basic Applications - Overview

Variables and literals

To make the preceding program work we need some way to store the values that will be used in the computation.String variable can store alpha numeric text and special symbols. “115”, “Hello”, “Ctow&%//gt12” are all

string literals

int – short for integer variable can store integer numbers only. 3.14 is not an integer 3 is.

Page 21: Java Chapter 2 Basic Applications - Overview

Variables and memory

Choose meaningful namesString variable can be large and consume lots of memory. Each character is stored in unicode (a 2 byte derivation of ascII)Integer variables are 4 byte in size and store information in binary format.

Page 22: Java Chapter 2 Basic Applications - Overview

Other Variables types

String – This is actually a class typeThese are all primitive data types int short long float double character byte boolean – True or False

Page 23: Java Chapter 2 Basic Applications - Overview

Primitive data typesdefined by type size and values

type size values

boolean varies true, false

char 16 unicode (ascII)

byte 8 -128 to 127

short 16 -32768 to 32767

int 32 -2147483648 to 2147483647

long 64 Really big

float 32 16 digits of decimal precision with range of 45 on exponent

double 64 10 times the range on exponent

Page 24: Java Chapter 2 Basic Applications - Overview

Declaring and initializing variables

int x = 10;Or

int x;X=10;

Page 25: Java Chapter 2 Basic Applications - Overview

Type casting

Converting one type to anotherThis is need for example

float rad, circ; circ = (float)Math.PI * rad; // this type casts double value of Math.PI to a float.

without this a syntax error message will be generated by the compiler.We can type case and primitive or object type.We are not required to type cast when converting to a larger storage class.

ie from float to double.

Page 26: Java Chapter 2 Basic Applications - Overview

Concatenation

System.out.println(“Hello “ + name );System.out.printlin(“Pay = “ + pay);

We can display unicode characters using the \uXXXX escape sequence.See page 723 for unicode table

Page 27: Java Chapter 2 Basic Applications - Overview

Constants

Help to make programs easier to maintain.Help to make the programs easier to read.

final double TAXRATE = 0.06;

Sales = Amt * quant * ( 1 + TAXRATE);

Page 28: Java Chapter 2 Basic Applications - Overview

Dialog boxes

The swing API provides classes and methods for creating and using dialog boxes. JOptionPane.showInputDialog(“prompt”); JoptionPane.showMessageDialog( null, “The

message”, “Windowtitle”, JoptionPane.INFORMATION_MESSAGE)

ERROR_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE are other options.

Page 29: Java Chapter 2 Basic Applications - Overview

Converting String values into integers

numint=Integer.parseInt(numstr)

Integer is a wrapper class. A class implementation of an integer value.The parseint method converts the string argument to an integer and returns its value.

Page 30: Java Chapter 2 Basic Applications - Overview

Calculations - Arithmetic

A = B + C;Sum = num1 + num2;These are arithmetic expressions.Composed of binary operators= ( assignment )+ ( addition )

Page 31: Java Chapter 2 Basic Applications - Overview

Operators Precedence

Binary Operators:*/%+- % - Modulus operator (integer division

remainder)

From left to right (infix notation)The equal sign evaluates from right to leftParenthesis can modify order of operations A = C * (B + 2) vs A = C * B + 2

Page 32: Java Chapter 2 Basic Applications - Overview

The scanner class

Import java.util.Scanner;

String Name;Scanner linput = new

Scanner(System.in)

Name = linput.nextLine();…

Page 33: Java Chapter 2 Basic Applications - Overview

Lets write a program

To compute the results of several arithmetic operations.

Page 34: Java Chapter 2 Basic Applications - Overview

Homework #2 (CS211/212)

Design, code and test problem 2.6, 2.10Due one week after date assignedTurn in source code and class files on a labeled disk as per syllabus.jc2e6.java and jc2e10.javaAlso turn in class files