Download First Java Program - New York University

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Introduction To Computers and Programming
Lecture 2: Your first program
Professor: Evan Korth
New York University
Road Map for Today
• Syntax vs. style
• Types of errors
• Your First Java Programs!
–
–
–
–
File names and class names
Comments (and why they are important)
The main() method
Outputting text via the standard output object
• Printing Several Lines
• Using Escape Characters
–
–
–
–
Blocks
importing classes from other packages
JOptionPane
System.exit()
• Reading
– Liang 5: finish Chapter 1, Sections 1.9 – 1.12
– Liang 6: finish Chapter 1, Sections 1.8 – 1.11
– Liang 7: finish Chapter 1, Sections 1.8 – 1.10
Review
•
•
•
•
•
•
•
What is a machine language?
What is an assembly language?
What is a high-level programming language?
What are some examples of high-level languages?
What does the term “portable” mean?
What does the Java compiler do?
What is the JVM?
Syntax vs. Style
• Syntax: The rules of a language
• Style: Good programming practices
Errors
• syntax error – Can be picked up by the compiler.
Your program will not compile and the compiler
will try to communicate the location of the error to
you.
• run time or logical error – The compiler cannot
pick up the error because the program is perfectly
legal Java. However, the program does not run as
intended.
A Sample Java Program
• Java uses some notations that may appear strange
at first.
• Let’s look at a sample program.
7
2.2
A First Program in Java: Printing a
Line of Text
• Application
– Program that executes using the java interpreter
• Sample program
– Show program, then analyze each line
 2003 Prentice Hall, Inc. All rights reserved.
8
1
2
3
4
5
6
7
8
9
10
11
12
13
// Fig. 2.1: Welcome1.java
// Text-printing program.
public class Welcome1 {
Outline
Welcome1.java
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( "Welcome to Java Programming!" );
} // end method main
} // end class Welcome1
Welcome to Java Programming!
Program Output
 2003 Prentice Hall, Inc.
All rights reserved.
9
2.2
1
A First Program in Java: Printing a
Line of Text
// Fig. 2.1: Welcome1.java
– Comments start with: //
(style)
• Comments ignored during program execution
• Document and describe code
• Provides code readability
– Traditional comments: /* ... */
/* This is a traditional
comment. It can be
split over many lines */
• Common error: When using traditional blocks always
remember to close the comment.
– Javadoc comments: /** ... */
/** This is a special type of comment used
by the javadoc command to automatically
create html documentation of classes,
methods and variables */
 2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
10
2.2
2
A First Program in Java: Printing a
Line of Text
// Text-printing program.
– Another line of comments
– Note: line numbers not part of program, added for reference
3
– Blank line (style)
•Makes program more readable
•Blank lines, spaces, and tabs are white-space
characters
–Ignored by compiler
 2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
