Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

Java CIS 260 Notes Part 1

Java CIS 260 Notes part 1

Uploaded by

fastalan392
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Java CIS 260 Notes Part 1

Java CIS 260 Notes part 1

Uploaded by

fastalan392
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 43

1

CIS 260 Introduction To Programming (Java)

Are you in the right class?

What this course is not about. . .

 Learning to use a computer

 Learning about computer hardware

 Using software such as word processor

What this course is about. . .

 Learning about the theory of programming

 Learning the Java programming language

 A brief introduction to computers and programming

 Fairly challenging

How to do well

 Attend class regularly with the notes and have read the material
assigned for the week before the week starts

 You have already paid $$$ for my office hours - USE THEM

 Learn what we are discussing at the time. Failing behind will


likely lead to a bad as the material builds though out the course.

 If you do not understand something I have just discussed in class,


ask right then

 Start programming assignments early, just in case

 Pay attention to my courses web site

 We have a lot to teach in 15 weeks. Do not fall behind or it will


be very hard to catch up!!!

Chapter 1: Hardware, Programming and Problem Solving


2

Hardware

Computers are just much, much faster and somewhat more complex
versions of a calculator. All computers manipulate sequences of
binary numbers consisting of 0's and 1's. These sequences can either
represent instructions for the computer or data such as text, images,
sound, and numbers. The computer’s hardware focuses on the ability
to process (add, subtract, multiply, divide, compare and branch),
store (retrieve, save) and move (input and output) this data. Here
is a brief list of several major functional components that allow
this to happen.

 The computer processes information in the CPU (Central Processing


Unit) is the silicon chip where all significant processing takes
place. A CPU consists of three parts. The control unit (CU)
determines how the CPU is to execute instructions. The Arithmetic
Logic Unit (ALU) which performs the mathematical and branching
operations described above. And a small storage area consisting of
registers/cache for fast access to frequently used data.

 The computer can store data using a variety of technologies.


Memory serves as a container to hold both executing and non-executing
programs and data. Memory (cache, SDRAM, DDR-SDRAM, etc) tend to be
somewhat fast, expensive and can not hold data or instructions when
the computer is turned off. Storage devices (hard drives and CD-
ROMs) are very, very, very slow. However, they are cheap and can
hold data without the need for a continuous supply of power.

 Input/Output (I/O) Devices refer to a vast array of gadgets whose


job it is to gather information and convert it to binary data (input)
for the computer. Or, to produce information form binary data
(output) stored in the computer. Some devices handle both of these
functions. Examples: sound cards (both), mice and keyboards (input),
printers, monitors (output).

Programs, Programming Languages and Programmers


3
What is a Program? A sequence of binary instruction that the
computer follows, just like a chemical formula. The computer blindly
follow these instructions until the program ends or an error occurs
Types of Programs

 The Operating System serves as an interface between you and the


computer. It also serves as a middle man between other programs and
the hardware / resources underneath. A middle man, manager,
coordinator

 Application Programs serve a purpose for you, such as Microsoft


Word and Doom III. Pretty much Anything that allows you to do your
”job”

 Utilities are programs that enhance the operation of the computer


or some other application. They do no other work themselves

Programming Language(s) are an application (for programmers). There


are several types of languages we can use to create computer
programs. Languages are designed to provide an “easy” method for
programmer to describe a solution and then have the computer
translate these instructions into a sequence of binary language
instructions that it understands. Note that these are black and
white categories, and that modern languages such as Java and the .Net
languages tend to blur across both compiler and interpreter

 Machine/Assembly languages are "low level" languages. That is the


programmer must talk to the computer in hexadecimal, or in it's
native tongue (sequences of 0's and 1's). These, languages are very
fast and efficient (90%-100%). They are very difficult to learn and
coding time is very long. Additionally, they change for each type of
computer so programs written for one type of computer are
incompatible with other types of computers. Examples: VAX MACRO,
68XXX Assembler, 80X86 machine code.

 Compilers can be either low level or high level. They are based on
a "easy" to learn language we use to write source code programs in.
The compiler then handles any preprocessing needed in later steps,
4
such as removing comments from source code. It then converts the
result into object code. This object code is linked with special
libraries and an executable image is formed. (Steps = edit,
preprocess, compile, link, load. . . and then run when ever you
want).
One advantage to a compiled language is that it is easier to
learn and use than machine/assembly language. It is also more
portable, large sections of C source code made on a Macintosh can be
compiled and run on a PC with a minimal amount of changes. And,
compiled languages can easily take advantage of the operating system
features, saving the programmer lots of work. On the other hand,
compiled code is only 30-75% (C is about 75%) efficient and the
programmer must go through several steps to get a working program.
Examples: Turbo PASCAL, C, C++, FORTRAN

 An interpreter is usually a high level language (meaning that it is


difficult to interface with “guts” of the machine. It translates
simple human readable commands into 0's and 1's each time a program
is executed. This means that it is only about 5-15% efficient
because the computer must "compile" each line of source code and then
executing that line each time a program is run. On the other hand,
errors in your code can be detected and corrected very quickly.
Some interpreters interpret byte code which is an intermediate form
of compiled code. Such languages are faster than the standard (20%-
60% efficient) but require a ‘pre-compilation’ of the source code
into byte code before executing

A Programmer is a person who writes programs in one (or more) of the


above languages

 Responsibilities Our goal is to do our job well. This entails

1) Your code works. It meets requirements, has a


reasonable user interface and handles errors gracefully
(robust)

2) It is completed on time and within budget

3) It can be maintained / modified without excessive time


And effort
5

4) It is re-usable

5) *Explore Several Solutions

 Ethics

Software Piracy

Privacy of Data

Use of Computer Resources

Problem Solving

Problem solving is what we do as programmers. It is much like doing


