Introduction to Java
2
A Brief History of OOP and Java
• Early high level languages– _________________________
• More recent languages– BASIC, Pascal, C, Ada, Smalltalk, C++, Java
• ______________ operating system upgrades prompted the development of the C language
• Powerful language … but not the best intro to programming– Difficult for ________________________– Does not fit modern programming strategies
3
A Brief History of OOP and Java
• Simula-67 was a language which facilitated the modeling of real-world objects– New language feature called the “_________”– A class was ______________ through
“inheritance”
• This was the foundation needed for Object Oriented Programming, OOP
• Smalltalk-80 used this concept– This is the first truly object-oriented language
4
A Brief History of OOP and Java
• The C language was extended to include “classes” and in 1983 became _________
• The Java language originally conceived to control __________________________ using the OOP concept– Thus, was meant to be platform (or ____________)
independent
• Soon this was seen as well suited for running small programs (_____________) on Internet web pages– By 1995, Netscape browsers began supporting Java
applets– This did much to establish Java as a major language
5
A Brief History of OOP and Java
• Note typical implementation of a program on different platforms
Source program
Compiler for UNIX
platform
Compiler for Windows Platform
Compiler for Mac OS Platform
Executable code for UNIX
platform
Executable code for
Windows platform
Executable code for Mac OS platform
We need ______________________________
6
A Brief History of OOP and Java
• Contrast compiler with interpreter– Compiler runs ________________, translates to
machine code for commands of whole program– _______________ translates one command at a time
• Java combines these two– Java compiler generates intermediate “___________”– An ____________________ is developed for each
platform to interpret the bytecode – Interpreter called the Java Virtual Machine or JVM
7
Phases of Java Programs
1. Edit the source code– filename._____________
2. Compile the source code into bytecodes– filename.__________
3. Load the .class file into memory– applications: stored and executed from
user's own computer– ________________: loaded from a
computer somewhere into a browser, executed by the browser
8
Phases of Java Programs
4. Verify bytecodes– check for ___________ and potential
security restrictions
5. Computer interprets bytecodes– ___________ bytecode at a time
9
Program is created in the editor and stored on disk.
Compiler creates bytecodes and stores them on disk.
Class loader puts bytecodes in memory.
Bytecode verifier confirms that all bytecodes are valid and do not violate Java’s security restrictions.
Interpreter reads bytecodes and translates them into a language that the computer can understand, possibly storing data values as the program executes.
Phase 1
Phase 2
Phase 3
Phase 4
Phase 5
DiskEditor
Compiler
Class Loader
Disk
Disk
PrimaryMemory
.
.
.
.
.
.
PrimaryMemory
.
.
.
.
.
.
PrimaryMemory
.
.
.
.
.
.
Bytecode Verifier
Interpreter
10
Programming with "Ready to Program"• Find the "Ready"
option on the program menu or click on the"_________" icon
11
Programming with "Ready to Program"
• An empty ___________ window appears
12
Java Programs
• A Java program consists of one or more classes
The name of the file and the name of the ________ must, have the
same name
Classes consist of a collection of
•
•
A Java class with a method called
main() is a Java __________.
13
Creating a Java Application
• The "Ready" environment will give you skeleton or boilerplate format for programs
• Click on File, New, and HSA Console option• A dialog box asks
for the ________ of the class
14
Creating a Java Application
• The appropriate boilerplate text appears in the edit window – note the color coding
Bold Face Java _______
Black Identifiers in Java _________ library
Blue___________
in your program
____________Comments
RedQuoted Strings
15
Creating a Java Application
• Fill in the necessary commands
• Save theprogram
Note that a dialog box will ask you for the nameBe sure to give it exactly the __________________
16
Creating a Java Application
• To run a Java program– Press the button or– Press Ctrl+R or– Press F1
• The consoleprogram showsa ___________window
17
Creating a Java Application
• Make sure to ________________ the program before quitting– The "Ready" environment will remind you
• To exit the "Ready" environment– Click the X close or– Choose File, Exit or– Use Ctrl-Q
18
Creating a Java Application
• Errors in the program– Syntax errors are found for you by the
compiler
Dialog box shows how many errors
_________ line(s)
highlighted
_______________ of error given in the
status bar
19
Introduction to Java Application Programs
• Java is an ____________ oriented programming language– Uses objects to carry out the tasks– Sends to the objects to perform
the tasks– Objects interact with each other to do the tasks– An actual object is called an ____________of
a class• The class is the declaration of or blueprint for the
object
20
Introduction to Java Application Programs
• Object oriented programs:– A collection of object interactions that solve
a problem
• Note the similarity of this definition to the definition for a program
// Welcome1.java// A first program in Java
import hsa.*;
public class Welcome1 {
public static void main (String args[]) { Stdout.println("Welcome to Java Programming");
} // end method main
} // end class Welcome1
// Welcome1.java// A first program in Java
import hsa.*;
public class Welcome1 {
public static void main (String args[]) { Stdout.println("Welcome to Java Programming");
} // end method main
} // end class Welcome1
Java program
Program Output
Comments
• Begins class definition for class Welcome1• Every Java program has at least one user-defined class
22
// Welcome1.java// A first program in Java
import hsa.*;
public class Welcome1 {
public static void main (String args[]) { Stdout.println("Welcome to Java Programming");
} // end method main
} // end class Welcome1
Java program
Part of every Java applicationApplications begin executing at main
Saving filesFile name is class name
and .java extensionWelcome1.java
Parenthesis indicate main is a _______________
Java applications contain one or more methods
23
Class Declaration
• Syntax:class ClassName extends Object{ Declarations of class members}
• Note the extends clause– specifies that the ClassName _________________
attributes and behaviors of Object– also it will ___________ new attributes and behaviors– ClassName is the subclass or derived class– _________________ is the superclass or base
class
24
Class Members• Specified between outermost set of curly braces { … }
• Members can be– ___________________ that store values– methods which perform ______________ on the variables
• The main method’s declaration
public static void main (String [ ] args){ a list of Java statements}
First statement of the program executed is first of these statements
Program terminates at last of these statements
First statement of the program executed is first of these statements
Program terminates at last of these statements
25
Java program
• Exactly one method must be called main• Methods can __________________ and
return information–____________ means main returns no
information
– For now, mimic main's first line
public static void main( String args[] )
26
Declarations
• Example
Class specification
variable name for a ________ object
Actually ________ the Console object
27
Calling an Object Method
• Example
Object nameParameters
Method name
28
Java Program
• Instructs computer to perform an action– Prints string of characters
• _____________ Stdout– Output object– Print to output window
• _____________ Stdout.println – Object calls method to display line of text– Argument inside parenthesis
• Statements must end with ___________
Stdout.println( "Welcome to Java Programming!" );
29
Java Program
• Java program using dialog box
• Note– JOptionPane ___________– ________ call– Output dialog box
• Program Output
30
A Simple Program: Printing a Line of Text
• ___________ statements – Locate the classes we use– Tells compiler to load JOptionPane from __________________package
import javax.swing.JOptionPane; // import class JOptionPane
31
A Simple Program: Printing a Line of Text
• Call method showMessageDialog of class JOptionPane– Requires ______ arguments– For now, first argument always null– Second argument is _________ to display
•showMessageDialog is a ________ method of class JOptionPane– static methods called using _____________,
dot (.) then method name
JOptionPane.showMessageDialog( null, "Welcome\nto\nJava\nProgramming!" );
32
A Simple Program: Printing a Line of Text
• Executing these lines displays the dialog box
– Automatically includes an _________ button• Hides or dismisses dialog box
– Title bar has string Message
JOptionPane.showMessageDialog( null, "Welcome\nto\nJava\nProgramming!" );
33
A Simple Program: Printing a Line of Text
• Calls static method ______________ of class System– Terminates application
• Use with any application displaying a GUI
– Because method is ___________, needs class name and dot (.)– Identifiers starting with capital letters usually class names
• Argument of 0 means application ended successfully– Non-zero usually means an error occurred
• Class System part of package java.lang– No ___________ statement needed– java.lang automatically imported in every Java program
System.exit( 0 ); // terminate the program
34
Sample Program
• Program 2.9 from text
• Note the features– Use of javax.swing routines– JOptionPane objects used
• Input __________ boxes• ___________ message boxes
– Conversion of string to _____________
35
Sample Program• Program 2.9 from text
Program Output
36
• Reads ______________ from the user, representing the numbers to be added– Method JOptionPane.showInputDialog displays
• Message called a prompt - directs user to perform an action
• Argument appears as _______________
• Then strings are converted to integers.
Another Java Application: Adding Integers// read in first number from user as a string firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
// read in second number from user as a string secondNumber = JOptionPane.showInputDialog( "Enter second integer" );
// convert numbers from type String to type int number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber );
37
• Use showMessageDialog to display results• "The sum is " + sum
– Uses the operator + to ______________ the string literal "The sum is" and sum
– Concatenation of a String and _______________• Results in a new string
Another Java Application: Adding Integers
// display the results JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE );
38
• Different version of showMessageDialog– Requires ____ arguments (instead of two as before)– First argument: null for now– Second: string to display– Third: string in ___________________________– Fourth: type of message dialog
Another Java Application: Adding Integers
// display the results JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE );
• JOptionPane.PLAIN_MESSAGE - no icon• JOptionPane.ERROR_MESSAGE • JOptionPane.INFORMATION_MESSAGE• JOptionPane.WARNING_MESSAGE• JOptionPane.QUESTION_MESSAGE
39
Values Held by Variables
• Primitive-type variables– store a __________ of the specified type (int,
double)
• Reference-type variables – store an _____________ of memory location
where value is stored– thought of as a _____________ for the object
that actually stores the values
40
Variable Declaration Syntax
• Syntax:type variable_name;ortype variable_name = expression;
• Note– type must be known to the compiler– variable_name must be a _______________– expression is evaluated and assigned to variable_name location
– In the first form, a ___________________________ (0, false, or null, depending on type)
41
Constants
• Value of object _____________– for oft used math values such as PI– for values which will not change for a given program– improve readability of program– facilitate program maintenance
• Declaration syntax:final type CONSTANT_NAME = expression;– ____________ is a Java keyword, makes a constant– type must be known by compiler– CONSTANT_NAME must be valid identifier– expression evaluated – should be placed at ___________ of class or method
42
Primitive Types
• Also known as "__________ types"– int, byte, short, and long for integer values– float and double for real/fractional values– char for letters, digits, symbols, punctuation– boolean for true and false
• Literals:– values of one of these types– 'A', -7, 3.5, true
43
Reference Types
• Needed to represent windows, buttons, inventory, students, etc.– objects ________________________ than
can be represented with simple types
• Create a class and you have created a new type whose name is the name of the class
• Types __________________ are called reference types
44
Java Provided Reference Types
• Over _______ classes already available in Java
• Examples:– String – for constant sequences of characters– StringBuffer – for variable sequences of
characters– BigInteger – for integers of "unlimited" size– BigDecimal – for fractional numbers of "unlimited"
size
45
Creating Reference Type Values:Constructors
• Primitive types use literals for their values– Meanings of literals built into compiler
• Reference types have no ___________________________________– Values must be created with the _____
operator– Example:Integer integerValue = new Integer(321);
46
Default Value: null
• Default value for reference types
Screen theScreen = null; //orScreen theScreen;
– value used if none is specified in declaration– indicates variable does _________________
to a value of that type– can later be assigned values created with ______________
47
Constructing an Object
• Use of new to create a reference type
• Class provides one or more methods– called _______________
• Syntax:
new ClassName (arguments, …)– ClassName is name of a _____________ type– arguments is a sequence of values separated by
commas– types of arguments match those permitted by ClassName
48
Ready to Program I/O Classes
• Stdin – A ___________________ class – Read all Java ___________ data types from
standard input – Possible to read several primitives from one
line
• Stdout – This is a non-instantiated class – Output ___________ data to standard output – Write data to fixed length fields and with a
fixed number of decimal places.
49
Stdin
• static byte readByte () • static short readShort () • static int readInt () • static long readLong () • static float readFloat () • static double readDouble () • static boolean readBoolean () • static char readChar () • static String readString () • static String readLine ()
– Returns the entire line of input read from the keyboard without the Return.
50
Stdout• static void print (byte b)• static void print (short s)• static void print (int i)• static void print (long l)• static void print (float f)• static void print (double d)• static void print (boolean b)• static void print (char c)• static void print (String s)
• static void println (byte b)• static void println (short s)• static void println (int i)• static void println (long l)• static void println (float f)• static void println (double d)• static void println (boolean b)• static void println (char c)• static void println (String s)
51
Ready to Program I/O Classes
• View sample program which uses hsa.* classes
• Note– Primitive type objects– Import statement for hsa.* routines– Use of static functions from non-instantiated
classes
52
Sample Problem
• Write a program to compute a sprinter’s average speed in kilometers per hour, given distance (meters) and time elapsed (seconds)
53
Program Tasks
• Display prompt for distance in meters
• Receive input from keyboard
• Display prompt for time in seconds
• Receive input from keyboard
• Compute kph
• Display titled results