11
2.2
4
A Simple Program: Printing a Line of
Text
public class Welcome1 {
– Begins body of class declaration for class Welcome1
• Every Java program has at least one user-defined class
• Keyword: words reserved for use by Java
– class keyword followed by class name
– Keywords can only be used for intended purpose(s)
• Modifier: defines attributes of classes, methods and variables
– public tells the compiler which methods can access the
method it modifies. For now, all methods will be declared
public.
• Naming classes: capitalize every word (style)
– SampleClassName
 2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
12
2.2
4
A Simple Program: Printing a Line of
Text
public class Welcome1 {
– Name of class called identifier
• Series of characters consisting of letters, digits,
underscores ( _ ) and dollar signs ( $ )
• Does not begin with a digit, has no spaces
• Examples: Welcome1, $value, _value, button7
– 7button is invalid
• Java is case sensitive (capitalization matters)
– a1 and A1 are different
• Try to use identifiers that “tell the story” of the program.
– For now, use public keyword
• Certain details not important now
• Mimic certain features, discussions later
 2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
13
2.2
4
A Simple Program: Printing a Line of
Text
public class Welcome1 {
– Saving files
• File name must be class name with .java extension
• Welcome1.java
– Left brace {
• Begins body of every class
• Right brace ends class declaration (line 13)
7
public static void main( String args[] )
– Part of every Java application
• Applications begin executing at main
– Parenthesis indicate main is a method
– Java applications contain one or more methods
 2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
14
2.2
7
A Simple Program: Printing a Line of
Text
public static void main( String args[] )
• Exactly one method must be called main
– Methods can perform tasks and return information
• void means main returns no information
– More on this later in the semester
• For now, mimic main's first line for subsequent programs
8
{
– Left brace begins body of method declaration for main
method
• Ended by right brace } (line 11)
• Note: Two different acceptable styles in this program.
However, it is bad style to mix these in one program.
 2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
15
2.2
9
A Simple Program: Printing a Line of
Text
System.out.println( "Welcome to Java Programming!" );
– Instructs computer to perform an action
• Prints string of characters
– String - series characters inside double quotes
• White-spaces in strings are not ignored by compiler
– System.out
• Standard output object
• Print to command window (i.e., MS-DOS prompt)
– Method System.out.println
• Displays line of text
• Argument inside parenthesis
– This line known as a statement
• A statement is an instruction or a method call
– An instruction is the smallest executable entity within a
programming language
• Statements must end with semicolon ;
 2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
16
2.2
11
A Simple Program: Printing a Line of
Text
} // end method main
– Ends method declaration
13
–
–
–
–
} // end class Welcome1
Ends class declaration
Can add comments to keep track of ending braces
Remember, compiler ignores comments
Comments can start on same line after code
 2003 Prentice Hall, Inc. All rights reserved.
17
blocks
• Any code enclosed between braces is called a
block.
• In the previous program there were two blocks.
– The class block (a block is required for a class)
– The method block (a block is required for a method)
• These are just two types of blocks. We will see
others later in the semester.
• Good Programming Habit: Get into the habit of
adding the right brace as soon as you enter the left
brace (then fill in between).
 2003 Prentice Hall, Inc. All rights reserved.
18
2.2
A Simple Program: Printing a Line of
Text
• Compiling a program from the command prompt
– Open a command prompt window, go to directory where
program is stored
– Type javac Welcome1.java
– If no errors, Welcome1.class created
• Has bytecodes that represent application
• Bytecodes passed to Java interpreter
• Let’s see how to compile it with our IDE.
– Compile
– Execute
 2003 Prentice Hall, Inc. All rights reserved.
19
2.2
A Simple Program: Printing a Line of
Text
• Executing a program
– Type java Welcome1
• Interpreter loads .class file for class Welcome1
• .class extension omitted from command
– Interpreter calls method main
Fig. 2.2
Executing Welcome1 in a Microsoft Windows 2000 Command Prompt.
 2003 Prentice Hall, Inc. All rights reserved.
20
2.3
Modifying Our First Java Program
• Modify example in Fig. 2.1 to print same contents
using different code
 2003 Prentice Hall, Inc. All rights reserved.
21
2.3
Modifying Our First Java Program
• Modifying programs
– Welcome2.java (Fig. 2.3) produces same output as
Welcome1.java (Fig. 2.1)
– Using different code
9
10
System.out.print( "Welcome to " );
System.out.println( "Java Programming!" );
– Line 9 displays “Welcome to ” with cursor remaining on
printed line
– Line 10 displays “Java Programming! ” on same line with
cursor on next line
 2003 Prentice Hall, Inc. All rights reserved.
22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Outline
// Fig. 2.3: Welcome2.java
// Printing a line of text with multiple statements.
Welcome2.java
public class Welcome2 {
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.print( "Welcome to " );
System.out.println( "Java Programming!" );
} // end method main
} // end class Welcome2
1. Comments
2. Blank line
3. Begin class
Welcome2
3.1 Method main
System.out.print keeps the cursor on
the same line, so System.out.println
4. Method
continues on the same line.
System.out.prin
t
4.1 Method
System.out.prin
tln
Welcome to Java Programming!
5. end main,
Welcome2
Program
Output
 2003 Prentice Hall, Inc.
All rights reserved.
23
2.3
Modifying Our First Java Program
• Newline characters (\n)
– Interpreted as “special characters” by methods
System.out.print and System.out.println
– Indicates cursor should be on next line
– Welcome3.java (Fig. 2.4)
9
System.out.println( "Welcome\nto\nJava\nProgramming!" );
– Line breaks at \n
• Usage
– Can use in System.out.println or
System.out.print to create new lines
• System.out.println(
"Welcome\nto\nJava\nProgramming!" );
 2003 Prentice Hall, Inc. All rights reserved.
24
Outline
1
2
3
4
5
6
7
8
9
10
11
12
13
// Fig. 2.4: Welcome3.java
// Printing multiple lines of text with a single statement.
Welcome3.java
public class Welcome3 {
1. main
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( "Welcome\nto\nJava\nProgramming!" );
} // end method main
2.
System.out.prin
tln (uses \n for new
line)
} // end class Welcome3
Program Output
Welcome
to
Java
Programming!
Notice how a new line is output for each \n
escape sequence.
 2003 Prentice Hall, Inc.