story problems for math, except we do not usually have all the data
at the start of the problem. We try to apply a logical, consistent
approach so that our jobs will be easier

Terminology

 Algorithm A step by step solution to some difficult portion of a


program. It will produce an exact answer in finite time

 *Heuristic A step by step plausible solution to some difficult


portion of a program. It should run much quicker that an algorithm,
but will produce an approximation as an answer

 Software Engineering The discipline devoted to the design,


production, and maintenance of computer programs that are developed
on time and within cost estimates, using tools that help to manage
the size and complexity of the resulting software products
6

 Software Process A set of software engineering tools and techniques


used on a project or by an organization. Varies from place to place
and sometimes even from project to project

 Development Process is a subset of the Software Process concerned


with the design and development of the project. Note this is as much
art as science and also varies a lot from place to place. Three of
the more popular approaches include

Waterfall traditional method of designing and developing


software with some number of stages such as meet with
customer, create design document, get approval, build code,
test code, give to customer, etc. . . See below for an
example of this process

Extreme Programming (XP) tries to involve everyone during


software development process and uses a set of pre-
generated tests cases to determine acceptance of code
versus a lot of design documentation. Heavy on
communication

Rational Unified Process (RUP) also tries to involve


everyone at all stages of the project. Most scientific and
relies extensively on very, very detailed design documents

Program Life Cycle (Using Modified Waterfall Development Process)

Design Phase Should encompass a fair portion of a successful projects


time. Tends to be mistakenly under emphasized by many companies
today due to time constraints for projects. Treat this just like a
story problem in math. List what you know, find out what you don’t
and confirm assumptions. Design and document what you do and don’t
be afraid to revise your first views of the solution. The stages of
A modified waterfall approach might go as follows
7

 Needs Analysis (Problem Analysis) Find out exactly what


needs to be done to solve the given problem from the view
point of the end user

 Requirements Definition (Start of Design Document)

Functional Requirements which are specifications for


describing what the program will need to accomplish,
from the programmers perspective.

Non-Functional Requirements are non-Code limitations such


as language, platform, etc.

 Determine a General Solution (Flow Chart, UML, Work Flow / Time


Line). Show how the program meets the requirements from both the
“big picture” overview on down to the detailed design of each
algorithm. Find the perceived trouble spots and deal with them.
Establish a time line and resource allocations / scheduling for work.

 Design Verification Discuss the design requirements with the


customer(s) to assure it meets their needs. Ideally catch bad
assumptions (finish design document).

Implementation Phase where we code and then deploy the application

 Concrete Solution (Implementation) Code the project. Programmers


should document on the individual level

 Test and verify the application both on an individual level and at


the application level (integration testing). Ideally have a QA team
8
that is separate from the code team test your code. Be sure to use
realistic as well as silly / extreme data just in case

 Documentation Finish any left over internal documentation (likely


code comments and possibly neaten up design document) as well as
write external documentation (user manuals)

 Deployment (Delivery) roll out the new(er) code and be sure to keep
backups of older code just in case you need to roll back your changes

Maintenance Phase where 75% of “bad” programs spend their companies’


resources. The more time we spend on design the less we should have
to spend here

 Use the program. Users or programmers uncover errors and needed


enhancements

 Maintenance Prioritize bugs and enhancements and work on them.


Then test and re-deploy newer code

Things to Avoid when working on a project

 Make as few assumptions as possible. Check everything you can

 Don’t just sit down and hack out some code

 Don’t do more than what was asked for UNTIL the basic code works

 Don’t shoot for 90% correct. Its’ an A in my class, but a


reprimand (maybe) or a pink slip (eventually) in the real world
9

 Don’t forget to get buy in for any changes to the design once
approved. Keep people in the loop

 Don’t ever forget the importance of visual appearance, meeting your


requirements and timeliness, over an efficient / clean solution if
choices must be made

 Documented well

Chapter 2: About OOP, Events, Java and Setting up Your PC

OOP

An Object Oriented Programming (OOP) Language combines several


concepts that allow us to work with ever larger projects and enhance
10
their maintenance and reusability. Since Java is only capable of
creating OOP programs, we will focus on what OOP is, rather than a
compare it non-OOP languages and techniques. Suffice to say that OOP
is generally beneficial, but at a cost of complexity for the
designer/coder and sometimes program execution speed.

OOP Concepts The key conceptual building blocks of the structure of


most OOP languages are as follows

 Encapsulation is word that means that data and algorithms are


combined to together in one indivisible item with access
restrictions. A program consists of one or more of these objects.
Further, because these objects all are required to adhere to their
own set of interfaces. It is possible to replace one object with
another, and not introduce bugs - so long as the new object’s
interface remains the same as the old. We can also modify how any
object stores data or works internally with similar results and
restrictions.
To accomplish this separation we need two things. First, a
container that holds both the data and the code. In most OOP
languages this is called a class (from which objects are created).
And second, a means of enforcing what can (not) access these pieces
of data and algorithms in the class. In java we use one of four
keywords to control this access

Public any object can access the code or data. Even


objects of an entirely different class

Protected only objects of this class, or of a class that is


derived from them, may access the code or data

Package only objects of this class and its’ derivatives


OR classes that are part of a given project (package), can
access the data or code. This is the default for Java and
is also an unique encapsulation type to my knowledge

Private only objects of this class may access the data or


code
11

 Abstraction is typically lumped in with encapsulation, but is


technically different. Abstraction means that the data that the
world sees may not be how that data is represented internally to the
class. For example, while we type characters, the computer stores
everything as binary numbers anyway. In combination with
encapsulation this means that we are free to change how our code
works, and how we store data in our class. So long as the means of
accessing (interface) and results our code produces fro a given input
stay the same

 Inheritance means that a class can be expanded to perform other


