Download presentation
Presentation is loading. Please wait.
Published byChristal Cunningham Modified over 9 years ago
1
Jaeki Song JAVA Lecture 02 Introduction to Java -The First Java Application-
2
Jaeki Song JAVA Outline Basic components of Java Data type Operators JBuilder Java Application
3
Jaeki Song JAVA 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
4
Jaeki Song JAVA 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
5
Jaeki Song JAVA 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
6
Jaeki Song JAVA 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
7
Jaeki Song JAVA 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
8
Jaeki Song JAVA 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.
9
Jaeki Song JAVA 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”); }
10
Jaeki Song JAVA 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
11
Jaeki Song JAVA Data Types Primitive data types integralFloating-point Boolean char byte short intlong floatdouble 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 logical values
12
Jaeki Song JAVA The Integral Data Type Type Minimum Value Maximum Value Size in Bytesbyte - 128 127 1 (8 bits)short - 32,768 32,767 2Int - 2,147,483,648 2,147,483,647 4long - 9,223,372,036,854,775,808 9,223,372,036,854,775,807 8char 0 65535 2
13
Jaeki Song JAVA 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 && andtrue && true true | |orfalse | | false false
14
Jaeki Song JAVA Floating-point Data Types Type Minimum Value Maximum Value Size in BytesFloat - 3.4 * 10 38 3.4 * 10 38 4double - 1.7 * 10 308 1.7 * 10308 8
15
Jaeki Song JAVA 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
16
Jaeki Song JAVA 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
17
Jaeki Song JAVA 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
18
Jaeki Song JAVA 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 statement variable = 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;
19
Jaeki Song JAVA Example int firstNumber; int secondNumber; int finalNumber; firstNumber = 7; secondNumber = 8; finalNumber = firstNumber + secondNumber firstNumber?secondNumber?finalNumber?firstNumber7secondNumber8finalNumber15
20
Jaeki Song JAVA 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
21
Jaeki Song JAVA 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”)
22
Jaeki Song JAVA 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
23
Jaeki Song JAVA Constant A constant represents permanent data that never changes final datatype CONSTANTNAME = VALUE; In java, the world final means that the constant cannot be changed. e.g. final double PI = 3.14159;
24
Jaeki Song JAVA 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 */
25
Jaeki Song JAVA 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”); }
26
Jaeki Song JAVA 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
27
Jaeki Song JAVA Formatting Output Escape characters CodeConceptResult \t Horizontal tab Moves insertion point eight spaces to the right \b Backspace Moves insertion point one space to the left \n New line Moves insertion point down one line and to the left margin \r Carriage return Moves insertion point to the left margin \” Double quote Used to print a double quote character
28
Jaeki Song JAVA 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
29
Jaeki Song JAVA 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
30
Jaeki Song JAVA Creating First Application The Java 2 Platform, Standard Edition JBuilder7
31
Jaeki Song JAVA JBuilder: Interface Main menu Project toolbar Project pane Structure pane Content pane File tab File view tab
32
Jaeki Song JAVA 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 89 th Street”); System.out.println(“ Lubbock, TX, 79413”); }
33
Jaeki Song JAVA 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 */
34
Jaeki Song JAVA 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
35
Jaeki Song JAVA 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
36
Jaeki Song JAVA 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 class e.g. public class Employee { ……….. }
37
Jaeki Song JAVA 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
38
Jaeki Song JAVA 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
39
Jaeki Song JAVA 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) { … }
40
Jaeki Song JAVA 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 { }
41
Jaeki Song JAVA Methods and Method Header public static void main(String[] args) //method header { …… } The method as accessible to all classes This method is for class Three parts return value method name arguments lists Void means that this method does not return a value when it is called Method name is main. Main method is the usual starting point for all stand-alone Java program Piece of data. args is an identifier for any string or character argument
42
Jaeki Song JAVA Body Code { System.out.println(“ Jaeki Song”); System.out.println(“ 1234 89 th 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 that takes a string argument. It returns its value to the System.out device
43
Jaeki Song JAVA 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
44
Jaeki Song JAVA Output Dialog showMessageDialog ( null, “string”); –A method of class JOptionPane –Two arguments Syntax JOptionPane.showMessageDialog(null, “string”);
45
Jaeki Song JAVA 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 }
46
Jaeki Song JAVA Output
47
Jaeki Song JAVA 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”);
48
Jaeki Song JAVA 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); }
49
Jaeki Song JAVA Output
50
Jaeki Song JAVA 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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.