All rights reserved.
25
2.3
Modifying Our First Java Program
Escape characters
– Backslash ( \ )
– Indicates special characters be output
Esc a p e
De sc rip tio n
se q ue nc e
\n
Newline. Position the screen cursor at the beginning of the
next line.
\t
Horizontal tab. Move the screen cursor to the next tab stop.
\r
Carriage return. Position the screen cursor at the beginning of
the current line; do not advance to the next line. Any
characters output after the carriage return overwrite the
characters previously output on that line.
\\
Backslash. Used to print a backslash character.
\"
Double quote. Used to print a double-quote character. For
example,
System.out.println( "\"in quotes\"" );
displays
"in quotes"
Fig. 2.5 So m e c o m m o n e sc a p e se q ue nc e s.
 2003 Prentice Hall, Inc. All rights reserved.
26
2.4
Displaying Text in a Dialog Box
• Display
– Most Java applications use windows or a dialog box
• We have used the command window
– Class JOptionPane allows us to use dialog boxes
• Packages
– Set of predefined classes for us to use
– Groups of related classes called packages
• Group of all packages known as Java class library or Java
applications programming interface (Java API)
– JOptionPane is in the javax.swing package
• Package has classes for using Graphical User Interfaces (GUIs)
 2003 Prentice Hall, Inc. All rights reserved.
27
2.4
Displaying Text in a Dialog Box
• Upcoming program
–
–
–
–
Application that uses dialog boxes
Explanation will come afterwards
Demonstrate another way to display output
Packages, methods and GUI
 2003 Prentice Hall, Inc. All rights reserved.
28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1// //
Fig.
2.6:
Welcome4.java
Fig.
2.6:
Welcome4.java
// Printing multiple lines in a dialog box.
2 // Printing multiple lines in a dialog box
3// import
javax.swing.JOptionPane; // import class JOptionPane
Java packages
4import javax.swing.JOptionPane; // program uses JOptionPane
5 public class Welcome4 {
public class Welcome4 {
6
public static void main( String args] )
// main method begins execution of Java application
7
{
public static void main( String args[] )
8
JOptionPane.showMessageDialog(
{
JOptionPane.showMessageDialog(
9
null, "Welcome\nto\nJava\nProgramming!" );
null, "Welcome\nto\nJava\nProgramming!" );
10
11
12
System.exit(
0 );
terminate
application
with window
System.exit(
0 );// //
terminate
the program
}
} // end method main
} // end class Welcome4
Outline
Welcome4.java
1. import
declaration
2. Class Welcome4
2.1 main
2.2
showMessageDial
og
2.3 System.exit
Program Output
 2003 Prentice Hall, Inc.
All rights reserved.
29
2.4
Displaying Text in a Dialog Box
– Lines 1-2: comments as before
4
// Java packages
– Two groups of packages in Java API
– Core packages
• Begin with java
• Included with Java 2 Software Development Kit
– Extension packages
• Begin with javax
• New Java packages
5
import javax.swing.JOptionPane;
// program uses OptionPane
– import declarations
• Used by compiler to identify and locate classes used in Java
programs
• Tells compiler to load class JOptionPane from
javax.swing package
 2003 Prentice Hall, Inc. All rights reserved.
30
2.4
Displaying Text in a Dialog Box
– Lines 6-11: Blank line, begin class Welcome4 and main
12
13
JOptionPane.showMessageDialog(
null, "Welcome\nto\nJava\nProgramming!" );
– Call method showMessageDialog of class
JOptionPane
• Requires two (or more) arguments
• Multiple arguments separated by commas (,)
• For now, first argument always null
• Second argument is string to display
– showMessageDialog is a static method of class
JOptionPane
• static methods called using class name, dot (.) then method
name
 2003 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
31
2.4
Displaying Text in a Dialog Box
– All statements end with ;
• A single statement can span multiple lines
• Cannot split statement in middle of identifier or string
– Executing lines 12 and 13 displays the dialog box
• Automatically includes an OK button
– Hides or dismisses dialog box
• Title bar has string Message
 2003 Prentice Hall, Inc. All rights reserved.
32
2.4
15
Displaying Text in a Dialog Box
System.exit( 0 );
// terminate application with window
– Calls static method exit of class System
• Terminates application
– Use with any application displaying a GUI
• Because method is static, 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 import declaration needed
• java.lang automatically imported in every Java program
– Lines 17-19: Braces to end Welcome4 and main
 2003 Prentice Hall, Inc. All rights reserved.