functions by just creating a file (a derived or extended class) that
adds/modifies only the changed feature(s) to the base class without,
re-writing the whole thing. As an example, several versions of
windows are all the same code base and can be easily maintained
because of this. Note that in Java, it is not fully possible to
support Multiple Inheritance where a class derives from two (or more
base classes)

 Polymorphism means that a class with a given interface can be


reused for a similar purpose in another project. Or that a given
interface is retained regardless of the class that underlies it. For
the former, a gas gauge class could be used in a Honda, a Nissan or
whatever. For the later, an on off switch works the same to the user
even though its connections to a calculator or a radio would do
different things internally

 Dynamic Binding is a nuts and bolts concept that goes hand and hand
with inheritance. While, not one of the prime concepts of OOP, it is
required to handle inheritance correctly. Essentially, if code
expects one object, it will also work with any inherited object (More
on this much later)

Events
12

Events are actions that can cause programmer changeable code to run.
Examples of events include a printer reporting out of paper, a user
clicking a mouse, each character entered in a text box, etc. If the
programmer does not over ride these actions, then they do whatever
they would normally do (usually very little). However, it is
possible to use inheritance to add code to events so that they can do
more (or less) then what is normally done

 Menu Driven Programming presents the user with X options every so


often, and that is all it handles at that moment. Each program is
responsible for handling its own menus and this si less efficient
than with the event driven model

 Event Driven Programming allows us to simply associate our code


with specific events that can occur, and leave it up to the OS or JVM
(more later) to handle everything up to the actual code running.
There are several reasons for this being a more flexible and
efficient approach then typical menu applications, but for now we
will just say it is so (See events later in course). As a down side
event driven code is much harder to debug as events can be both
asynchronous and trigger in odd combinations

 All Events are objects based on a hierarchy of inherited classes,


this makes expanding the event code easy when new events are needed.
An example, is a mouse click this event object that contains all the
data (which button was clicked, what the mouse was over, etc) and
code needed to know about, and handle, that particular an event

 All Events are originally triggered by the OS. This in turn passes
the event objects to the Java Virtual Machine (JVM, more later). The
JVM periodically checks to see what events it has. If someone’s Java
program has some special event code that matches that event, it will
run that code
13
Java

Java is object oriented language that is designed to be safe,


platform independent and to be easier to use than C++. It is a fully
object oriented interpreter. An examination of Java turns up several
interesting points

 Java is in some sense a compiled language, because Java programs


are first byte code compiled. This means that our English language
commands are first converted to a very dense platform neutral code.
This code is not directly executable however, it just an intermediate
form of code. The upside to this is that any machine that can read
this byte code can run your program. This is the essence of the
“Write once, Run anywhere” motto of Java. The downsides are that
Java loses the ease of debugging compared to truly interpreted
languages. And, that this cross platform compatibility is not really
100%. Although it does this far better than any other language I am
aware of

 Java is primarily an interpreter. Each time you run a program, the


byte codes are loaded by the Java Virtual Machine which then
interprets them as your code runs. The plus is that these byte codes
are much faster to interpret than traditional interpreter. They are
still notably slower than other compiled languages such as C++ or the
.Net languages giving rise to the motto, “Write once, Run anywhere
slowly” joke made by its detractors

 Java is a clean ground up design incorporating almost all the


object oriented features that allow large, scalable, maintainable and
reusable code to be created fairly easily. The exceptions? Java is
implemented in such a way that some trivial things are actually
harder (text input and file usage), or slower (arrays) than in other
languages. Also, a few important features of most other OOP
languages where left out of Java, primarily templates and operator
overloading
14

 Java supports safe computing. The JVM first checks Java code to be
sure that it can not do anything malicious before running it. This
is especially true of Java applets (small Java programs downloaded
off of web pages). This increases the safety of running Java
programs, but at the cost of increased start up times. The later
issue is one reason why there are very few web sites that have client
side executable Java content any more, despite the safety guarantee

 Java supports Rapid Application Development (RAD). Java makes it


easier to do such things such as DB connectivity and Graphical User
Interfaces (GUI) in comparison to the bad old days VC++ (pre VC+
+ .net). And, through Java Beans, it even offers some “click and
code” functionality similar to VB. However, it is not as easy to do
so as when using the newer versions of any of the .Net languages, or
VB 6.0 for that matter.

 Java is pointer free language that handles memory allocation and


freeing up that memory automatically for you. This may not mean
much to you, but in the bad old days (and still in C++) pointer
errors where/are the number two cause of runtime bugs. This means
that Java code tends to be more robust and easier to write / debug.
However, this same approach makes it both hard to get to the lowest
level of the machine/OS and can make it impossible to directly
manipulate memory as you may wish at times. Luckily the need for
this is rare

Java’s Industry Adoption is mixed. Java is the major player in the


