jaeki song java lecture 02 introduction to java -the first java application-
TRANSCRIPT
JAVA
Jaeki Song
Lecture 02Introduction to Java
-The First Java Application-
JAVA
Jaeki Song
Outline
• Basic components of Java
• Data type
• Operators
• JBuilder
• Java Application
JAVA
Jaeki Song
What is 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
Jaeki Song
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
Jaeki Song
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
Jaeki Song
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
Jaeki Song
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
Jaeki Song
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.
JAVA
Jaeki Song
The Basics of Java Program
• To write meaningful program, learn the programming language’s special symbols, words, syntax rules, and semantic rules– Syntax rules: tell you which statements are legal, or accepted by the
programming language– Semantic rules: determine the meaning of the instructions
• Programming language– A set of rules, symbols, and special words
Public class Welcome{ public static void main (String [ ] args) { System.out.println (“Welcome to Java Class”); }}
JAVA
Jaeki Song
Data
• Categorize data as variable or constant
• Constant– Data cannot be changed
• Variable– Data might be changed– Variable are named memory locations that
your program can use to store values
JAVA
Jaeki Song
Data Types
Primitive data types
integral Floating-point Boolean
char byte short int long float double
The fundamental data types in Java
A data type that deals with integers, or numbers without a decimal part
A data type that deals with decimal numbers
A data type that deals with logicalvalues
JAVA
Jaeki Song
The Integral Data Type
Type Minimum Value Maximum Value Size in Bytes
byte - 128 127 1 (8 bits)
short - 32,768 32,767 2
Int - 2,147,483,648 2,147,483,647 4
long - 9,223,372,036,854,775,808 9,223,372,036,854,775,807 8
char 0 65535 2
JAVA
Jaeki Song
The boolean Data Type
• Boolean logic is based on true-false comparisons
• Boolean variable– A variable that holds a Boolean value (true or
false)
Operator Name Example
! Not&& and true && true true| | or false | | false false
JAVA
Jaeki Song
Floating-point Data Types
Type Minimum Value Maximum Value Size in Bytes
Float - 3.4 * 1038 3.4 * 1038 4
double - 1.7 * 10308 1.7 * 10308 8
JAVA
Jaeki Song
Arithmetic Statements
Operator Description Example
+ addition 45+2, the result is 47
- subtraction 45-2, the result is 43
* multiplication 45*2, the result is 90
/ addition 45/2, the result is 22 (not 22.5)
% modulus (remainder) 45%2, the result is 1
JAVA
Jaeki Song
Order of Precedence
• When more than one arithmetic operator is used in an expression, Java uses operator precedence rules to determine the order in which operations are performed to evaluate the expression– Higher level of precedence: *, /, %– Lower level of precedence: +, -
• Expression exercise
JAVA
Jaeki Song
Cast Operator
• Implicit type coercion– When a value of one data type is automatically changed to
another data type– Generate unexpected results
• E.g.3 / 2 + 5.0 = 6.0
• To avoid implicit type coercion, Java provides for explicit type of conversion through use of a cast operator (also called the type conversion or type casting)(dataType) expression
e.g.(int) (7.9) 7
(double) (15) / 2 (double) (15 / 2)
7.5
7.0
JAVA
Jaeki Song
Declaration and Assignment• 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 variableName e.g.
int x; //Declare x to be an integer variable• After a variable is declared, you can assign a value to it by using an
assignment statementvariable = expression;e.g.
x = 1; //Assign 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 step
int x;x = 1 int x = 1;
JAVA
Jaeki Song
Example
int firstNumber;
int secondNumber;
int finalNumber;
firstNumber = 7;
secondNumber = 8;
finalNumber = firstNumber + secondNumber
firstNumber ?
secondNumber ?
finalNumber ?
firstNumber 7
secondNumber 8
finalNumber 15
JAVA
Jaeki Song
Increment and Decrement Operators
• Increment operator– Increases the value of a variable by 1
• E.g.int count = 0; count = count + 1;
– Pre-increment: ++ variable (++x)• First the value of x is incremented by 1, and then the new value of x is used to evaluate
the expression– E.g. x = 5; y = ++ x; (after execution, x = 6 and y = 6)
– Post-increment: variable ++ (x ++)• First the current value of x is used in the expression, and then the value of x is
incremented by 1– E.g.
x = 5; y = x ++; (after execution, x = 6 and y = 5)
• Decrement operator– Decreases the value of a variable by 1
JAVA
Jaeki Song
String and the Operator +
• The operator + can be used to concatenate two strings as well as a string and a numeric value or a character– E.g.
String str;
str = “Sunny”;
str = str + “Day”; (results in “Sunny Day”)
JAVA
Jaeki Song
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
JAVA
Jaeki Song
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;
JAVA
Jaeki Song
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
*/
JAVA
Jaeki Song
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”);
}
}
JAVA
Jaeki Song
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
JAVA
Jaeki Song
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
JAVA
Jaeki Song
Java Naming Conventions
• Standards were originally proposed by Sun and have been widely adopted by the Java programming community
• Packages– The prefix of a unique package name is always written in all-
lowercase ASCII letters and should be one of the top-level domain names
– Use dots to separate the parts• E.g.: com.sun.eng, com.objectcentral.javatools
• Classes– Class (and interface) names should be nouns descriptive of the
purpose of the class– Names are in mixed case, beginning with a capital and with the
first letter of each internal word capitalized– Use complete words and avoid abbreviations
• E.g.: Point, Shape, MovieEditor, ClientList
JAVA
Jaeki Song
Java Naming Conventions• Methods
– Methods should be verbs descriptive of the purpose of the method– Names are mixed case with the first letter lowercase and the first letter
of each internal word capitalized – There are prefix conventions for general types of methods, such as
using get and set for getters and setters• E.g.: getOrigin, findSmallest, drawGraph, saveMoney
• Variables– Except when used as constants, all variables are named using mixed
case with a lowercase first letter, and with intenral words starting with capital letters
– Use one-letter variable names only for temporary variables• E.g.: myMovie, editedMovie, backgroundColor
• Constants– Names should be all uppercase with words seperated by underscores
(“_”)• e.g.: MAX_SIZE, TERM_LIMIT
JAVA
Jaeki Song
Creating First Application
• The Java 2 Platform, Standard Edition
• JBuilder7
JAVA
Jaeki Song
JBuilder: Interface
Main menuProjecttoolbar
Projectpane
Structurepane
ContentpaneFile tab
File view tab
JAVA
Jaeki Song
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”); }
}
JAVA
Jaeki Song
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
Jaeki Song
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
Jaeki Song
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
JAVA
Jaeki Song
Creating Class
• When you create a class, first you must assign a name to the class, and then you must determine what data and methods will be part of the class– An optional class modifier
• public, final, or abstract
– They keyword class– Any legal identifier you choose for the name of your classe.g.public class Employee{ ………..}
JAVA
Jaeki Song
Access Control
• The goal of class creator (those who create class) is to build a class that exposes only what’s necessary to the client programmer (the class consumers who use the class in their application) and keeps everything else hidden– Class creator can change the hidden portion without
worrying about the impact to anyone else– Class creator can change the internal working of the
class without worrying about how it will affect the client programmer
• Java use three boundaries– public, private, and protected
JAVA
Jaeki Song
Access Modifier: Class
• Class access modifiers– public, final, or abstract
• public classes are accessible by all objects– public classes can be extended or used as a basis for
any other class
• In the class, allowable field modifiers are public, private, protected, and final
– Private means that no other classes can access a field’s value and only methods of the same class are allowed to set or get
JAVA
Jaeki Song
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) { … }}
JAVA
Jaeki Song
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 { }
JAVA
Jaeki Song
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
JAVA
Jaeki Song
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
JAVA
Jaeki Song
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
JAVA
Jaeki Song
Output Dialog
• showMessageDialog ( null, “string”);– A method of class JOptionPane– Two arguments
• Syntax
JOptionPane.showMessageDialog(null, “string”);
JAVA
Jaeki Song
Example: Output Dialog
import 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 }}
JAVA
Jaeki Song
Output
JAVA
Jaeki Song
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”);
JAVA
Jaeki Song
Example: Add Integer
import 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); }}
JAVA
Jaeki Song
Output
JAVA
Jaeki Song
Example: Convert Length
• Write a program that takes as input given lengths expressed in feet and inches. The program should then convert and output the lengths in centimeters using GUI. Assume that the given lengths in feet and inches are integers