JAVA Program

eyelashesnectarineSoftware and s/w Development

Nov 3, 2013 (3 years and 11 months ago)

73 views

Commercial

Programming

Module 1

Java Fundamentals

Commercial
Programming







Module 1

2009
-
2010









Java Fundamentals

Course Layout


The semester is spread over 17 weeks ~
ending 27
th

January 2011.



There will be
2

assignments


1 Class Assignment


1 Home Assignment




Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Lesson Structure


Lessons will cover
basic Java techniques.



We will emphasize strengthening our
problem
-
solving

skills rather than making our programs
look good.


Each program is a problem that needs to be solved!



Lots and lots of PRACTICE!



Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Course Material


Slides

will guide you through the course.


Example programs

shown in class.


e
-
Book
: Core Java 2, Volume 1:
Fundamentals


We will be covering Chapter 1


5 of this
book.


The official
Java tutorial
:


http://java.sun.com/docs/books/tutorial/index.html


Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Software Needed


We will be using the
latest version

of Java.


This is currently version JDK 7



It is free to download from:


http://www.oracle.com/technetwork/java/javase/downl
oads/index.html



We will also be using an
IDE,

Netbeans


Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Key Concepts of the Java Programming
Language


Originated in 1991 with the initial aim to develop
embedded programs

i.e. programs to work on
consumer devices such as microwaves, DVD
players etc…


Became most popular with the WWW when it
was used to develop
multimedia web
components from web pages
.


These small applications are called
applets
.


Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Java is a direct descendent


of C and C++.

Java Applets and Applications


Java can be used to create 2 types of
programs:


Applications
: programs which run on your
computer, under the operating system of that
computer.


Applets
: an application designed to be
transmitted over the Internet and executed by
a Java
-
compatible browser.

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Security

is in
-
built in Java applets by confining programs


to the Java execution environment and not allowing it

to accessother parts of the computer.

Writing and Running a Program


When we write programs in a particular language, we
say we write the
source code
.


Computers do not understand source code, and each
programming language must provide a
compiler

which converts
source code to machine code
.


The machine code produced
must be that of the
computer on which the program is to be run
.


Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Write


Program

Compiler

Source code

Run

Program

Machine code

Key Concepts of the Java Programming
Language


Compiling source code to
a particular

machine code limits the program to run on
ONE particular machine.


This means the program is
platform
dependent.


The program needs to be
recompiled

to run
on another machine.


To eliminate this restriction, Java was
designed to be
platform independent
.


Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Writing and Running a
JAVA Program


Instead of compiling to machine code, the Java compiler
outputs
byte
-
code
.


Byte
-
code is always the same

whatever the platform.


To run byte
-
code we need the
Java Virtual Machine
(JVM).


The Java Virtual Machine (JVM)
is specific

to the
platform it will be used on.


The JVMs are written to
interpret
(translate) bytecode
into a particular machine language.

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Write

Java


Program

Compiler

Java source

code

Run

Program

with

JVM


Java byte

code

Writing and Running a
JAVA Program

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Writing and Running a C++ Program

(the difference)

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

A First Simple Program

STEP 1: Type in the code


Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

/*


This is a simple Java program.


Call this file Example.java

*/

class Example{


// A Java program begins with a call to main().


public static void main(String args[ ]) {




System.out.println("Java drives the Web.");



}

}

A First Simple Program


When writing a Java Program these 3
steps are always followed:


1.
Type

in the Program.

2.
Compile

the Program.

3.
Run

the Program.



Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Java Buzzwords


The Java programming language was
designed to be:



Object
-
oriented


Distributed


Simple


Multithreaded


Secure


Platform
-
independent


Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Java Technology Product Groups


Java is a product developed by
Sun
Microsystems
.



Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Java’s Simple Types


Two general categories of built
-
in data types:



Object
-
oriented



Non
-
object
-
oriented



8 simple data types (non
-
object
-
oriented):


boolean


byte


double


float


int


long


short


CLASSES!

NON
-
CLASSES!

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Integers

Type

Width in
Bits

Range

byte

8

-
128 to 127

short

16

-
32,768 to 32,767

int

32

-
2,147,483,648 to 2,147,483,647

long

64

-
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

Remember: Integers are WHOLE numbers!


Most commonly used

is
int
.

Inches.java

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Floating Point Types


Floating point types can represent decimal
point numbers.

Type

Width
in Bits

Range

float

32

1.4e
-
045 to 3.4e+038

double

64

49e
-
324 to 1.8e+308


Most commonly used

is
double
.