mobile devices arena, and it is also used with frequency as a server
side language for web sites. But, while Java has made some
appearance in the PC application arena, it has not yet been strongly
adopted in the applications space. Basically, only very small
companies that can not afford to develop cross platform. Or,
companies that do not want be tied to Microsoft for economic or
political reasons consider it for broad deployment. Of course, this
later segment is rapidly growing given Micro$ofts recent licensing
terms debacle and the recent general down turn in the economy
15
Currently, maybe 15% of the application jobs require Java. To my
knowledge the biggest local adopter that I know of is Sherwin
Williams. However, most of the major IT shops (National City,
Progressive, University Hospitals, Cleveland Clinic) are mostly all
Microsoft (VC++, C#, VB, ASP) on the desktop / web servers with some
Java used on certain projects

Java has a variety OOP Structures are used to embody the key OOP
concepts we previously mentioned. The basic Java structures are

A Class is the basic plan for your objects that will make up your
Java programs. This is a structural container that holds a
description (blue print) of the field variables (the data) and the
methods (the code) that make up each object you will instantiation
(create). This process works very much like using the blue print for
a Ford Focus from which you can build any number of actual Focuses to
use.

 The class itself requires encapsulation and allows the static


modifier if desired (more on this later). Note that the main class
file that your program start with must have public encapsulation

 The name of your class must also be the same as file name (not
counting the .java file extension) that stores it including all
capitalization. Note, if you have more than one class in a file the
other classes do not have to be so named

 A class is a structure used to describe a grouping of data and


methods to the Java compiler. And, like all structures, it uses { }
to contain everything else associated with that class
 A class may contain data in the form of field variables. In
general each object created from a class contains its own independent
copy of each field variable, unless that variable is static

 A class may also contain code in the form of methods. As for field
variables, a copy of each is created fro each object created for each
object of the class
16

 Any field variable or method in a class can be accessed using the .


(dot) naming scheme. Eg) Object.methodname() or
object.fieldvariablename. Note that it is possible to have nested
class structure where by an object of one class contains an object of
another a class, etc. So something like
object1.object2.object3.fieldvariablename is possible assuming
encapsulation allows (i.e. not private, etc)

Methods are named sections of code in a class. Each method


typically performs some function using statements, other control
structures and local variables (more on all later). Thus, methods
are the ‘actions’ that an object of a class can perform. In general
we try to create fairly flexible methods that can work with a wide
variety of data. So, for example, a method that squared 2 would be
fairly useless. A method that squared any value would be more
useful. But, a method that could raise any number to any power would
be preferable to both previous concepts

 All methods need a name, a list of values to do there job called


parameters (can be nothing) and what they give back called a return
type (if anything) when they are finished executing

 All methods require encapsulation and allow the static modifier if


desired (more on this later). Note that exactly one method named
main may exist in your whole program and it must be static and
public. This is the method that will start executing when your
program is run

 A method signature is how the compiler determines which method to


run. This consists of the method’s name as well as the number, type
and order of its parameters (more on this later). Note that the
return type is NOT part of this signature

 A method is a structure used to describe a section of code to the


Java compiler. So it uses { } to contain everything else associated
17
with that method. Which include local variables, calls to other
methods and code statements

 A method in an object can be accessed by calling its signature and


giving it arguments using the. naming scheme. Eg)
objectname.methodname(value1, value2);

 A method usually interfaces with the rest of the program through


the values it receives and passes back. The values that we provide
when calling a method from our code are called arguments. When the
method receives them, they are called parameters. And finally, if a
method gives a value back to the code that called it, that value is
its return

 Each object of a class will have its own copy of each method,
unless that method is declared static (more later)

Field Variables are values available to an entire class. Each field


represents some property (data), such as gas level in tank, or
position of the overhead dome light switch. If methods are actiosm
then variables are the things (data) we act on

 All variables need a type and a name

 All field variables require encapsulation and allow the static,


const or final modifier if desired (more on this later)

 A field variable is not a structure

 A field level variable in an object can be accessed by specifying


its name using the . naming scheme. E.g.)
objectname.fieldvariablename;
18

 Each object of a class will have its own copy of each field
variable, unless that field variable is declared static (more later)

How Java Programs are Made and Executed

 Traditional Java Approach

Edit your plain text source file(s) (with a .java extension)


using a text editor or your IDE

Use the Java byte code compiler (javac) to convert your program
to byte code, or chose compile for your IDE

Distribute your compiled byte code class file


User tries to run program by typing (java program_name)

The OS starts the Java Virtual Machine (JVM) whose job it is to


interpret byte codes if it is not already in memory

The JVM then loads the program byte codes into memory

The program’s byte codes are verified for security to make sure
your application does not do anything naughty

The JVM then executes the program by interoperating the


byte code

 Compiled Approach it is possible for Java to run like a true


compiler with some other software. You lose portability, but gain
speed

Edit your plain text source file(s) (with a .java extension) as


above

Use a true Java compiler such as the GNU Java Compiler (GCV –
http://gcc.gnu.org/java/ ) to convert your program directly to
19
native machine code

Distribute your executable code

User tries to run program

The OS loads program

The OS executes program just like any other program

Setting Up Java on Your PC

 You can get an older version of Java off of the CD that comes with
the course book. However, a newer free version is located at
http://java.sun.com/j2se/1.4.2/download.html. Note that this is a
big download. Do it over night if you are a modem user (or go to a
friend’s house with broadband and burn a CD from him/her)

 I do not recommend the IDE that comes on the CD. It is very slow,
difficult to use and quite buggy. To get a decent free IDE that
works on all Windows versions that I am aware of, try going to the
site http://www.jcreator.com/ and downloading the free version 2.50
LE. It is only a 1.8 meg download. A “Pro” version featuring
inteli-sense is about $30 and well worth it.

 If you wish to use Java from the command line you will need to set
the Path Environment Variable. Under XP / 2000 this can be set in
control panel -> system -> advanced -> environment variables ->
system variables -> path. Add the following to the path to make it
look like the end of this line ( That assumes that is the version and
location where Java is installed for you – should be correct if you
downloaded from Sun’s site above and changed nothing during
installation )

;C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin; C:\Program Files\j2sdk_nb\


j2sdk1.4.2\lib
20

 Class Documentation for the various standard components of Java can


be found at http://java.sun.com/j2se/1.4.1/docs/api/index.html. Mark
this and use it when needed

 Some good free tutorial/references include Thinking Java, 3rd


Edition a free downloadable web book which I base my notes in part on
at http://64.78.49.204/. Also Sun has an extensive site on Java
tutorials at http://java.sun.com/docs/books/tutorial/

 Other help can be found on the web at http://www.google.com/ by


searching for the key words. If you needed help on
System.out.println for example. Try the keyword line “Java Tutorial
println” as a good starting place.

Source Code Example)

