Title: Lecture 2 focuses on:
1Lecture 2
Getting Started
- Lecture 2 focuses on
- How to run Java application?
- Important parts of the application
- Examples of Java Application
- Example of Java GUI application
- How to run java Applets?
- Examples of Java Applets
2First Step "Resources needed"
- To Write your first program
- Install JDK 1.3.1 You can get from the site
- Â Â http//java.sun.com/j2se/1.3/
- Set class path for the compiler. Here is example
for JDK1.3 for Windows - Click on Start button.
- Click on Run
- You will get a text box. Type "sysedit" in the
text box and hit enter key. - You will probably get many different windows. Add
following at the end of the front window. - PATHÂ C\WINDOWSC\WINDOWS\COMMANDC\JDK1.3\bin
path
3First Step
- Second way of doing same thing is following.
- Go to DOS Prompt.
- Go to C derive or whatever derive you are using.
- Now type command "edit autoexec.bat"
- At the end of the file enter the path statement.
- PATHÂ C\WINDOWSC\WINDOWS\COMMANDCJDK1.3\bin
path - A text editor You need any plain text editor.
For example "NotePad"
4Second Step "Creating First Application"
- Create a Source File
- Compile the Source file into byte code file.
- Run the Program contained in the byte code file.
5Create a Source File
- Start Notepad and in new document window type
following code. - /
- The HelloWorldApp class implements an
- application that simply displays
- "Hello World!" to the standard output.
- /
- public class HelloWorldApp
- public static void main(String args)
-
- //Display the string "Hello CIS375".
- System.out.println("Hello CIS375")
-
-
6Create a Source File
- Save this code into a file name
"HelloWorldApp.java" - Remember following while you save your file.
- If your class is public then you must give the
exactly same - filename as your public class name.
- Use double quotation marks as shown above in the
save dialog box. - Remember the directory name where you are saving
your file. - You can not have more than one public classes in
one file.
7Compile the Source File
- Start DOS Prompt
- Go to the directory where you have saved your
source file. - Enter following on command line   Â
- javac HelloWorldApp.java
- This will compile your source code. Compiler will
generate - byte code for the JVM. You can see another file
in same direcotry "HelloWorldApp.class"
8Run the Program
- If you do not have any error message in previous
step, then you can run your code as follows. - java HelloWorldApp
9Java Program Structure
- In the Java programming language
- A program is made up of one or more classes
- A class contains one or more methods
- A method contains program statements
- These terms will be explored in detail throughout
the course - A Java application always contains a method
called main
10Java Program Structure
// comments about the class
public class HelloWorldApp
class header
class body
Comments can be added almost anywhere
11Java Program Structure
// comments about the class
public class HelloWorldApp
// comments about the method
public static void main (String args)
method header
method body
12Comments
- Comments in a program are also called inline
documentation - They should be included to explain the purpose of
the program and describe processing steps - They do not affect how a program works
- Java comments can take two forms
// this comment runs to the end of the line
/ this comment runs to the terminating
symbol, even across line breaks /
13Example GUI application
// printing multiple lines in a dialog
box //Java extension packages import
javax.swing.JOptionPane//import class
JOptionPane public class Welcome4 //main
method begins execution of Java
application public static void main(String
args) JOptionPane.showMessageDialog(null,
"Welcome\nto\nJava\nProgramming!") Syste
m.exit(0) //terminate the program // end of
main method //end of class Welcome4
14Java Applets
- Applets are Java programs that can be embedded in
HTML documents (WebPages). - The browser that executes an applet is
generically known as the applet container. - Appletviewer is one kind of applet container that
comes with JSDK. - Few examples from JSDK
- Tic tac toe
- The java 2D applet.
15Creating your First Applet
- Create Source files
- You need two files Java source file as we did in
previous - application and html file to run the applet.
16WelcomeApplet.java
- // WelcomeApplet.java
- // A first applet in Java
- import javax.swing.JApplet // import class
JApplet - import java.awt.Graphics // import class
Graphics - public class WelcomeApplet extends JApplet
- public void paint( Graphics g )
-
- g.drawString("Welcome to Java Programming!", 25,
25 ) -
17welcomeApplet.html
- lthtmlgt
- ltapplet code"WelcomeApplet.class" width300
height30gt - lt/appletgt
- lt/htmlgt
18Compile the Source File
- At the prompt type the following command and
press return - javac HelloWorldApplet.java
- The compiler should generate a Java bytecode
file, HelloWorldApplet.class
19Run the Program
- TWo ways to run this applet
- 1. You can run this program in Web browser.
Just open the html file - welcomeApplet.html
- 2. At the prompt type the following command and
press return - appletviewer welcomeApplet.html
20WelcomeApplet2.java
- // WelcomeApplet2.java
- // Displaying multiple strings
- import javax.swing.JApplet // import class
JApplet - import java.awt.Graphics // import class
Graphics - public class WelcomeApplet2 extends JApplet
- public void paint( Graphics g )
-
- g.drawString( "Welcome to", 25, 25 )
- g.drawString( "Java Programming!", 25, 40
) -
21Another example WelcomeLines.java
- // WelcomeLines.java
- // Displaying text and lines
- import javax.swing.JApplet // import class
JApplet - import java.awt.Graphics // import class
Graphics - public class WelcomeLines extends JApplet
- public void paint( Graphics g )
-
- g.drawLine( 15, 10, 210, 10 )
- g.drawLine( 15, 30, 210, 30 )
- g.drawString( "Welcome to Java Programming!",
25, 25 ) -
-
22AdditionApplet.java
- // AdditionApplet.java
- // Adding two floating-point numbers
- import java.awt.Graphics // import class
Graphics - import javax.swing. // import package
javax.swing - public class AdditionApplet extends JApplet
- double sum // sum of the values entered by
the user - public void init()
-
- String firstNumber, // first string
entered by user - secondNumber // second string
entered by user - double number1, // first number to
add - number2 // second number to
add - // read in first number from user
- firstNumber
- JOptionPane.showInputDialog(
- "Enter first floating-point value" )
-
23- // read in second number from user
- secondNumber
- JOptionPane.showInputDialog(
- "Enter second floating-point value"
) - // convert numbers from type String to type
double - number1 Double.parseDouble( firstNumber
) - number2 Double.parseDouble( secondNumber
) - // add the numbers
- sum number1 number2
-
- public void paint( Graphics g )
-
- // draw the results with g.drawString
- g.drawRect( 15, 10, 270, 20 )
- g.drawString( "The sum is " sum, 25, 25
) -
24Identifiers
- Identifiers are the words a programmer uses in a
program - An identifier can be made up of letters, digits,
the underscore character (_), and the dollar sign - They cannot begin with a digit
- Java is case sensitive, therefore Total and total
are different identifiers
25Identifiers
- Sometimes we choose identifiers ourselves when
writing a program (such as Lincoln) - Sometimes we are using another programmer's code,
so we use the identifiers that they chose (such
as println) - Often we use special identifiers called reserved
words that already have a predefined meaning in
the language - A reserved word cannot be used in any other way
26Reserved Words
abstract boolean break byte byvalue case cast catc
h char class const continue
default do double else extends false final finally
float for future generic
goto if implements import inner instanceof int int
erface long native new null
operator outer package private protected public re
st return short Static strictfp super switch
synchronized this throw throws transient true try
var void volatile while widefp
27Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
28You may run into words that sounds as if they
should be Java keywords because of your
familiarity with C or C. Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â
                        Â