Hypot.java

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Characters

Type

Width
in Bits

Range

char

16

0 to 65,536





Characters are represented using
Unicode
.


Unicode is a character set that can represent all of
the characters found in all human languages.


Declare a character:
char ch;


Assign a value:
ch = ‘X’;

CharArithDemo.java

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Booleans


The
boolean

type represents true or
false.


Java defines the values true and false by
the keywords:
true

and
false
.

boolean b;

b = false;

BoolDemo.java

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Literals


A literal is a value that is represented in it’s
human
-
readable form:






char c;

c = ‘X’;

‘X’ is a
char

literal

int i;

i =
-
10;

10 is a
int

literal

long l;

l =
-
10L;

-
10L is a
long

literal

float f;

f =
-
1.5F;

-
1.5F is a
float

literal

int i = 10;

long l;

l = i;

An
int

value can

be assigned

to a
long
.

float f =
-
1.5F;

double d;

d = f;

A
float

value can

be assigned

to a
double
.

WITHIN RANGE!

short s = 128;

byte b;

b = s;

RANGE???

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Character Escape Sequences


How can we display:


Shout: “HELP!”



Will this work?


System.out.println(“Shout: “HELP!””);




Some characters need special codes to be
displayed.


Double quotes are confusing!

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Character Escape Sequences

\


Single quote

\


Double quote

\
\

Back slash

\
n

New line

\
t

Tab

\
b

Backspace

System.out.println(“ Shout:

\

HELP!
\
” ”);

StrDemo.java

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Initializations


These are valid initializations:

int count = 10;

char ch = ‘x’;

float f = 12f;

int a, b = 8, c = 19, d;

double radius = 4; height = 5;

double volume = Math.PI * radius * radius * height;

Volume is assigned at

runtime
!

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Scope of a Variable


A block of code defines a variable’s scope:

int x;



x = 10;

if(x == 10)

{ // start new scope


int y = 20; // known only to this block




// x and y both known here.


System.out.println("x and y: " + x + " " + y);


x = y * 2;

}

y = 100; // Error! y not known here

y

can’t be referenced here
-

it was declared in an inner block.

y
is
out of scope
!

ScopeDemo.java, VarInitDemo.java, NestVar.java

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

All

the Arithmetic Operators

Operator

Meaning

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulus

++

Increment

--

Decrement

ModDemo.java, PostPrefix.java

x++ x = x +

x
--

x = x
-

1

Prefix: ++x

Prefix:
--
x

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Logical Operators

Operator

Meaning

&

AND

|

OR

^

XOR (exclusive OR)

||

Short
-
circuit OR

&&

Short
-
circuit AND

!

NOT

RelLogOps.java, SCops.java, SideEffects.java

Explanation of the First Program

MULTI
-
LINE COMMENTS






This is a comment.


Using /* */ defines a multi
-
line comment.




Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

/*


This is a simple Java program.




Call this file Example.java.

*/


Explanation of the First Program

KEYWORD:
CLASS




This line uses the keyword
class

to declare that a new
class is being defined.


The class is Java’s
basic unit of encapsulation
.


Example

is the name of the class.


The class definition begins with the opening curly
bracket

{

and ends with the closing curly bracket

}
.


The elements between the two brackets are the
members of the class
.


Don’t worry too much about the details for now!





Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

