You are on page 1of 59

,;,Copyright 2000-2004 1om lunter

,;,Copyright 2000-2004 1om lunter


Chapter 2
Introduction to Java
Applications
,;,Copyright 2000-2004 1om lunter
A Java Application 2ust have the method
main.
A Java Application begins executing at
main.
Let`s look at details oI an Application:
Java Applications Are
A Series oI Classes
,;,Copyright 2000-2004 1om lunter
public class Welcome1
,
public static void main( String args, )
,
System.out.println( Welcome to Java! );
, // end of main()
, // end of class Welcome1
This is a basic Application.
Notice the comments. These are required in this course.
Java is Iree Iorm, but you`ll be happy iI you get in the habit
oI documenting like this.
Also, whenever you type an opening curly bracket, type
the closing one right away.
Your curly brackets must always--in this class--line up as
shown.
,;,Copyright 2000-2004 1om lunter
5:-ic cass Wecome1
,
public static void main( String args, )
,
System.out.println( Welcome to Java! );
, // end of main()
, // end of class Welcome1
The line above in blue is the class definition Ior
Wecome1.
Every class name must be Capitalized.
Notice, every scrap oI code is within this class.
Since it is named Wecome1, this Application is saved in
a Iile called Wecome1.java, spelled exactly the same.
The compiler will make a Iile called Wecome1.cass.
,;,Copyright 2000-2004 1om lunter
public class Welcome1
,
public static void main( String args, )
,
System.out.println( Welcome to Java! );
, // end of main()
, // end of class Welcome1
The word Wecome1 is an identiIier identiIier.
An identiIier identiIier is a user-deIined word, which consists oI:
letters
digits
(underscore)
$ (a dollar sign)
An identiIier cannot begin with a digit.
,;,Copyright 2000-2004 1om lunter
5:-ic class Welcome1
,
public static void main( String args, )
,
System.out.println( Welcome to Java! );
, // end of main()
, // end of class Welcome1
Notice that we put the word 5:-ic beIore the word
class.
This means the class can be called by anything.
The alternatives to 5:-ic are discussed in Chapter 8.
,;,Copyright 2000-2004 1om lunter
public class Welcome1
,
5:-ic static void main( String args, )
,
System.out.println( Welcome to Java! );
, // end of main()
, // end of class Welcome1
The method main is also declared 5:-ic.
This should just be copied until Chapter 6, when we
know methods better.
,;,Copyright 2000-2004 1om lunter
public class Welcome1
,
public static void main( String args, )
,
System.out.println( Welcome to Java! );
, // end of main()
, // end of class Welcome1
void means nothing is returned to the operating system
when the program Iinishes.
The ( String args[] ) works with 'arguments
that were passed when the program was executed.
Although you cannot omit it ( String args[] ),
we don`t discuss this topic just yet, so please copy it.
,;,Copyright 2000-2004 1om lunter
public class Welcome1
,
public static void main( String args, )

System.o:t.5rintn( Welcome to Java! );


} // end of main()
, // end of class Welcome1
The System.o:t.5rintn puts the message in
quotes on the command console.
II we used System.o:t.5rint, then the cursor would
not not do a carriage return / line Ieed aIter it prints the text.
Notice the opening and closing blue curly brackets. The
unit oI code enclosed in them is called a 'block.
It is also called the 'body oI the method.
%is is called te
Standard output
object.
,;,Copyright 2000-2004 1om lunter
public class Welcome1
,
public static void main( String args, )
,
System.out.println( Welcome to Java! )
, // end of main()
, // end of class Welcome1
You will Iind that you very rarely use this
Standard output object.
Instead, you will use the GUI objects.
Notice in red the semicolon. All executable
statements in Java ends in a semicolon.
,;,Copyright 2000-2004 1om lunter
5:-ic cass Wecome1

5:-ic static void main( String args[] )

System.o:t.5rint( Wecome )
System.o:t.5rintn( to Java! )
} // end of main()
} // end of cass Wecome1
This will still produce the same text as the
previous version.
,;,Copyright 2000-2004 1om lunter
public class Welcome1
,
public static void main( String args, )
,
System.out.print( Welcome\nto\nJava! );
, // end of main()
, // end of class Welcome1
Notice the ' \n . The slash is an escape
character. It tells the System object that whatever
Iollows the slash is special:
\n new line
\t tab
\r carriage return
\\ backslash
\ quote
Welcome
to
Java!
,;,Copyright 2000-2004 1om lunter
import javax.swing.JJptionPane
public class Welcome4
,
public static void main( String args, )
,
JJptionPane.showMessageDialog( null, Hi Java! );
System.exit( 0 )
, // end of main()
, // end of class Welcome1
First GUI: JOptionPane
This adds an import statement, which tells the
compiler you want to use somebody else`s class.
The ' javax.swing is like a DOS path.
,;,Copyright 2000-2004 1om lunter
import javax.swing.JJptionPane
You must know these classes, and how to use them.
This path helps the compiler Iind the class you wish to
use.
The javax.swing portion oI this name is called the
'package.
Classes in the same package have a connection we will
explore later.
SuIIice it to say that they are very chummy.
First GUI: JOptionPane
,;,Copyright 2000-2004 1om lunter
First GUI: JOptionPane
import javax.swing.JJptionPane
public class Welcome4
,
public static void main( String args, )
,
JJptionPane.showMessageDialog( null, Hi Java! );
System.exit( 0 )
, // end of main()
, // end of class Welcome1
The Statement JO5tionPane.showMessageDiaog means:
'I want object JOptionPane to perIorm its method
showMessageDiaog(). Also, I`m passing the data:
'null and 'Hi Java! In Java, we call that data
'arguments.
,;,Copyright 2000-2004 1om lunter
import javax.swing.JJptionPane
public class Welcome4
,
public static void main( String args, )
,
JJptionPane.showMessageDialog( null,
Hi Java! )
System.exit( 0 )
, // end of main()
, // end of class Welcome4
System.exit( 0 ) This statement uses the
method 'exit oI class System to end the application.
GUI Applications always require this statement to
terminate correctly.
Class System is imported automatically, in package
java.ang
,;,Copyright 2000-2004 1om lunter
Build An Application
When you are building an Application, there is a set
template Ior design that you automatically Iollow.
Get in the habit oI doing exactly as will be done on the
next Iew slides.
Addition
,;,Copyright 2000-2004 1om lunter
import javax.swing.JJptionPane;
1.) You tell the compiler to import any oI the extra
classes you will be using in your Application.
,;,Copyright 2000-2004 1om lunter
import javax.swing.JJptionPane;
public class Addition

} // end of class Addition


2.) DeIine your class name, and right away place the
opening and closing brackets--ith the co22ent.
,;,Copyright 2000-2004 1om lunter
import javax.swing.JJptionPane;
public class Addition
,
public static void main( String args, )
,
System.exit( 0 )
, // end of main()
, // end of class Addition
3.) Add the main method, and the System.exit( 0 )
that you know it will require--include the co22ent.
,;,Copyright 2000-2004 1om lunter
import javax.swing.JJptionPane;
public class Addition
,
public static void main( String args, )
,
String firstNumber,
secondNumber;
System.exit( 0 );
, // end of main()
, // end of class Addition
4.) Include any local variables you will need in this
method. A local variable is visible and accessible only
within the method.
These two are 'String references. That means they
have the potential to point to objects oI type String.
However, at this point, they point to nothing.
They are e2pty reIerences.
I
,;,Copyright 2000-2004 1om lunter
import javax.swing.JJptionPane;
public class Addition
,
public static void main( String args, )
,
String firstNumber,
secondNumber;
int number1,
number2,
sum;
System.exit( 0 );
, // end of main()
, // end of class Addition
5.) Now we have added three integer variables. They are
not objects. They hold three integers--without any
methods or classes. n:m-er1, n:m-er2 and
n:m-er3 are called primitive variables.
otice,
int` does not
start wit a
capital
letter.
,;,Copyright 2000-2004 1om lunter
import javax.swing.JJptionPane;
public class Addition
,
public static void main( String args, )
,
String firstNumber,
secondNumber;
int number1,
number2,
sum;
firstNumber = JO5tionPane.showInputDialog( First Num );
secondNumber = JO5tionPane.showInputDialog( Second Num );
Look at the Java Documentation Ior the
JO5tionPane object. You will Iirst see the hierarchy
oI this object within the Java object hierarchy:
String argument
is received.
d
String is
returned
by te
metod.
,;,Copyright 2000-2004 1om lunter
This is the hierarchy Ior
the JO5tionPane.
We will cover 'inheritance
starting in Chapter 8, but you
need to begin learning these API class libraries.
The Class JO5tionPane has several methods.
A class`s methods are its capabilities.
For now, you should know that method
showIn5:tDiaog()
receives a String argument, and
returns a String result.
,;,Copyright 2000-2004 1om lunter
import javax.swing.JJptionPane;
public class Addition
,
public static void main( String args, )
,
String firstNumber,
secondNumber;
int number1,
number2,
sum;
firstNumber = JJptionPane.showInputDialog( First Num );
secondNumber = JJptionPane.showInputDialog( Second Num );
These InputDialog boxes are created by this code.
But, since they are Strings, we can`t add them.
,;,Copyright 2000-2004 1om lunter
import javax.swing.JJptionPane;
public class Addition
,
public static void main( String args, )
,
String firstNumber,
secondNumber;
int number1,
number2,
sum;
firstNumber = JJptionPane.showInputDialog( First Num );
secondNumber = JJptionPane.showInputDialog( Second Num );
So, how do we get String 'numbers converted into
actual integers that we can do addition on?
We need some Object that has a method capable oI
taking a String argument and returning an integer.
,;,Copyright 2000-2004 1om lunter
import javax.swing.JJptionPane;
public class Addition
,
public static void main( String args, )
,
String firstNumber,
secondNumber;
int number1,
number2,
sum;
firstNumber = JJptionPane.showInputDialog( First Num );
secondNumber = JJptionPane.showInputDialog( Second Num );
number1 = Integer.5arseInt( firstNumber );
number2 = Integer.5arseInt( secondNumber );
sum = number1 + number2;
Integer is a class. Its method 5arseInt()
takes a String argument and returns an int.
,;,Copyright 2000-2004 1om lunter
import javax.swing.JJptionPane;
public class Addition
,
public static void main( String args, )
,
String firstNumber,
secondNumber;
int number1,
number2,
sum;
firstNumber = JJptionPane.showInputDialog( First Num );
secondNumber = JJptionPane.showInputDialog( Second Num );
number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt( secondNumber);
sum = number1 + number2;
JJptionPane.showMessageDialog( null, The Sum is: + sum,
Results, JJPtionPane.PLAIN_MESSAGE );
System.exit( 0 );
, // end of main()
, // end of class Addition
The method showMessageDialog oI class
JJptionPane takes Iour arguments:
null -- this will be explained in a later chapter
'The Sum is: sum --this converts the int sum into a
String and concatenates it with the String 'The Sum is:
'Results is the message displayed in the title bar.
JJptionPane.PLAIN_MESSAGE deIines the icon.
For the icons, you have Iive alternate constants to choose Irom:
JJptionPane.PLAIN_MESSAGE
JJptionPane.ERRJR_MESSAGE
JJptionPane.INFJRMATIJN_MESSAGE
JJptionPane.WARNING_MESSAGE
JJptionPane.QUESTIJN_MESSAGE
n Jaa, Constants are always all upper case, with words separated
by underscores.
,;,Copyright 2000-2004 1om lunter
A Caution About String Concatenation
On the previous slide, we concatenated a String with
an int: The S:m is + s:m.
Remember the sequence: Iirst, s:m was converted
Irom an int to a String, and then that String was
concatenated with the other String 'The Sum is:
So, what would the Iollowing code produce?
int number1 = 2;
int number2 = 4;
JJptionPane.showMessageDialog( null,
The Sum is: + number1 + number2,
Screwy Result, JJptionPane.WARNING_MESSAGE );
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
A variable called n:m-er1 actually reIers to a place in
memory where the value oI the variable is stored.
Every variable in Java has a:
name,
type,
size, and a
value.
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
name
Variable names must conIorm to the rules Ior identiIiers:
they must begin with a letter,
aIter that they can contain digits, dollar signs and
underscores.
Java uses Unicode Ior its characters, so any
'letter that is valid Ior a word in any world
language is thereIore valid Ior a name in Java.
,;,Copyright 2000-2004 1om lunter
int num1=2;
You declare a variable and
initialize it on the same line.
This is a declaration. At this point,
the name num1 reIers to a location
a pointer} in the computer`s RAM
where this variable is stored.
Because an int is declared, we
know that Iour bytes are set aside.
Still, nothing is stored in it yet.
Primitive Data Types
type
The 'type appears beIore the identiIier name.
The type can be one oI the 'primitive data types or it
can be any previously deIined class.
int num1;
num1 = 2;
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
size
When we assign a type | int, String| to a
variable, we are not only declaring a memory
location.
We also decide how big oI a number or character
is able to be stored in that variable.
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
value
Finally, the value is what we want the variable
to store.
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
Java is a Strongly-typed language. That means,
every variable 2ust be declared as a type.
In Java, there are 8 primitive types:
6 oI those reIer to numbers
--4 Ior integers types,
--2 Ior Iloating-point types,
1 is the character type char, used Ior characters
in Unicode encoding, and
1 is a -ooean type Ior tr:e or fase values.
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
int
In contrast to C/C, an int will always--no
matter which operating system--take 4 bytes
oI storage space.
Because those 4 bytes are set in stone, you can be
sure that every JVM that runs your program
will be able to store the same size numbers.
int is the most commonly used number size.
Range:
-2,147,483,648 to 2,147,483,647 (over two billion)
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
short
In Java, a short is deIined as 2 bytes, no matter
which operating system is used.
You would only use this Ior special situations,
such as when speed is really crucial.
For VB programmers, a short is what
you`ve come to think oI as an int . }
Range:
-32,768 to 32,767
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
ong
A ong is deIined as 8 bytes, no matter
which operating system is used.
Range:
-9,223,372,036,854,775,808Lto
9,223,372,036,854,775,807L
Please notice the upper-case L suIIix is appended to any
ong. This is required.
Hexadecimal numbers have a preIix: 0x
0x1CFE.
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
-yte
A -yte is deIined as 1 byte, no matter
which operating system is used.
Range:
-128 to 127
Again, like a short, a -yte is only used under
rare circumstances.
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
foat
A foat is deIined as 4 bytes, no matter
which operating system is used.
Range:
approximately I3.40282347E38F
( 6-7 signiIicant decimal digits )
Because there are so Iew decimal places available,
foat is not used all that oIten.
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
do:-e
A do:-e is deIined as 8 bytes, no matter
which operating system is used.
Range:
approximately I1.79769313486231570E308
( 15 signiIicant decimal digits )
'do:-e is the one to have when you`re having
more than one--decimal place, that is.
This is the most common choice Ior any decimal.
do:-e is the deIault, not foat, thereIore, no
special character is appended. (See red arrow.)
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
char
A char is deIined as 2 bytes, no matter which
operating system is used. A char type always reIers
to a character in the Unicode encoding scheme.
|\: \u is the escape character syntax|
About 65,536 diIIerent characters can be represented.
Single quotes denote a char constant
H' is a char constant
H is a string that happens to only contain a
single character.
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
char
A char is deIined as 2 bytes. A char type is a
single Unicode character.
|\uFFFF \u is the escape character syntax--65,536
diIIerent characters can be represented.|
Single quotes denote a single-letter char constant
H' is a char constant.
H is a String that happens to only contain a
single character--it is not a char.
This is a syntax error! The compiler will
complain.
,;,Copyright 2000-2004 1om lunter
Primitive Data Types
-ooean
A -ooean type has only two values.
In contrast to C/C, in Java 0 and 1 cannot
stand in Ior true or Ialse.
A -ooean type must be assigned the value oI the
constants true or false.
|Meaning, these exact lowercase words.|
,;,Copyright 2000-2004 1om lunter
Java Math Operators
Addition
Subtraction -
Multiplication *
Division /
Modulus
All are binary operators, i.e., they work with two
numbers. They are executed according to the rules Ior
operator precedence. |page 1240|
(There is no operator Ior exponentiation in Java)
,;,Copyright 2000-2004 1om lunter
Multiplication *
What happens iI you multiply variables oI diIIerent types?
Java Math Operators
int x = 2;
double y = 3.889, sum = 0.000;
sum = y x;
The integer will be temporarily converted to a
double and two doubles will be multiplied.
AIterwards, the original integer is unchanged.
,;,Copyright 2000-2004 1om lunter
Rules Ior Temporary Conversions
1st Priority: II either oI the operands is oI type do:-e, then the other
one is converted to do:-e Ior the calculation.
2nd Priority: Otherwise, iI either oI the operands is oI type foat,
then the other one is converted to foat Ior the calculation.
3rd Priority: Otherwise, iI any oI the operands is oI type ong, then
the other one is converted to ong Ior the calculation.
Note: these conversions are automatic because none oI them result in a
loss oI accuracy.
Java Math Operators
,;,Copyright 2000-2004 1om lunter
Static Casts
So, what happens when you desire to convert a do:-e to a
foat? InIormation will inevitably be lost.
You accomplish this using a cast.
Java Math Operators
int x = 2, sum = 0;
double y = 3.889;
sum = (int)y x;
, sum is now equal to 6 ,
Here, a value oI just 3 will be used Ior y.
II you want to round y, you a method Irom class
Math:
sum = (int)Math.round(y) x;
,;,Copyright 2000-2004 1om lunter
Java Math Operators
Division
Division can lead to unexpected results:
II both operands are integers, then the result oI the
division is also an integer.
Any Iractional part oI the division is discarded.
ThereIore: 17/3 = 5
,;,Copyright 2000-2004 1om lunter
Java Math Operators
Modulus
The modulus operator is conIusing at Iirst, but
eventually it becomes your good Iriend.
In contrast to the division operator, it returns the
remainder oI any division. The modulus operator can
only be used when both operands are integers.
17 3 = 2
You say this '17 modulus 3 equals 2
,;,Copyright 2000-2004 1om lunter
Comparison Operators
These are used Ior selection structures:
equality
not equal !
greater than ~
less than
greater than or equal ~
less than or equal
,;,Copyright 2000-2004 1om lunter
Comparison Operators
The equality operator is a common source oI mistakes:
equality
Note that two equal signs are always used.
The single equal sign | | is only used Ior
assignment, that is, assigning the value on the right to the
variable on the leIt.
num1 33;
,;,Copyright 2000-2004 1om lunter
Comparison Operators
When you make a compound symbol using the equal
sign, the equal sign is always on the right:
equality
not equal !
greater than or equal ~
less than or equal
,;,Copyright 2000-2004 1om lunter
'if Statement Syntax
Decision Making
The if exactly mirrors C/C, and it has three
variants:
1.) if( expression )
statement;
2.) if( expression )
statement;
else
statement;
3.) if( expression )
statement;
else if( expression )
statement;
else
statement;
,;,Copyright 2000-2004 1om lunter
if( expression )
statement;
if( expression )
,
statement1;
statement2;
,
'if Statement Syntax
Simple if
The 'expression must be something that uses the
comparison operators and resolves to either true or Ialse.
The statement is executed iI the expression is true.
Only one statement can be made conditional without
brackets. II you wish to conditionally execute more than
one statement, you use brackets to create a block.
,;,Copyright 2000-2004 1om lunter
if( expression )
statement;
else
statement;
'if Statement Syntax
Simple if/ese
II the 'expression is true, the iI branch executes,
iI not, the else branch executes.
,;,Copyright 2000-2004 1om lunter
if( expression )
,
statement1;
statement2;
, else
,
statement3;
statement4; ,
'if Statement Syntax
Simple if/ese
II the 'expression is true, the iI branch executes,
iI not, the else branch executes.
if( expression )

statement1;
statement2;
} //end of if else

statement3;
statement4; } //
end of else
Don`t bother to label the
closing brackets unless
you have a really long iI.
Still you should always line
up your brackets.
,;,Copyright 2000-2004 1om lunter
'if Statement Syntax
if( expression )
statement;
else if( expression )
statement;
else
statement;
Compact if/ese if/ ese
To prevent your nested iI`s Irom marching across
the page, you can use this nested iI. You can go on nesting
them as long as you like, and the last one is just an else.

You might also like