29White Space
- Spaces, blank lines, and tabs are collectively
called white space - White space is used to separate words and symbols
in a program - Extra white space is ignored
- A valid Java program can be formatted many
different ways - Programs should be formatted to enhance
readability, using consistent indentation
30Identifiers
- Words used in programs to name variables,
classes, methods, - or labels are identifiers and are subject to
strict rules. - Following are the rules
- None of the Java reserved words may be used
- First character may only be a letter, a dollar
sign (), or an underscore character. - Letters can be drawn from the Unicode character
set. - Identifiers are case-sensitive.
- Examples
- MyVariable
- Variable
- _AnotherVariable
31Identifiers
- Conventions
- Method names start with a lower case letter.
- public void myMethod ( )
- Variables and Class names start with an upper
case letter. - public class MyClass
- public int MyVariable 5
-
32Variables
- A variable is a name for a location in memory
- A variable must be declared, specifying the
variable's name and the type of information that
will be held in it
int total
int count, temp, result
Multiple variables can be created in one
declaration
33Variables
- A variable can be given an initial value in the
declaration
int sum 0 int base 32, max 149
- When a variable is referenced in a program, its
current value is used
34MaxVariablesDemo.java
- public class MaxVariablesDemo
- public static void main(String args)
- // integers
- byte largestByte Byte.MAX_VALUE
- short largestShort Short.MAX_VALUE
- int largestInteger Integer.MAX_VALUE
- long largestLong Long.MAX_VALUE
- // real numbers
- float largestFloat Float.MAX_VALUE
- double largestDouble Double.MAX_VALUE
35MaxVariablesDemo.java
- // other primitive types
- char aChar 'S'
- boolean aBoolean true
- // display them all
- System.out.println("The largest byte value is "
largestByte) - System.out.println("The largest short
value is " largestShort) - System.out.println("The largest integer
value is " largestInteger) - System.out.println("The largest long
value is " largestLong)
36MaxVariablesDemo.java
- System.out.println("The largest float value is "
largestFloat) - System.out.println("The largest double value
is " largestDouble) - if (Character.isUpperCase(aChar))
- System.out.println("The character "
aChar " is upper case.") - else
- System.out.println("The character "
aChar " is lower case.") -
- System.out.println("The value of aBoolean
is " aBoolean) -
37Assignment
- An assignment statement changes the value of a
variable - The assignment operator is the sign
total 55
- The expression on the right is evaluated and the
result is stored in the variable on the left
- The value that was in total is overwritten
- You can only assign a value to a variable that is
consistent with the variable's declared type
38public class Geometry // Prints the number
of sides of //several geometric shapes. public
static void main (String args) int sides
7 // declaration with //initialization
System.out.println ("A heptagon has " sides
" sides.") sides 10 //
assignment statement System.out.println ("A
decagon has " sides " sides.")
sides 12 System.out.println ("A
dodecagon has " sides " sides.")
39Constants
- A constant is an identifier that is similar to a
variable except that it holds one value for its
entire existence - The compiler will issue an error if you try to
change a constant - In Java, we use the final modifier to declare a
constant - final int MIN_HEIGHT 69
- Constants
- give names to otherwise unclear literal values
- facilitate changes to the code
- prevent inadvertent errors
40Constants
- You can declare a variable in any scope to be
final. The value of a final variable cannot
change after it has been initialized. Such
variables are similar to constants in other
programming languages. - To declare a final variable, use the final
keyword in the variable declaration before the
type - final int aFinalVar 0
- or
- final int blankfinal
- ......
- ....
- blankfinal 0
41Data Types in Java
- Java has four kinds of named data types and two
categories of variables. - The data types are primitives, classes,
interfaces, and arrays. - Variables can either contain primitive values or
refer to objects.
42Primitive Data
- There are exactly eight primitive data types in
Java - Four of them represent integers
- byte, short, int, long
- Two of them represent floating point numbers
- float, double
- One of them represents characters
- char
- And one of them represents boolean values
- boolean
43Numeric Primitive Data
- The difference between the various numeric
primitive types is their size, and therefore the
values they can store
44Characters
- A char variable stores a single character from
the Unicode character set - A character set is an ordered list of characters,
and each character corresponds to a unique number - The Unicode character set uses sixteen bits per
character, allowing for 65,536 unique characters - It is an international character set, containing
symbols and characters from many world languages - Character literals are delimited by single
quotes - 'a' 'X' '7' '' ',' '\n'
45Characters
- The ASCII character set is older and smaller than
Unicode, but is still quite popular - The ASCII characters are a subset of the Unicode
character set, including
46Boolean
- A boolean value represents a true or false
condition - A boolean can also be used to represent any two
states, such as a light bulb being on or off - The reserved words true and false are the only
valid values for a boolean type - boolean done false
47Primitive Data Types
Keyword Description Size/Format Range of
Values (integers) byte Byte-length
integer 8-bit two's complement -128 to
127 short Short integer 16-bit two's
complement -32768 to 32767 int Integer 32-bit
two's complement -231 to 231-1 long Long
integer 64-bit two's complement -263 to
263-1 (real numbers) float Single-precision
floating point 32-bit IEEE 754 double Double-pre
cision floating point 64-bit IEEE 754 (other
types) char A single character 16-bit
Unicode character \u0000 to \uFFFF boolean A
boolean value (true or false) true or false
48Primitives (Facts)
- The character type represents 16-bit Unicode
characters and can be - considered as an un-signed integer for many
purposes. - The integer types are all treated as signed.
- The floating point tupes are in the standard IEEE
754 format. - (These formats are the same regardless of the
hardware). - Integer Primitives
- Member variables of the integer primitive type
are initialized to zero by default. - Floating-point Primitives
- Member variables of the floating-point primitive
type are initialized to zero by default. - Boolean Primitives
- Member variables of the Boolean primitive type
are initialized to false by default.
49Reference Variables
- Arrays, classes, and interfaces are reference
types. - The value of a reference type variable, in
contrast to that of a primitive type, is a
reference to (an address of) the value or set of
values represented by the variable. - Reference variables are declared in Java with a
statement that gives the type of object to which
the variable is expected to refer.
50Reference Variables
- Example
- Object anyRef
- String myString
- The type of reference that these variables can
hold depends upon the object hierarchy. Because
every class in Java desends from Object,
anyReference could refer to any object.
51Variable Names
- In the Java programming language, the following
- must hold true for a simple name
- It must be a legal identifier. An identifier is
an unlimited series of Unicode characters that
begins with a letter. - It must not be a keyword, a boolean literal (true
or false), or the reserved word null. - It must be unique within its scope. A variable
may have the same name as a variable whose
declaration appears in a different scope.
52Scope of a Variable
- The scope of a variable is the part of the
program over which the variable name can be
referenced or in other words the part of the
program where variable can be visible. - Variables that are declared within a method are
called local variables, as they are only
accessible within that code block. - (check "Scope.java" in suplement directory)
53Using Literals
- Literals are used to create values that are
assigned to variables, used in expressions, or
passed to methods. - Numeric Literals
- Literal numbers can appear in Java programs in
base ten, hexadecimal, and octal forms. - Unmodified integer value is assumed to be the
32-bit int primitive. - Value containing a decimal point is assumed to be
the 64-bit double, unless you append an F or f to
indicate the 32-bit float primitive.
54Using Literals
- Examples
- int n 42
- long j 4096L //appending L or l makes it long
- long k 0xFFFFFFFL
- byte b2 010 //an octal literal
- double f2 1.023 //double is assumed
- float f2 1.023F //F or f makes it a float
- Few Tricky Assignment Facts
- int n2 4096 //would require a specific
//(int)cast - short s1 32000 //OK
- short s2 33000 //out of range for short
primitive
55Numeric Wrapper Classes
- Each of the primitive data type has a
corresponding wrapper - class in the Java standard library. Java uses
these classes for - several purposes. For example static methods are
used for - conversion routines such as the toString method,
which - returns a String representing a primitive value.
- We can also Create objects that contain a
primitive value, using either literal or
primitive variables.
56Numeric Wrapper Classes
- Examples
- Integer myInt new Integer (42 )
- Boolean flag Boolean (false )
- Character ch new Character('\u000a' )
- Long lx new Long( x) // where x is a
//long variable - Note
- The contained value in the wrapper class objects
can not be changed. These objects are said to be
immutable.
57Numeric Wrapper Classes
- Wrapper Class Primitive
- Byte byte
- Short short
- Char char
- Integer int
- Float float
- Double double
- Boolean boolean
- End of lecture 2