class Example {


Explanation of the First Program

SINGLE LINE COMMENTS




A
single
-
line comment

begins with a //
and ends at the end of the line.


As a general rule, we use multi
-
line
comments for long remarks and single
-
line
comments for short ones.





Commercial Programming







Module 1

2009
-
2010









Java Fundamentals


// A Java program begins with a call to main().


Explanation of the First Program

THE MAIN METHOD




This line begins the
main()

method.


A method is a block of code that performs a
particular action.


We saw some examples in our OO Petrol Pump.



main()

is the line at which the program will
begin

executing
.





Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

public static void main(String args[]) {

We will explain each part of this line

as the unit progresses.

Explanation of the First Program

WRITING TO CONSOLE




This line outputs the string “Java drives the
Web”, followed by a new line on the screen.


Output is accomplished by the built
-
in
println
()

method.


println
()

prints the string which is passed to it.


System

is a predefined class which provides
access to the system.


out

is the output stream which is connected to
the console.



Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

System.out.println("Java drives the Web.");



This explanation will become clearer

as we go along.

SEMICOLON!

1
-
Minute Drill


Where does a Java program begin
execution?



What does
System.out.println()

do?



What is the name of the JDK compiler?



What is the name of the JDK
interpreter?

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Using dialog boxes


It would be much better to deal with

the user using some type of GUI.


The example shows a

showmessageDialog

box.


This is one type of dialog used in Java which shows
messages to the user.


Try showing a message dialog box by typing the following:


JOptionPane.showMessageDialog
(null, “Some
text”)


What happens?

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Using dialog boxes


The compiler will give you an error

because it can’t find the
Swing


library


The
swing
library is one of the

libraries that allows GUI applications.


In order to run the application you need to import the
swing

library

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Input using Scanner


Another type of input is using Scanner:





By using Scanner, we can read any type we want, be it
int
,
String, char,
etc.



Don’t forget to import the Scanner library:



Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

import
java.util.Scanner
;

Declaring Variables




2 variables are being declared here:


var1

and
var2
, both of type
integer
.


In Java, all variables must be declared before they are
used.


Also, to declare a variable, we must declare it’s
type
.


A variable of type integer can only hold
whole numbers
.

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

int var1; // this declares a variable

int var2; // this declares another variable



In general:

type var
-
name;




TYPE




NAME

Assigning a Value to a Variable




This line assigns
var1

the value 1024.


In Java, the assignment operator is the single
equal sign.




Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

var1 = 1024; // this assigns 1024 to var1

Outputting the Value of a Variable




This statement uses the + to display
the value
of

var1

together with the string:
“var1
contains:”


We can use the + operator to join as many items
as you want in a single
println()

statement.




Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

System.out.println("var1 contains " + var1);


Basic Arithmetic Operators



This line divides the value in
var1

by 2.


The answer is stored in
var2
.


var1

is NOT changed!



Java supports a full range of operators:

+


Addition

-

Subtraction

*


Multiplication

/


Division



Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

var2 = var1 / 2;

print()

and
println()




Notice the use of
print()

instead of
println()

in
the first line.


Can you tell what it does different to
println()
?



Add a line to display var1 AFTER the division
takes place.


This should verify that the value of var1 does
not change.

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

System.out.print("var2 contains var1 / 2: ");

System.out.println(var2);


Another Data Type:
double


In the preceding program, our variables were of type int.



This means they could hold whole numbers only.


They can hold 18 but not 18.3!



In order to hold a value such as 18.3, we need to use the
type:
double
.



Decimal values are often called
floating
-
point
values.



Take a look at
Example3.java


Can you see the difference between
int

and
double
?

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Incrementing


The statement:



Can be written as:





Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

count = count + 1;

count++;

Decrementing


Likewise, the statement:



Can be written as:






Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

count = count
-

1;

Count
--
;

Using Blocks of Code


Another key element of Java is the
code
block
.


A code block is a grouping of 2 or more
statements.


This is done by enclosing the statements
between opening and closing curly braces.

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

if (w < h ) {


v = w * h;


w = 0;

}

Start of block

End of block

Semicolons and Positioning


In Java, the semicolon is a statement
terminator.


We can write:




As:



However, the first option is more
readable
.


Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

x = y;

y = y + 1;

System.out.println(x + “ “ + y);


x = y; y = y + 1; System.out.println(x + “ “ + y);


The Java Keywords


48 keywords are currently defined in Java.



These keywords, together with the syntax
of operators and separators, form the
definition of the Java language.



Keywords cannot be used as names for
variables, class or methods.

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

The Java Keywords

abstract

boolean

break

byte

case

catch

char

class

const

continue

default

do

double

else

extends

final

finally

float

for

goto

if

implements

import

instanceof

int

inheritance

long

native

new

package

private

protected

public

return

short

static

strictfp

super

switch

synchronized

this

throw

throws

transient

try

void

volatile

while

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

We’ve already seen the highlighted ones in the examples, although

we don’t know what they all mean yet!

Identifiers in Java


An identifier is a name assigned to a
variable, class or method.


Variable names may start with any
letters

of the alphabet, an
underscore
or a
dollar sign
.


Acceptable identifiers:


Test


x


y2


MaxFuel

$price

_top


my_age

sample23

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Keep variable names MEANINGFUL!

Parsing


The
JOptionPane.showInputDialog
()
method accepts only String.



To be able to work with numbers we need
to
parse

the input into a number



If the String can be parsed into a number
Java will allow you!

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals

Parsing


To parse to
int
:

Integer.parseInt
(
stringVariable
)



To parse to double:

Double.parseDouble
(
stringVariabl
e
)

Commercial Programming







Module 1

2009
-
2010









Java Fundamentals