// Class test
// Prints a message to the screen
// written by David Antolovich

class test
{
public static void main( String args[] )
{
System.out.println("Hello and welcome to CIS 260.");
} // end main routine
} // end class test

Some Essentials to Note

 Comments are notes to other programmers, something that the java


byte code compiler throws out. Anything on a line after // or
anything between pair of /* */ is a comment and not a program
instruction

 Every program will contain files with one (or more) classes each.
However, only one class of all files in a project can be defined as
public. This is an indicator to the computer that this class
contains the a starting code to use
21

 public class test


{

Creates a class called test. Public is the encapsulation, the class


word designates that this will be a class and test is our name
Everything that is part of the class test must be enclosed inside the
{ }

 public static void main( String args[] )


{

Creates a method called main. Public is encapsulation. Static is


something we need for our main method (more later). Void is the
return type (void means nothing). The stuff in the ( ) are the
parameters that we expect to receive as arguments from whom ever
calls this method. All the code that goes with our method must be
enclosed in this set of { }

 System.out.println("Hello and welcome to CIS 260.");

This is a call to an already completed method called println. Note


the . naming scheme and the that calls trough two objects System and
out. The stuff in () is the argument we are giving println

 Note that test and main() are a special case. The OS implicitly
and automatically instantiates an object from class test and runs its
main method by default. Every other object we want to create and
every other method we wish to use has to be done explicitly

 We don not have to code all the methods we wish to use. If someone
else has made them, such as System.out.println(), then we can just
call them and use them
22

 Each actual executable statement ends with a ;. Note that


structures such a class test and the method main are not statements,
so we do not end them with a ;

Chapter 3: Variables, Types, Modifiers

Variables

Variables are named containers that can store changeable data as


opposed to literal values typed on the screen. In Java there are two
types of variables. A reference variable holds a location in memory
23
where some object is (or can be). And, primitive variables, that
store a value

Five Key Concepts that involve variables.

 Declaration occurs when we specify a type and a name for a


variable. We must specify a type because Java is strongly typed
language – meaning it checks how we use that variable later to make
sure we are not trying to fit a square peg into a round hole. Note
you may never declare the same variable more than once in the same
scope (more later)

 Definition strictly speaking, this occurs when the memory is


actually allocated for this variable. Generally this is in the same
step as declaration

 An Assignment occurs any time we place a value in this variable.


This step can even be combined with the first two when a variable
appears for the first time in code. Since we can change the
variables value throughout our code, we sometimes call subsequent
assignments re-assignment

 A Reference occurs any time we read the value currently in the


variable. Note, do not confuse this use of reference with a reference
variable.

 Instantiation occurs any time we assign a new object to a reference


variable (More on this later).

The Scope of variable affects where it can be seen. For now, assume
that we have two choices

 Local scope refers to variables that are declared and defined


inside a method. Such variables are declared and defined each time a
method is called. When the method is finished, they are destroyed
and the values they hold are lost. Local variables do not have
encapsulation as they are only available inside the method they are
declared in
24

 Field variables have class wide scope and are declared and defined
outside of any method (but within the class). Such variables are
declared and defined once each time an object is instantiated from a
class. They are accessible to any method in the class and survive
until the object itself is terminated. All such variables must have
encapsulation

Source Code Example)

// Class test
// written by David Antolovich

public class test


{
// declaration / definition of field variables would occur here

public static void main( String args[] )


{
// declaration / definition of variables local to main would go
// here

} // end main

public static void othermethod()


{
// declaration / definition of variables local to othermethod
// would go

} // end othermethod

} // end class test

Types

Java supports several types of Variables and each type has its own
uses and limitations. Variables can take more or less memory to hold
and can also store different things. In general the more flexible or
complex a variable type, the slower it is to use. Types listed below
marked with * are the fastest to work with
25
 Whole numbers are represented by numbers with no decimals or
special surrounding characters other than the – character. Example
literal values) 1 4 6 23 -45

byte storing from 0 to 255, 1 byte

short storing from 0 to approximately 64000, 2 bytes

int *stores from 0 to 4 approximately billion, 4 bytes

long stores 0 to some really big number, 8 bytes

 A limited form of real (decimals) numbers can be represented in the


computer. Such forms can not only over flow, but also underflow.
and all have gaps between values that can not be represented. Also,
such numbers take more computationally intensive to work with then
whole numbers. The compiler can determine which numbers are decimal
values because of the point. Example literal values) 3.4 -5.6
3444.23

float *stores a small floating point number of about 10


or so total digits accuracy, 4 bytes

double storing a larger float, 8 bytes

 Character variables also exist but are fairly slow to use. In


Java all characters are Unicode. This means they are more flexible
than the character variables in other languages, but also slower and
suffer from some added work needed in converting them back and forth
with most other software. Note that the String type is actually a
object / reference variable but is included here any away since they
deal with text.
The compiler can determine literal character values because they
are surrounded by ‘ ‘ marks. String are surrounded by “ “ marks.
26
Example character literal values) ‘a’ ‘1’ Example string literal
values “Hi” “234445” “r” “”

char *stores a single character, 2 bytes

String storing a sequence of characters, 2 bytes * size + 2

 Reference Variables are any variable that stores a memory address


