Jaeki Song
description
Transcript of Jaeki Song
Jaeki Song
Lecture 01Introduction to Java Programming
Instructor
• Name: Jaeki Song• Office: BA 712• Office Hours
Tuesday & Thursday 10:00-Noon or by appointment
• Office Phone: (806) 742-8036• E-mail: [email protected]• Website: http://jsong.ba.ttu.edu
Course Materials
• Required TextbookDeitel and Deitel, Java How to Program, 4th
Edition, Prentice Hall
Course Objectives
• Objectives– Introduce OOP using JAVA– Understand JAVA programming– Understand the issues related to web-
programming using JAVA– Emphasize critical thinking about new
developments
Grading
• First Exam: 20%
• Second Exam: 20%
• Third Exam: 30%
• Assignments: 30%
Course Structure
• Fundamentals of programming
• Object-oriented programming
• Graphics programming
• Developing comprehensive programming
Objectives
• Basics of Programming Language
• What is Java?
• Introduction to Java Applications
Program Development Life Cycle (PDLC)1. Analyze Problem- Review program specification- Meet with users- Identify program components
2. Design Program- Group activity into modules- Devise solution algorithms- Test solution algorithms
3. Code Program- Translate solution algorithm- Enter program code into computer4. Test Program
- Remove any syntax error- Remove any logic error
5. Formalize Solution- Review program code- Review documentation- Implement program
6. Maintain Program- Identify errors- Identify enhancements
Structured Programming
• Hierarchical Input Process Output (HIPO) chart
• Algorithmic Thinking– Pseudocode– Flowchart– Storyboard
Top-Down Design
• One method that is useful when defining the procedures to be used is termed Top-Down Design. With Top-Down Design you– break down a problem down into functional
tasks or parts;– break each part, or task, into sub-parts;– continue the ‘chunking-up’ process until the
sub-parts, or sub-tasks, are very simple and easily described.
HIPO Chart
Main
ProcessInitialization
DeclareVariable
Print Report
Read arecord
CalculateAccumulate
totalPrint
Detail Calculateaverage
Print totalAnd averages
Wrap-up
Calculatediscount
CalculateGross amount
Calculate netAmount due
Algorithmic Thinking
• Correct– Using logical constructs and valid data in an organized
way • The steps will be carried out correctly • The program will make suitable response
• Efficient– The program’s ability to deliver a results in a time short
enough to be useful and in a space small enough• An algorithm can be defined in various ways. Two
common ways include the use of pseudocode and flowchart
Pseudocode
• uses English-like phrases to describe the instructions– List the actions using
keywords
– Depicts logical grouping or structures using indentation
MAIN MODULE:Call InitializationCall ProcessCall Output
END
PROCESS MODULE:Do While not End of FileRead a recordCall CalculateCall AccumulatePrint Detail LineEnd Do
RETURN
CALCULATE MODULE:If Hours > 40 thenCall overtimeElseCall Regular timeEnd If
RETURN
Flow Chart
ProcessSymbol
Represent process
I/OSymbol
Makes data available for processing (input) orDisplaying (output) of process information
Decisionsymbol
Represents a decision that determines whichOf number of alternative paths is to be followed
Connectorsymbol
Represents any entry form, or exit to, another partof the flow chart
Terminalsymbol
Represents the beginning, the end, or a point of Interruption or delay in a program
Storyboard
Interest Calculator
Principal:
Interest Rate:
Months:
Amount Paid:
CalculateCalculate ClearClear
principalField
amtlField
clearButton
monthslField
calButton
monthsLabel
intLabel
principalLabel
intField
amtLabel
What is Java?
• Computer programming language– Computer program
• A set of instructions
– Programming language• A set of words, symbols, and codes
– Syntax• A set of grammar or rules that specify how the
instructions are to be written
History of Java
• Designed in the early of 1990s by Sun Microsystems
• Provide animation and interactivity on the World Wide Web– Web browsers have provided the opportunities
to run Java applets
• The fastest growing language
Java Language
• Standard language used for programming, creating applets, servlets, JavaBeans, and enterprise components
• Java is simple
• Java is object-oriented language
• Java is distributed
Java Language
• Java is interpreted– Need an interpreter to
run Java program
– The program are compiled into Java Virtual Machine (JVM) code called bytecode
Java Source Code
Java compiler
Java Bytecode Code
Java Interpreter
CPU
JVM
Java Language
• Java is robust– Reliabile
• Detect many problems
• Java is secure• Java is platform-independent• Java is portable
– Can be run on any platform without being recompiled
• Java is multithreaded
Java Virtual Machine (JVM)
• Interpreter for the Java programming language– a simple platform that all Java applications run
on.
• Comes with Java Development Kit (JDK)– Contains JVM and run-time system– Java 2 SDK
• www.sun.com
Java Environment• Editor
– Integrated Development Environment (IDE)• Jbuilder, J++, Forte, Visual Cafe
• Compiler– Translate into bytecode
• For Sun Microsystems- javac (included in SDK)• Class loader produces .class file
• Loading– Applications
• loaded and executed using Java Interpreter java example.class
– Applet• loaded in the browser and could be viewed by applet viewer using the html file in
which the applet is placed.
Creating First Application
• The Java 2 Platform, Standard Edition
• JBuilder4 or 5
JBuilder: Interface
Main menuProjecttoolbar
Projectpane
Structurepane
ContentpaneFile tab
File view tab
Example
/* Assignment 1 Printing on the screen Programmer: Jaeki Song Student ID : 999-99-9999 Date : September 2001 Program Name: Address */
public class Address{
public static void main(String[] args) //method header{ System.out.println(“ Jaeki Song”); System.out.println(“ 1234 89th Street”);
System.out.println(“ Lubbock, TX, 79413”); }
}
Documentation
• Comments– Block comment
/* ….. */
– Line comment: //– e.g.
/* Assignment 1 Printing on the screen Programmer: Jaeki Song Student ID : 999-99-9999
Date : September 2001 Program Name: Address */
Java Class
• Java program consists of pieces called classes– Existing classes in Java Class Libraries
• Known as Java APIs (Applications Programming Interfaces)
• Classes consists of pieces called methods– Perform tasks and return information
Java Class
• A single class resides in a single Java source file with extension .java
• public class Address { …. }• The source code is Address.java.
– The name of the class is the name of the file
• Class name and file name must match
Main Method
• The class which contains the main() method is the class that starts running the program
• Every Java application (not applet) has a main class
public class Address{ public static void main(String[] args) { … }}
Access Modifier
• Specifies the circumstances in which the class can be accessed– E.g.: public class Address
{
…….
}
• Public indicates that this code can be access by all objects and can be extended or used as a basis for another class
• The contents of the class must be enclosed in braces { }
Methods and Method Header
public static void main(String[] args) //method header{
……
}
The methodas accessible to all classes
This method is for class
Three parts• return value
• method name
• arguments lists
Void means that this methoddoes not return a value when it is called
Method name is main. Mainmethod is the usual starting point for all stand-alone Java program
Piece of data. args is an identifier for any string or character argument
Body Code
{ System.out.println(“ Jaeki Song”); System.out.println(“ 1234 89th Street”); System.out.println(“ Lubbock, TX, 79413”); }
Out is the object that represents the default display
System is the name of the class (program-defined class)
Println is the name of a method thattakes a string argument. It returns its value to theSystem.out device
Variable
• Used to store data– Variable declaration
• To use a variable, you declare it by telling the compiler the name of the variable as well as what type of data it represents
datatype variableNamee.gint x; //Declare x to be an integer variabledouble interest; char a; //Declare a to be a character
valueint x, y, z;
Assignment
• After a variable is declared, you can assign a value to it by using an assignment statementvariable = expression;
e.g.
x = 1; //Assing 1 to variable x
x = y + 1 ; //assign the addition of y and 1 to x
– You can declare variable and initialize it in one stepint x;
x = 1 int x = 1;
Constant
• A constant represents permanent data that never changesfinal datatype CONSTANTNAME = VALUE;
In java, the world final means that the constant cannot be changed.
e.g.final double PI = 3.14159;
Numeric Data Types
• The Java Built-In data type– int: always 32-bit signed integer.– short: 16-bit integer.– byte: 8-bit integer (new).– long: 64-bit singed integer.– float: 32-bit floating-point number.– double; 64-bit floating-point number.– char: Unicode (16-bit, language independent
character value, international standard.– boolean: true or false, false is not 0 in Java
Numeric Operators
Operator Example Equivalent
+= i+=8 i = i+8
-= f-=8.0 f = f-8.0
*= i*=8 i = i*8
/= i/=8 i = i/8
%= i%=8 i = i%8
Increment and Decrement Operators
• Increment or decrement a variable by 1X++ or X--; suffix
++X or –X; prefix• Suffix operator: the variable is used in the
expression first, then incremented or decremented by 1
• Prefix operator: the variable is first incremented or decremented by 1, then used in the expression
Relational Operators
• Relational operator
Operator Name Example Answer
< less than 1 < 2 true<= less than or equal to 1 <=2 true> greater than 1 > 2 false>= greater than or equal to 1 >= 2 false= = equal to 1 = = 2 false!= not equal to 1 != 2 true
Boolean Operators
• Boolean variable– A variable that holds a Boolean value (true or
false)
Operator Name Example
! Not&& and true && true true| | or false | | false false
Programming Style and Documentation
• Appropriate Comments– Every program has the following block comment
appear at the top of the source code file:/* Programmer: Jaeki Song
Course: ISQS 6337
File Name: Assign1XXXX.java
Description: A brief description of the program
*/
Programming Style and Documentation
• Naming conventions– Make sure the meanings of the descriptive means you choose are
straightforward– Names are case-sensitive
• For variables and methods– Use lowercase– If the name consists of several words, concatenate them into one, making the first
word lowercase and capitalizing the first letter of each subsequent worde.g: calculateSalary
• For class names– Capitalize the first letter of each word
e.g; ComputeSalary
• For constants– All letters are capitalized
e.g.: MAX_VALUE = 10
Programming Style and Documentation
• Proper indentation and spacing– Clear and easy to read
e.g.:
public class Test
{
public static void main(String args[])
{
System.out.println(“Example”);
}
}
Programming Errors
• Syntax error– Result from errors in cod construction
• E.g.: mistyping, omitting some necessary punctuation, using an opening brace without a corresponding closing brace
• Logical error– Occur when a program does not perform the way it was
intended to
• Run-time error– Cause a program to terminate abnormally
• E.g.– Input error: the user enters an unexpected input value that the program
cannot handle– Division by zero
Formatting Output
• Escape characters
Code Concept Result
\t Horizontal tab Moves insertion point eight spaces to the right
\b Backspace Moves insertion point one space to the left
\n New lineMoves insertion point down one line and to the leftmargin
\r Carriage return Moves insertion point to the left margin
\” Double quote Used to print a double quote character
Using Java Swing Class
• Refers to the new library of GUI– A component set that makes up all the objects of GUI
• Displays output using windows or dialog boxes– Input Dialog and Output Dialog
• Use packages– Predefined classes grouped into categories of related
classes called packages (sometimes called java class libraries or java applications programming interface (API))
– JOptionPane• Defined in a package called javax.swing
Output Dialog
• showMessageDialog ( null, “string”);– A method of class JOptionPane– Two arguments
• Syntax
JOptionPane.showMessageDialog(null, “string”);
Example: Output Dialogimport javax.swing.JOptionPane; //import class JOptionPane
public class Address{
public static void main(String[] args) //method header{ JOptionPane.showMessageDialog(
null, " Jaeki Song\n1234 89th Street\n Lubbock, TX, 79413"); System.exit(0); //terminate program }}
Output
Input Dialog
• Uses predefined dialog box from class JOptionPane called input dialog– Allows the user to input a value for use in the
program– Syntax
JOptionPane.showInputDialog(“ Enter first integer”);
Example: Add Integerimport javax.swing.JoptionPane;
public class AddInt{ public static void main (String args[]) {
String number1, number2; //first and second string entered by user int numInt1, numInt2, sum; number1 = JOptionPane.showInputDialog(“Enter first number”); number2 = JOptionPane.showInputDialog(“Enter second number”); numInt1 = Integer.parseInt(number1); numInt2 = Integer.parseInt(number2); sum = numInt1 + numInt2; JOptionPane.showMessageDialog(null, “The sum is “ + sum, “Results”,
JOptionPane.PLAIN_MESSAGE); System.exit(0); }}
Output
JDK Packages
Package Name Description
java.applet Classes to facilitate using applets
java.awtAbstract Window Toolkit; classes to Facilitate graphics user interfaces
java.netClasses used for networking and client/Server applications
java.io Classes to facilitate input and output
java.langClasses to facilitate data types, threads,Strings, and others
java.util Classes used for dates, vectors, and others