java chapter 2 basic applications - overview
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 PresentationTRANSCRIPT
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
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?
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
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
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
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
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[] )
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
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.
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)
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
Once compiled we can Run
To run the Java programType: Java HelloWorld in our command window.
Adding to and changing a program
Reopen the source(.java) file with an editor.Add another print statement.SaveCompileAnd run
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); }}
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!!!
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.
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
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); }
}
Keywords or Reserved words
importpublicsuperwhilecharfloatdoublereturnclass
forintifelseextendsvoid….
Can not be used as programmer declared identifier.
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.
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.
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
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
Declaring and initializing variables
int x = 10;Or
int x;X=10;
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.
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
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);
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.
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.
Calculations - Arithmetic
A = B + C;Sum = num1 + num2;These are arithmetic expressions.Composed of binary operators= ( assignment )+ ( addition )
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
The scanner class
Import java.util.Scanner;
String Name;Scanner linput = new
Scanner(System.in)
Name = linput.nextLine();…
Lets write a program
To compute the results of several arithmetic operations.
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