rather than a value. All are 32 bits long, because that is the
addressable range of the CPU. And all objects are accessed through
reference variables
Since objects of custom size, when a new object is instantiated,
it is created in a space in memory called the heap (more later). The
local or field reference variable holds the location in the heap
where the object is at. Thus, accessing the object is a two step
process; first access the reference variable, then go to memory in
the heap and access the object itself. This is of course slower than
with primitive variables which store their values directly
On the plus side, you can change what a reference variable points
to without losing the original object (with work), and have distinct
advantages when used as arguments (more later), and have more than
one reference variable point to the same object
Declaring a reference variable does not automatically create an
object. It merely creates the reference variable and sets its value
to null. To get a reference variable to point to an object either
assign it the value of another reference variable (two or more refs
can look at the same object) or assign it the results of
instantiating a new object (more)

Modifiers

Modifiers can be applied to variables when they are declared and


affect how the variable is used. Note that they can be combined if
you wish

 final is used to indicate a variable can not have any other value
assigned to it after it is first declared. In essence these are
“constant” variables. One use of this is for such thing as defining
27
PI or some other global and unchanging value you may need in your
code

 Encapsulation is required for field level variables and defaults to


package unless you specify otherwise. The other keywords are
public, protected and private as per the section on OOP above. Note
that local variables can never have an encapsulation modifier

 static may indicate one of four things. Two of which have to do


with methods and classes but are included here for completeness

In front of a field variable, it means that there is one


shared value used for each and every object of a class.
Normally each instance would have its own independent copy
of each field variable. In this way different instances can
share information. Note, that this is required if a static
method wishes to use a field level variable. Also, a static
variable of a class is available to access even
before any objects of the class it is in are created

In front of a local variable it indicates that that


variable will retain its value between calls to that
method. The variable’s value never gets reset after the
first time it is initialized even when that method ends.
Note that the local variable is still only visible to the
code in the method that contains it.

In front of a class it indicates that only one such class


may ever exist and that it is automatically instantiated
when the program starts. This means you can use dot
notation to access methods and field level variables
without explicitly instantiating an object o this class

In front of a method it indicates that only one such


method ever exists no matter how many object of this class
28
are instantiated. A static method may only access field
level variables that are also static

Declaration and Naming Conventions

 You may not name a variable after any reserved word or key word in
Java. A reserved word is word Java may use for itself. A keyword is
a word it currently uses.
Eaxmples) ( + main { - println int float .

 You must start a variable with a letter followed by up to 32 other


letters or numbers or _ character. There are a few other character
that you could use but I do not recommend it.

 No two variables in the same class and scope can have the same
name. Thus you could have a field level variable called x and a local
variable in each method of the class also called x. But, never two
field level variables called x or two local variables in a method
both called x

 By Java tradition you pick names starting with a lower case letter
and then capitalize every word in the name. You may use modified
Hungarian notation if you wish
Examples) iSocialSecurityNumber, myVariable, x

 Also, traditionally in Java field variables are declared before the


first method. Variables local to method are declared before the code
for that method begins. However, some coders prefer to declare local
variables right before use

 Good practice is to make names as descriptive as possible. E is a


great variable name in a physics program (E=MC2), but very poor
choice otherwise. Energy would be a better name in those cases
29

Source Code Example)

// Class test
// declares and assigns to variables and prints results
// written by David Antolovich

public class test


{
// declaration / definition of field variables
static int iMySSN;
static float fBankBalance;

// declaration / definition of field variables


final char cFirstInitial = 'D';
static String sMyName = "Dave Antolovich";

public static void main( String args[] )


{
// declaration / definition / assignment of local variables
double dNationalDebt = 24000000;

System.out.println("iMySSn = " + iMySSN);


System.out.println("fBankBalance = " + fBankBalance);
System.out.println("cFirstInitial = " + cFirstInitial);
System.out.println("sMyName = " + sMyName);
System.out.println("dNationalDebt = " + dNationalDebt);
} // end main routine

} // end class test

Chapter 4: Import, Streams, Output, Input

Import

Import is a keyword that simplifies the use of previously predefined


methods and objects in our code by allowing us to abbreviate the
location of these classes. So long as the class / method we want to
reference is in the computer’s path, Java will try to find it based
on the dot naming scheme and then use it. Note, that not everything
30
needs to be imported, classes considered to be part of the core Java
language, such as System, are static and thus provided for us
automatically

 All imports must come first in our code, even before we start our
class declaration(s)

 import must have the full . naming scheme to locate the appropriate
class.

 We can specify a specific class / field of class. Ex)


javax.swing.JOptionPane; Or, import all classes / fields of a class
by using *. Ex) javax.swing.*

Streams

Streams in Java almost all textual input or output is handled by


streams. Each stream is essentially a holding bin in memory that
serves as a “middle man” between our program and the actual OS
controlled hardware itself

 An Input stream allows us to look into the bin and remove /


retrieve information from it. The computer / operating System
handles the actual placing of information into the bin from the
appropriate input device when we request input. When the OS finishes
this we can then retrieve as much of the information as we wish

 An output stream works the just the reverse of the input stream.
Here we place things into the bin, and then OS will remove as much
information (usually all) as it wishes and send it to the appropriate
output device

 The bins that streams use should never be confused with the actual
IO device itself. For example it is possible to send stuff to be
output and have the machine crash after we have completed adding
31
information to the bin, but before it actually gets written to the
output device

 The streams can be buffered or unbuffered. Buffered streams will


read or write data in big gulps from the hardware and temporarily
store that in our ‘bin’. Each time we request information from a
stream for example, we first look in the bin. Only if it is empty
would we actual go back to the hardware for input. Unbufferd streams
do not do this, they typically connect fairly directly to the
hardware

Output

Output is the display of information to the user. Generally we are


either writing text to the screen, working with some GUI component or
sending information to a file (more on this later).

Text Output is accomplished via using the println or print method we


have seen previously. The distinction is that println will also
cause a carriage return to occur after it prints

 println( /* string of text here */ ); outputs all the included text


to the screen and then skips a line

 print( /* string of text here */ ); outputs all the included text


