Chapter 2. Getting Started with Java
Objectives:
·
Identify the basic components
of Java programs
·
Write simple Java Program
·
Describe the process of
creating and running Java Programs
·
Use the Date, SimpleDateFormat,
String, and JOptionPane classes from the standard Java Packages.
·
Develop Java Programs, using
the incremental development approach.
2.1 The first java program
Our first Java application program
displays a window on the screen, as shown in the output below. The size of the
window is set to 300pixels wide and 200pixels high. A pixel is a shorthand for
picture element, and it is the standard unit of measurement for the screen
resolution.
/*
Chapter 2 Sample Program: Displaying a
Window
File: Ch2Sample1.java
*/
importjavax.swing.*;
class Ch2Sample1 {
public static void main( String[] args){
JFramemyWindow;
myWindow =
new JFrame();
myWindow.setSize(300,200);
myWindow.setTitle("My First Java
Program");
myWindow.setVisible(true);
}
}
This will not concern the majority of
you, but if you are using a Java development tool that does not let you stop a
running program easily, then insert the statement
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
after
myWindow.setVisible(true);
so the program terminates automatically
when the frame window is closed.
HELPFUL REMINDERS
A Java program is composed of comments,
import statements, and class declarations.
To use an object in a program, first we
declare and create an object, and then we send messages to it.
OBJECT DECLARATION
Object declaration syntax
<class name> <object
names>;
Where
<object names> is a sequence of object names separated by commas and
<class name> is the name of a class to which these objects belong. Here’s
how the general syntax is matched to the object declaration of the program:
JFrame myWindow ;
More examples:
Account checking;
Customer john,jack,jill;
OBJECT CREATION
Object creation syntax
<object name> = new <class
name> (<argument>);
Where
<object name> is the name of a declared object, <class name> is the
name of the class to which the object
belongs, and <arguments> is a sequence of values passed to the new
operation. Let’s match the syntax to the actual statement in the sample
program:
myWindow = new JFrame ();
Example of object declaration and object
creation statements:
Customer customer;
customer = new Customer(
);
Instead of writing statements for object
declaration and creation separately, we can combine them into one statement. We
can write, for example.
Student john = new
Student( );
Instead of
Student
john;
John = new
Student( ) ;
Quick Check
1.
Which of the following are
invalid identifiers?
a.
one
b.
my Window
c.
1234
d.
DecafeLattePlease
e.
Hello
f.
JAVA
2.
What’s wrong with the following
code?
JFramemyWindow();
myWindow.setVisible(true);
3.
Which of the following
statements is valid?
a.
myFirstWindow.setVisible{“true”);
b.
myFirstWindow.setVisible(true);
2.2 Program Components
Comments
Design
Guidelines
Always aim for self-explanatory code. Do
not attempt to make a poorly written code easier to read by comments. Good
comments are not a substitute for good code. Bad code is bad, no matter how
well your comments are written.
Comment markers are useful in disabling a
portion of a program. Let’s say you find a portion that may be causing the
program to crash, and you want to try out different code for the problem
portion. Instead of replacing the whole problem portion with new code, you can
leave the questionable code in the program by converting it into a “comment”
with comment markers. You can remove the comment marketing if you need this
code later.
Import statement
The
import statement allows the program to refer to classes defined in the
designated package without using the
fully qualified class name
/*
Chapter 2 Sample Program: Displaying a
Window
File: Ch2Sample1.java
*/
importjavax.swing.*;
class Ch2Sample1 {
public static void main( String[] args){
JFramemyWindow;
myWindow =
new JFrame();
myWindow.setSize(300,200);
myWindow.setTitle("My First Java
Program");
myWindow.setVisible(true);
}
}
If no import statement
/*
Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample1.java
*/
importjavax.swing.*;
class Ch2Sample1 {
public static void main( String[] args){
javax.swing.JFramemyWindow;
myWindow = new javax.swing.JFrame();
myWindow.setSize(300,200);
myWindow.setTitle("My First Java
Program");
myWindow.setVisible(true);
}
}
Instead of using the expression
javax.swing.JFrame to refer to the class, we can refer to it simply as
JFrame
By including the import statement
importjavax.swing.*;
You
might want to know
When
we say “import a package”, it sounds as if we are copying all those classes
into our programs. That is not the case. Importing a package is only a
shorthand notation for referencing classes. The only effect of importing a
package is the elimination of the requirement to use the fully qualified name.
No classes are physically copied into our programs.
Class Declarations
Syntax code
class<class name> {
<class
member declarations>
class Ch2Sample1 {
public static void main( String[] args){
JFramemyWindow;
myWindow =
new JFrame();
myWindow.setSize(300,200);
myWindow.setTitle("My First Java
Program");
myWindow.setVisible(true);
}
}
Method Declarations
Syntax code
<modifiers><return
type><method name> ( <parameter>
){
<method
body>
}
Public static void main( String[] args){
JFramemyWindow;
myWindow =
new JFrame();
myWindow.setSize(300,200);
myWindow.setTitle("My First Java
Program");
myWindow.setVisible(true);
}
}
2.3 Edit-Compile-Run-Cycle
Step 1. Type in the program, using the
editor, and save the program to a file. Use the name of the main class and the
suffix .java for the filename. This file,in which the program is in a
human-readable form, is called a source file.
Step 2. Compile the source file. This
compiled version is called bytecode, and the file that contains bytecode is called bytecode file. The
name of the compiler-generated bytecode file will have the suffix .class while
its prefix is the same as the one for the source file.
Step 3. Execute the bytecode file. A
Java interpreter will go through the bytecode file and execute the instructions
in it. If your program is error-free, a window will appear on the screen.
Four
standard classes:
1.
JOptionPane
2.
String
3.
Date
4.
SimpleDateFormat
JOptionPane for Output
/*
*
Chapter 2 Sample program: Shows a Message Dialog
*
File: Ch2ShowMessageDialog.java
*/
importjavax.swing.*;
class Ch2ShowMessageDialog {
public static void main(String[] args){
JFramejFrame;
jFrame = new JFrame();
jFrame.setSize(400,300);
jFrame.setVisible(true);
JOptionPane.showMessageDialog(jFrame,"How
are you?");
JOptionPane.showMessageDialog(null,"Good
Bye");
}
}
The showMessageDialog method of
JOptionPane is a class method. As such, there’s no need to create an instance
of JOptionPane.
If you want to display multiple lines of
text, we can use a special character sequence \n to separate the lines, as in
JOptionPane.showMessageDialog(null,
“one\ntwo\nthree”);
Which will result in the dialog
Quick Check
1.
Write Java statements to
display a message dialog with the text I Love Java
2.
Write statements to display the
following shopping list on a message dialog:
Shopping List:
Apple
Banana
Lowfat Milk
String
/*
*
Chapter 2 Sample Program: Simple String Processing
*
file: Ch2StringProcessing.java
*/
importjavax.swing.*;
class Ch2StringProcessing2{
public static void main( String[] args){
String text;
text = "Espresso";
JOptionPane.showMessageDialog(null,
text.substring(2,7));
}
}
/*
*
Chapter 2 Sample Program: Simple String Processing
*
file: Ch2StringProcessing.java
*/
importjavax.swing.*;
class Ch2StringProcessing {
public static void main( String[] args){
String fullName,firstName,lastName,space;
fullName = new String("Decafe
Latte");
space = new String(" ");
firstName=
fullName.substring(0,fullName.indexOf(space));
lastName = fullName.substring(fullName,indexOf(space) +
1, fullName.length());
JOptionPane.showMessageDialog(null,"Full
Name:" + fullName);
JOptionPane.showMessageDialog(null,
"First:" + firstName);
JOptionPane.showMessageDialog (null,
"Last:" + lastName);
JOptionPane.showMessageDialog(null,"You
last name has " + lastName.length() + "characters.");
}
}