to the screen but does not skip a line after printing to the screen

 Punctuation and Spaces are up to you to provide. The computer


makes no assumptions so if you want words to be spaced out, you must
include a space between them, Etc.

 System.out is a static class which means that we can access its


code right away with out having to know anything else about how to
32
“declare and define” objects of classes. It also means that we can
not declare and define objects of this class. Essentially this is
Java’s way of creating re-usable code that we can just use without
having to do / know a bunch of OOP stuff
The \ character is a special character when doing output. When
embedded in a string with print and println, it indicates that the
next normal character should be treated specially. Or, if the next
character is a special character, that it should be treated normally
instead. This is special property of the way print / println works
and not something part of strings themselves

 \n indicates a new line

 \t indicates a tab

 \” indicates printing a “ and not the end of a string

 \\ indicates printing a \ and not treating the second \ specially

Source Code Example)

// Class test
// uses print and println and \
// written by David Antolovich

public class test


{
public static void main( String args[] )
{
System.out.print("Hi");
System.out.print(", how are you?");

System.out.println("\n\n");

System.out.println("And then Dave said, \"Hi, how are you.\"");

System.out.println("3 back slashes: \\\\\\");

System.exit(0); // ends the program


} // end main routine
33

} // end class test

GUI Output can be done with a variety of widgets and is fairly easy
to do in Java. We will look at just the simplest message box to
start with and explore other GUI widgets later on in the course

 import javax.swing.JOptionPane; is required to use sing GUI


objects. This is the most recent GUI Java API and so we will use it
over the more basic awt library. JOptionPane is a class that allows
for the display of message boxes and also retrieval of user entered
strings from an input box. Import shortens the path for using this
we can import the class javax.swing.JOptionPane so that we can now
use just JOptionPane in our dot notation

 JOptionPane.showMessageDialog( null, String Message ); Causes a


message box to appear with the appropriate message displayed for the
user. They then have to click okay to make it go away.
showMessageDialog is the method. The first argument indicates which
window to appear over, in this case a null means whichever the
current window is and the message is the text that will appear in the
dialog box

 System.exit(0); should be the final instruction we give the


computer in our main method. It indicates that the program is done
and his worked correctly if we have reached this point. We must
explicitly do this now because we are working with GUI windowing and
events – even though we do not see the guts of this here

Source Code Example)

// Class test
// creates a message to say hello
// written by David Antolovich

import javax.swing.JOptionPane; // imports JOptionPane

public class test


{
public static void main( String args[] )
{
34
// say hi
JOptionPane.showMessageDialog( null, “Hello and welcome to Java.”
);

System.exit(0); // ends the program


} // end main routine

} // end class test

Input

Input is the gathering of information from the user. Generally we


are reading text from the keyboard off of the command line, reading
text from some GUI component or reading from a file (more later).

Text Input is sadly a much more complex process than for output. We
need to deal with exceptions (events), import and instantiating
buffered reader objects and attaching them to System.in. To shorten
this I include a separate class that can be used to help retrieve
keyboard input from a text window.

Source Code Example)

import java.io.*;

// DaveIO class that serves as a short cut for text input


// Reads and returns a string from keyboard input
public class DaveIO
{
public static String readtext() throws IOException
{
BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));
String message = "";

message = stdin.readLine();

return(message);
} // method readtext

} // class DaveIO
35

// Test code
import javax.swing.JOptionPane; // imports JOptionPane
import java.io.*;

public class Test


{
public static void main( String args[] ) throws IOException
{
DaveIO objInput = new DaveIO();
String strTest;

// say hi
JOptionPane.showMessageDialog( null, "Hello and welcome to Java."
);

System.out.println("Enter some text");


strTest = objInput.readtext();
System.out.println("You entered: " + strTest);

System.out.println("Enter some more text");


strTest = objInput.readtext();
System.out.println("You entered: " + strTest);

System.exit(0); // ends the program


} // end main routine

} // end class test

GUI Input can be similarly to GUI output. We will look at just the
simplest input box to start with and explore other GUI widgets later
on in the course

 JOptionPane.showInputDialog( null, String Message ); Causes a


dialog box to appear with the appropriate message displayed for the
user. They then can type information into the box in response to the
question. Hitting okay or pressing enter will return that
information to us as a string and we must assign that information to
a string variable. Hitting cancel will abort the entry of
information. The arguments are the same as for the message dialog
box
36
Source Code Example)

// Class test
// creates a message box
// reads in some values by the user using an input box
// writes those values back to the screen
// written by David Antolovich

import javax.swing.JOptionPane; // imports JOptionPane

public class test


{
public static void main( String args[] )
{
// holds user’s name
String sUserName;

// ask if we can continue


JOptionPane.showMessageDialog( null, “click okay if the computer
can ask you a quesiton.” );

// retrieve users name saving it in a variable


sUserName = JOptionPane.showInputDialog( null, “Please enter your
name” );

// print name back to the screen


System.out.println( “You entered ” + sUserName );

System.exit(0); // ends the program


} // end main routine

} // end class test

Chapter 5: Operators, Concatenation, Precedence and Conversion

Operators

Expressions are formulas involving operands (literal or variable


values) and operators (mathematical or logical). Note that operands
can include results from calls to other methods, or referencing
variables in other classes as well (so long as they have a valid
value or return a valid value)
37

Mathematical Operators are what we use to get mathematical work done.


Operators in an expression are evaluated one at a time in order of
precedence (later). The result an operator produces is always of the
most complex variable type of its operands. So an operator that
worked on a String and an integer, or an integer and a String, would
produce a String as a result in either case. Operators can be

· Left Associative meaning the left hand side evaluates before the
right hand side

· Right Associative which works the other way around

· Unary, working with only one operand at a time

· Binary(typical), working with two operands at a time

Basic Operators are all left associative and binary. They work only
on primitive literals and/or variables

· Multiplication *

· Division /, be careful of dividing two integers

· Addition +, works as concatenation for strings (later)

· Subtraction -

· Modulus (%) is the numerator of the remainder of a division. It is


left associative

intX = 2 % 5
38

intX = 0 % 5

intX = 17 % 5

Special Mathematical Operators

· Assignment = is right associative and binary. Assignment causes


the value of the right hand side expression to be placed in the
variable named on the left hand side. It can be used for both
primitives and reference variables

· auto increment ++ a unary operator that increments a primitive


variable’s value by 1. Can be pre or post increment

iX = 4;
iY = ++iX + 3;

iX = 4;
iY = iX++ + 3;

· auto decrement –- a unary operator that decrements a primitive


variable’s value by one. Can be pre or post decrement

iX = 6;
iY = --iX + 3;

iX = 6;
iY = iX-- + 3;
39
· unary + or – used to temporarily flip the sign of a primitive
variable’s value

fX = 6.0;
fY = -fX + 2.0;

Logical Expressions work with operands that always evaluate to true


or false no matter how complex the expression

Basic Logical Operators include <, >, <=, >= and are binary, left
associative and only work on primitives

Special Logical Operators

· Logical Negation !, makes true false and false true. This is a


uniary operator that works on other logical expressions or bolleans
only

! ( 5 < 3 )

· Is Equal ==, evaluates to true if both sides are equal. This is a


binary operator that works on both primitives and objects. For
objects it determines if two references are looking at the same
object however, NOT if two objects are have the same content

3 == 4

· Not Equal !=, evaluates to true if both sides are NOT equal.
Binary, and usable for both primitive and reference types with the
same conditions as above

3 != 3

Compound Logical Operators allow us to link logical expressions


together.

· Logical And, && means the expression is true if both sides are
true, this will stop evaluating (short circuit) if the left hand side
is false. & works the same way but does not short circuit
40

3 != 3 && 4 < 5

· Logical Or, ||, means the expression is true if either side is true
and it will stop evaluating if the left hand side is true (short
circuit). | works the same way but does not short circuit

3 > 2 || 4 < 7

Concatenation

Concatenation Operator is an over loaded operator, something not


normally part of Java. However, the + operator is one of the few
that is overloaded. The + can be used between strings, variables and
literals. In this case, the string(s) and/or string values of a
variable are attached together to form a longer string

· Java implements string concatenation fairly inefficiently. Use as


so use few as possible. In most cases it is not something worry
about, but if you are doing whole lot of this sort of thing then see
what you can combine or eliminate. Or switch to other forms of text
manipulation

Source Code Example)

// Class vartest
// shows use of + for concatenation
// written by David Antolovich

public class test


{
public static void main( String args[] )
{
// declaration / definition / assignment of local variables
char cFirstInitial = 'D';
String sMyName = "Dave Antolovich";
41
System.out.println("Hi, my name is “ + sMyName + “ and my first
initial is “ + cFirstInitial + “.” );

} // end main routine


} // end class test

Precedence

Precedence refers to the order of evaluation of the operators before


left or right associativity is considered. Precedence is important
because all languages work with just one operator at a time in an
expression. If you are unsure of the precedence which will take
place, you can always use () to over ride

( )
! + - (unary operators)
++ -- (pre increment / decrement )
* / %
+ -
<=, >=, <, >, ==, !=
&&, &, |, ||
=
++ -- post increment / decrement

Examples

iX = 3 + 3 * 3;

iX = ( 3 + 3 ) * 3;

fX = 2.0 * ( 1.0 + ( 3.0 * 2.0 ) );

2 == 4

5 != -5
42

ix = 3;
3 < 4 && ix++ < 5

--5 <= 4 && 4-- >= 4

2 != 4 | 7 < 4

Type Conversion

Converting Values it is possible to convert values from one type to


another, and because Java is strongly typed we usually have to do so
explicitly.

Automatic Promotion occurs among primitive variables of the same


basic type types in assignment (including calling methods) and during
the evaluation of expressions. This change only affects the
resulting assignment (if any) and not the original variable(s)
type(s). We need not use any explicit method for conversion,
although we can if we wish (see below)

· Numeric variables all convert upwards automatically. So an int can


be assigned to long with no issues. An int can also be assigned to a
float or double as well

iX = 1;

fY = iX;
dZ = iX;
lX = iX;

· Decimal Variables all convert upward automatically, so a float will


convert to a double
43
fX = 3.333;
dX = fX;

· Cross Type Conversion does not happen automatically among


primitives other than what has been described. As a matter of fact we
can not do so using this sort of conversion, so no Boolean to tring
or char to String, etc

Casting is the name for explicitly converting a primitive from one


type to another. We do so by specifying the type we want to convert
to in ( ) ahead of the value / variable we wish to convert. We can
convert downward (to smaller simpler variables) by doing this.
However, some information maybe truncated or chopped off. Otherwise
it works like automatic conversion above

· Numerics and Decimals can be cross converted in any way as follows

iX = 1;
dZ = 3.2222;

iY = (int)dZ;
dZ = (int)3.2 + 2.3;
fX = (float)dZ;

Converting To and From Strings involves using the predefined


conversion methods provided in Java for each primitive type. When
converting from a string we use Type.parseType( String value ). When
converting to a string we can use concatenation (slow) or
Type.toString( Type value ) which is faster

Source Code Example)

String sAge;
Int iUsersAge;

sAge = JOptionPane.showInputDialog( null, “Please enter your age” );


iUsersAge = Integer.parseInt( sAge );

sAge = “” + iUsersAge;
sAge = Integer.toString( iAge );
sAge = Double.toString( 13.2 );

You might also like