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

Java First Session

The document discusses Java programming language concepts including what programming and programming languages are, object oriented programming principles, Java technology, applications of Java, Java versions, and advantages of Java over other languages. Key topics covered include programming concepts like algorithms, different types of programming languages, and object oriented concepts like abstraction, encapsulation, inheritance, and polymorphism. Java is presented as a simple, powerful, platform independent language similar to C++.

Uploaded by

Eslam Zidan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
483 views

Java First Session

The document discusses Java programming language concepts including what programming and programming languages are, object oriented programming principles, Java technology, applications of Java, Java versions, and advantages of Java over other languages. Key topics covered include programming concepts like algorithms, different types of programming languages, and object oriented concepts like abstraction, encapsulation, inheritance, and polymorphism. Java is presented as a simple, powerful, platform independent language similar to C++.

Uploaded by

Eslam Zidan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 139

Java Programming Language 

Session 1 
1. Programming concepts and algorithms
a. What is programming: it is the process of writing, testing,
debugging/troubleshooting, and maintaining the source
code/commands/instructions of computer programs. This source
code is written in a programming language e.g. visual basic, C,
C++, Pascal, Java.

b. What is a programming language: A vocabulary and set of


grammatical rules for instructing a computer to perform specific
tasks. The term programming language usually refers to high-level
languages, such as BASIC, C, C++, COBOL, FORTRAN, Ada, and
Pascal. Each language has a unique set of keywords (words that it
understands) and a special syntax for organizing program
instructions.

High-level programming languages, while simple compared to


human languages, are more complex than the languages the
computer actually understands, called machine languages. Each
different type of CPU has its own unique machine language.

Lying between machine languages and high-level languages are


languages called assembly languages. Assembly languages are
similar to machine languages, but they are much easier to program
in because they allow a programmer to substitute names for
numbers. Machine languages consist of numbers only.

Lying above high-level languages are languages called fourth-


generation languages (usually abbreviated 4GL). 4GLs are far
removed from machine languages and represent the class of
computer languages closest to human languages.

Regardless of what language you use, you eventually need to


convert your program into machine language so that the computer
can understand it. There are two ways to do this:
• compile the program (explained later)
• interpret the program (explained later)

c. Kinds of programming Languages:

• Imperative— “telling the machine what to do”


• Declarative— “telling the machine what to achieve”

d. What is object oriented programming: a method of


implementation in which programs are organized as cooperative
collection of objects, each of which represents an instance of a
class, and whose classes are all members of a hierarchy of classes
united via inheritance relationships. These objects communicate and
interact together E.g. books (science fiction/ adventure/ horror),
customer (individual/ retailer), product (CD/ DVD/ HD) . Advantage:
easy to create similar objects without having to rewrite the
overlapping code, just modify

Four major concepts of OOP


• Abstraction: denotes the essential characteristics of an
object that distinguish it from all other kinds of objects. This is
in variables e.g. name, ID and methods (functions or
procedures) used to do a certain operation or calculation. You
can add to or modify them.
• Encapsulation: Encapsulation hides information from
unwanted outside access by attaching that information to only
methods that need access to it. This binds data and operations
tightly together and separates them from external access that
may corrupt them intentionally or unintentionally.
Encapsulation is achieved by declaring variables as Private in a
class- this gives access to data to only member functions of the
class.
• Inheritance: Inheritance is the process by which one
object acquires the properties of another object
• Polymorphism: Polymorphism is a term that describes a
situation where one name of method may refer to different
methods of different implementations. java determines the
proper methods to call at the program’s run time e.g.
Class Book
{
String title;
String publisher;
float price;
setBook(String title) {}
setBook(String title, String
publisher) {}
setBook(String title, String
publisher,float price){}
}

e. What are algorithms: a sequence of


language independent steps which may
be followed to solve a problem

2. Java technology
a. What is java:
• Simple powerful language
• Similar to C++ (both object oriented supporting classes
instantiated from objects / similar variable types e.g int, float /
case sensitive)
• Originated at Sun Microsystems, Inc. in 1991. It was
conceived by James Gosling
• Developed to provide a platform-independent
programming language on any system where a Java™ Virtual
Machine is available e.g. Windows 9x/ME/NT/2000/XP etc.,
MacOS, OS/2, Solaris, LINUX, UNIX and PDAs (Pocket PCs).
b. Applications of java :
• Web based applications – ecommerce (Java applets -
small standalone applications e.g. text editor, calculator - can
run in a Web browser for many platforms, including Windows,
Unix, Mac OS and Linux using a Java Virtual Machine).
The client sends an HTTP request to the web server. A web
server that implements Java Servlet and JavaServer Pages
technology converts the request into an HTTPServletRequest
object. This object is delivered to a web component (There are
two types of web components: Java Servlets and JavaServer
Pages (JSP ) pages. Servlets are Java programming
language classes that dynamically process requests and
construct responses), which can interact with JavaBeans
components or a database to generate dynamic content. The
web component can then generate an HTTPServletResponse or
it can pass the request to another web component. Eventually
a web component generates a HTTPServletResponse object.
The web server converts this object to an HTTP response and
returns it to the client).
• Financial applications (stocks / payroll / banks),
• Gaming applications (racing cars etc.),

• Embedded systems (desktop systems provide a wide


spectrum of technologies to serve a broad range of application
needs, while embedded devices are fitted with just enough
software to handle a specific application.- Microcontroller-Based
Temperature Monitoring and Control / Navigation system using a
GPS receiver / Communications systems for protocol conversion
and VoIP / energy meter reading / air conditioner remote control,
audio player remote control, typing speed indicator, database
application, electronic voting.
• Distributed enterprise applications
• Mobile applications
(cinema repertoire -
browsing currently
displayed movies with
reviews, descriptions,
photos. Repertoire is
updated at user’s request.
Electronic Brochure of
Products/Services-
providing users with
information about your
services or products).

• Image processors: helps developers manipulate image


pixels using Java 2D API. Processing an image is simply a
matter of calculating a new color for each pixel. A platform-
independent application to view, edit and print images on any
system where a Java™ Virtual Machine is available
• Desktop applications e.g. MagicDraw UML, ArgoUML
c. Java versions

• JAVA 1.0 - 1995


• JAVA 2 – 2006 (J2EE(enterprise), J2ME(micro),
J2SE(standard))

d. Features & Advantages of java


• Portable - Platform Independent: Unlike many other
programming languages when Java is compiled, it is not
compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the
web and interpreted by virtual Machine (JVM) on whichever
platform it is being run. When compiled, the code will run in a
similar fashion on any platform. A programmer should be able
to write a program one time, compile it one time, and then be
able to execute it anywhere. As SUN slogans:”Write once, run
anywhere”
• Simple: easy to learn
• Reusable: can use code (classes, objects & methods) all
over again don’t have to rewrite it
• Distributed: With extensive set of routines to handle
TCP/IP protocols like HTTP and FTP java can open and access
the objects across net via URLs
• Robust: Automatic garbage collection is another great
feature of Java with which it prevents inadvertent corruption of
memory by freeing the memory if the object is no longer
needed.Also the concept of Exception Handling allows java to
detect errors during runtime and prevent the program from
crashing suddenly.
• Secure: Java was designed to allow secure execution of
code across network. To make Java secure many of the
features of C and C++ were eliminated. Java does not use
Pointers - Java programs cannot access arbitrary unprotected
addresses in memory.
• High Performance: fast compilation
• Dynamic : interacts with databases & enterprise
information systems EIS
• Multi-Threaded: One of the powerful aspects of the Java
language is that it allows multiple threads of execution to run
concurrently within the same program independently and
continuously e.g. Multiple Java applets can run on the browser
at the same time sharing the CPU time

e. Why use it rather than C/C++


• Platform independent
• Easier – not complex to learn
3. Java code
a. Classes & Objects
• Classes are a blueprints, templates or prototypes from
which objects are created. An object is an instance of a class.
So 2 dogs but one has long tail the other has short but they
both have tails
• Objects are often used to model the real-world objects
that you find in everyday life
• Objects have state (attributes/characteristics) and
behavior. Dogs have state (name, color, breed, hungry) and
behavior (barking, fetching, wagging tail)
• Objects interact with each other by sending messages
E.g. invoice & receipt e.g. lego objects form larger objects
together

b. Methods
• An object stores its state in fields (variables in some
programming languages) and exposes its behavior and
interaction with the outer world through methods (functions in
some programming languages).
• Hiding internal state and requiring all interaction to be
performed through an object's methods is known as data
encapsulation (e.g. when assembling a pc, each object- card,
processor etc.- is a self contained unit, and all you are
interested in is how the units interact with each other not how
each one works alone)
c. How to write Java:
• Enter the program source code in a data file using an
editor e.g. JCreator / IBM Websphere etc.
• Transform the source program into machine language or
Java Bytecode using a compiler
• Return to the editor to correct any errors (or bugs) and
start the cycle again
• Bytecode files, which are very compact, are easily
transported through a distributed system like the Internet.
•The compiled Java code (resulting byte code) will be executed
at run time

Java programs can be written and executed in two ways:

• Stand-alone application (A Java Swing (interface) Application)


• Applet which runs on a web browser (Example: Internet Explorer)

4. Compiler and interpreter


a. What is a compiler & JVM
• In Java, the compiler is called a class compiler. A class
compiler compiles high-level Java code into a set of assembly-
like instructions known as Java bytecodes. The bytecodes are
the machine language of Java's "virtual machine." The virtual
machine idea is central to Java's platform independence. A
virtual machine can be any platform-hardware or software-that
is capable of understanding and executing Java bytecodes.
There are currently three such platforms: Java Virtual
Machines, Just-in-Time Compilers, and Java Processors.
• The Java Virtual Machine (VM) is a piece of software
implemented on top of hardware and operating system that
translates Java bytecodes to the processor's native opcodes as
they are executed. There are many implementations of the
Java VM available, but all of them support the same set of
bytecodes defined in the Java Virtual Machine Specification.
Versions of the Java VM are available for many common
hardware platforms.
• Interpreted languages are portable, but slow. Just-in-
Time (JIT) compilers were invented to speed the execution of
Java programs by speeding up the language translation
process. A JIT compiler is a drop-in replacement for the Java
VM. The only difference is that it keeps a copy of all previously
translated code for potential reuse. That way, the same section
of code never has to be reinterpreted. Only new bytecodes that
have not been previously executed need to be translated. A
typical program with loops and repeated function calls should
execute about 10 times faster under a JIT compiler. That
makes the speed of programs written in Java comparable to
those written in C++.
• To speed the execution of Java bytecodes even further,
Sun Microsystems has announced a line of Java processors.
These are hardware realizations of the Java virtual machine. In
other words, each Java processor is a microprocessor with a
set of opcodes that are identical to the Java bytecode
standard. To eliminate the need for native methods, these
chips will have a set of extended bytecodes for accessing
memory directly. It is reasonable to expect that these so-called
JavaChips will execute Java bytecodes as quickly as any
processor can execute its own assembly language. However,
since the programs themselves will be written in the high-level
Java, it is more realistic to expect performance comparable to
C.

b. What is an interpreter : An interpreter translates high-level


instructions into an intermediate form, which it then executes. In
contrast, a compiler translates high-level instructions directly into
machine language. Compiled programs generally run faster than
interpreted programs. The advantage of an interpreter, however, is
that it does not need to go through the compilation stage during
which machine instructions are generated. This process can be time-
consuming if the program is long. The interpreter, on the other
hand, can immediately execute high-level programs. For this
reason, interpreters are sometimes used during the development of
a program, when a programmer wants to add small sections at a
time and test them quickly.
The disadvantage is that interpreted programs run much slower
than compiled programs. As much as 5-10 times slower as every
line of code has to be re-read, then re-processed

c. JDK (Java Development Kit)


A free software development package from Sun Microsystems that
implements the basic set of tools needed to write, test and debug
Java applications and applets and java compiler to run them. The
JDK contains documentation, examples, installation instructions,
class libraries and packages, and tools. To run java applications you
must install it. After using an editor like JCreator to type your code,
you must save your source code with a .java extension. The name
of the file must be the name of the public class contained in the file.

d. Java API: API stands for “Application Programming Interface”. The


command line arguments used for a program are an API. It is the
set of methods or objects which a programmer can
manipulate. It is The interface (calling conventions) by which an
application program accesses operating system and other services

e. J2EETM Architecture- The Java™ 2 Platform, Enterprise Edition


(J2EE) provides a standard for developing multitier, enterprise
services
Database
Server
• Client tier: In the client tier, Web components, such as
Servlets and JavaServer Pages (JSPs), or standalone Java
applications provide a dynamic interface to the middle tier.
• Middle tier: In the server tier, or middle tier, enterprise
beans and Web Services encapsulate reusable, distributable
business logic for the application. These server-tier
components are contained on a J2EE Application Server, which
provides the platform for these components to perform actions
and store data.
• Enterprise data tier: In the data tier, the enterprise's
data is stored and persisted, typically in a relational database.

J2EE applications are comprised of components, containers, and


services. Components are application-level components.

It consists of the following technologies


• Java Database Connectivity (JDBC) : The JDBC API allows
the java programs to access the database
• Java Naming and Directory Interface (JNDI) : allows the
java applications to access enterprise naming and
directory services
• Enterprise Java Beans (EJB) : a component architecture
for developing and deployment of component-based distributed
applications. EJB components contain server-side business
logic for enterprise applications.
• Web components, such as Servlets and JSPs, provide
dynamic responses to requests from a Web page.
• Java Server Pages (JSP) : Java Server Pages allows the
developers to embed the java code into html pages. It is a
mean by which dynamic content can be generated using the
static HTML pages and the data from the database.
•Java Servlets: Java Servlets are server side components that
provides a powerful mechanism for developing serverside
applications.
Java Programming Language 
Session 2 
Use Case Models
† “Architectural” view of the system viewed by its end-users and the services they
use.
† Key elements in the Use Case model are “actors” and “use cases” and “other
systems” to which it’s connected.
† A use-case is a service, or unit of functionality in the system.
† Use cases are often used as an aid to “requirements specification”.
† It is relatively easy to discuss the correctness of a use-case model with a non-
technical person (e.g., your client),

Example (View Points /Services)

† The viewpoints become “actors”


• Human being
• External computer systems.
† The services become “use-cases”
Case Study
A retail business wishes to automate some of its sales procedures. Preliminary
interviews reveal that there are number of staff roles in the Sales department:
† A salesperson can place orders on behalf of customers and check the status of
these orders.
† A technical salesperson has the same duties, but additionally is able to provide
customers with detailed technical advice (which we would not expect an ordinary
salesperson to be able to do).
† A sales supervisor is a salesperson, with the additional responsibility of creating
new customer accounts and checking their credit-worthiness.
† A despatcher is responsible for collecting the goods ordered from the warehouse,
and packing them for despatch to the customer.
† To assist in this operation the computer system should be able to produce a list
of unpacked orders, and delete the orders from the list that the despatcher has
packed.
† All staff are able to find general details of the products stocked, including stock
levels and locations in the warehouse.
† A re-ordering clerk is responsible for finding out which products are out of stock
in the warehouse, and placing orders for these products from the manufacturers.
† The system should be able to advise the re-order clerk of which products are
`priority' products.
† A stock clerk is responsible for placing items that arrive from manufacturers in
their correct places in the warehouse. To do this the clerk needs to be able to find
the correct warehouse location for each product from the computer system.
† Currently the same person in the business plays the roles of stock clerks
and re-order clerk.
Types of Classes
† Concrete Classes:
„ Classes like 'Book' and 'Member' are physical or concrete classes
„ They correspond to REAL things in the physical world
† Conceptual classes:
„ The classes 'Loan' and 'Return date' are different 'types' of classes.
„ They do not correspond to real, physical entities at all.

Attributes (Variables)
† Attributes are the PROPERTIES of a class; on the whole they are things that can
be measured or observed.
† When a new object is created, an area of the computer's memory is
allocated to store the object.
† Attributes are defined by variables : locations in memory in which values can be
stored
† Variables have a
„ name,
„ type,
„ value
† A variable must be declared before you can use a variable. After declaration,
values can be assigned to it

Types of Variables
† instance variables: (Non-Static Fields) used to define attributes or the state
for a particular object INSTANTIATED from a class.
„ Each instance (object) can have different values for a variable but always
the same type. (Even if all the attributes of two objects are identical, this
does not make the objects identical).
„ Instance variables may be set when an object is created and stay constant
throughout the life of the object, or they may be able to change at will as the
program runs.
† class variables: (Static Fields) this tells the compiler that there is exactly one
copy of this variable in existence. They apply to all that class's instances (and to
the class itself) rather than having different values for each object.
„ Class variables' values are stored in the class itself.
† local variables: are declared and used only inside a method definition or a block.
„ Once the method (or block) finishes executing, the variable definition and its
value cease to exist.

Data Types of Variables


Each variable declaration must have a type, which defines what values that variable can
hold. The variable type can be one of three things:
† One of eight primitive data types
„ They handle integers, floating-point numbers, characters, and boolean values
(true or false).
„ They're called primitive because they're built into the system and are not
actual objects, which makes them more efficient to use :
„ Integer (4):
Type Size Range

byte 8 bits —128 to 127


short 16 bits —32,768 to 32,767
int 32 bits —2,147,483,648 to 2,147,483,647
long 64 bits —9223372036854775808 to 9223372036854775807
„ Floating-point decimals (2):
float (32 bits precision)
double (64 bits precision)
„ Individual characters :
char
„ Boolean type can have one of two values, true or false:
boolean
† The name of a class or interface :
„ variables in Java can also be declared to hold an instance of a particular class
e.g.
String text = "hello"; (as opposed to : “char x = text[1];”)
Font basicFont;
OvalShape myOval;
† An array (explained later)

Declaring variables

† Variable declarations consist of a type and a variable name


† They are most commonly declared at the beginning of the definition before they are
used, e.g.
public static void main (String args[]) {
int myAge;
String myName;
boolean isTired;}
† You can string together variable names with the same type e.g.
int x, y, z;
† You can also give each variable an initial value when you declare it:
int a = 4, b = 5, c = 6;
† Local variables must be given values before they can be used (your Java program
will not compile if you try to use an unassigned local variable).
† Instance and class variable definitions do not have this restriction (their initial
value depends on the type of the variable: null for instances of classes, 0 for
numeric variables, '0' for characters, and false for booleans).
Assigning Values to Variables

Once a variable has been declared, you can assign a value to that variable by using the
assignment operator =:
size = 14;
tooMuchCaffiene = true;
name= “noha”
Variable/Method Names
† choose names that are meaningful - represent the characteristic of the variable or
what the method does
† Variable names in Java can start with a letter, an underscore (_), or a dollar sign
($).
† They cannot start with a number
† Do not use reserved java words e.g. “class”, “public” etc.
† Symbols, such as %, *, @, and so on, are often reserved for operators in Java so
avoid them
† Names in java are case sensitive
† If it’s a complex name the first word is lowercase, but all following words have an
initial uppercase letter e.g.
Button theButton;
long reallyBigNumber;
boolean currentWeatherStateOfPlanetXShortVersion;

Comments
Java has three kinds of comments
† /* and */ surround multiline comments , e.g.
/* I don't know how I wrote this next part; I was working
really late one night and it just sort of appeared.
*/
† Double-slashes (//) can be used for a single line of comment
† comments beginning with /** and ending with */ are used to generate API
documentation from the code. (API) is an interface implemented by a software program
to enable interaction with other software, much in the same way that a user interface
facilitates interaction between humans and computers.

String Literals

String literals consist of a series of characters inside double quotes.


The most used is ‘\n’ which means new line
e.g. "A string with a \n new line"

Methods (operations)
† Operations say what a class does.
† Methods are operations/functions defined inside classes that operate on instances
(objects) of those classes. Java does not have functions (methods) defined outside
classes (as C++ does)
† Message Passing:
„ All of a class's operations are accessible to other classes (Public
Operations)
„ Classes can communicate by invoking EACH OTHERS’ operations.

Method Declaration
† Method definition syntax:
return value type method-name ( parameter1, parameter2, …, parametern){
declarations and statements
}
† A method definition consists of a method header and a method body.
† A method header states the method name and the type of the return value.
† The header may also specify variables called formal parameters which receive
incoming arguments. These formal parameters are used in them method body to
perform the computations.
† The method body consists of a sequence of declarations and statements enclosed
in braces{}
† The method main “public static void main (String args[])” has
„ void as type of return value which means that it does not return a value,
„ method name is main,
„ this method returns a parameter of an array of Strings with any name.
„ static means that the method belongs to the class in which it resides
† Methods that do not return a value must have the reserve word void.
† Static methods operate on a class as a whole (not on specific instances of the
class).
† Keyword public means that it can be accessed from outside the class.

Creating Java Applications


† A Java application consists of one of more classes and can be as large or as small
as you want it to be.
† The jumping-off class for your program needs one thing: a main() method
† When you run your compiled Java class (using the Java interpreter), the main()
method is the first thing that gets called.
Examples

† UML (Universal Modeling Language) is used to model classes


class Customer {
// variables
<variable1>
<variable2>
<variable...>
// methods
<method1>
<method2>
}

e.g. class Book


{
// variables
String title;
int numPages;
String shelfMark;
int daysLate;

// methods for getting the Title, Num of Pages, Shelf mark


String getTitle() { // method implementation }
int getNumPages() { // method implementation }
String getShelfMark() { // method implementation}
Your first Java application

class HelloWorld
{
public static void main (String args[])
{
System.out.println("Hello World!");
}
}

1. This program has two main parts:


a. All the program is enclosed in a class definition—here, a class called HelloWorld.

b. The body of the program (here, just the one line) is contained in a method
(function) called main(). In Java applications, as in a C or C++ program, main() is
the first method (function) that is run when the program is executed
2. Parentheses are used for the beginning and end of any class or method
3. Semicolons end each statement in a method
4. If a statement returns a value , it is called an expression e.g. when you add two
numbers together or test to see whether one value is equal to another
5. A statement is called a block if complex lines surrounded by parentheses e.g. loop,
array, if condition
6. Once you finish typing the program, save the file. Most of the time, Java source files
are named the same name as the class they define, with an extension of .java. This
file should therefore be called HelloWorld.java.
7. Now, let's compile the source file using the Java compiler. In Sun's JDK, the Java
compiler is called javac. The compiler should compile the file without any errors. If
you get errors, go back and make sure that you've typed the program exactly as it
appears
8. When the program compiles without errors, you end up with a file called
HelloWorld.class, in the same directory as your source file. This is your Java bytecode
file. You can then run that bytecode file using the Java interpreter. In the JDK, the
Java interpreter is called simply java
9. If your program was typed and compiled correctly, you should get the string "Hello
World!" printed to your screen as a response
10. You can make another class and instantiate this one from inside it i.e. make an
instance of it which executes: If a class is the general (generic) representation of an
object, an instance is its concrete representation = an object
a. e.g. you might create a class for the user interface element called a button. The
Button class defines the features of a button (its label, its size, its appearance) and
how it behaves (does it need a single click or a double click to activate it, does it
change color when it's clicked, what does it do when it's activated?). Once you define
the Button class, you can then easily create instances of that button—that is, button
objects—that all take on the basic features of the button as defined by the class, but
may have different appearances and behavior based on what you want that
particular button to do. By creating a Button class, you don't have to keep rewriting
the code for each individual button you want to use in your program, and you can
reuse the Button class, by creating instances (objects) of it from inside other classes,
to create different kinds of buttons as you need them .
Second Java Application

class Motorcycle {
String make;
String color;
boolean engineState;

public static void main (String args[]) {


Motorcycle m = new Motorcycle();
m.make = "Yamaha RZ350";
m.color = "yellow";
System.out.println("Calling showAtts...");
m.showAtts();
System.out.println("————");
System.out.println("Starting engine...");
m.startEngine();
System.out.println("————");
System.out.println("Calling showAtts...");
m.showAtts();
System.out.println("————");
System.out.println("Starting engine...");
m.startEngine();
}

void startEngine() {
if (engineState == true)
System.out.println("The engine is already on.");
else {
engineState = true;
System.out.println("The engine is now on.");
}
}

void showAtts() {
System.out.println("This motorcycle is a "
+ color + " " + make);
if (engineState == true)
System.out.println("The engine is on.");
else System.out.println("The engine is off.");
}
}
Answer:
Calling showAtts...
This motorcycle is a yellow Yamaha RZ350
The engine is off.
————
Starting engine...
The engine is now on.
————
Calling showAtts...
This motorcycle is a yellow Yamaha RZ350
The engine is on.
————
Starting engine...
The engine is already on.

† The first line declares the main() method


† Motorcycle m = new Motorcycle(), creates a new instance of the Motorcycle class
and stores a reference to it in the variable m
ƒ P.S. you don't operate directly on classes in Java programs; instead,
you create objects from those classes and then call methods in those
objects. Thus when Java executes the main() method, the class that
holds it is not automatically instantiated when your program runs. You
have to instantiate it in the main() method yourself
† Then set the instance variables for this motorcycle object
† Println – creates a new line for writing
† Then call the showAtts() method / startEngine() method
† All lines are shown in the console of the Application Developer
† The startEngine method tests to see whether the engine is already running (in the
line engineState == true) and, if it is, merely prints a message to that effect. If the
engine isn't already running, it changes the state of the engine to true and then
prints a message.
† == means check that both arguments are equal
† = means make the second argument equal to the first
Accessing and Setting Class and Instance Variables
† To get to the value of an instance variable, you use dot notation
† With dot notation, an instance or class variable name has two parts: the object on
the left side of the dot, and the variable on the right side of the dot
e.g. m.color / m.startEngine()
Calling Methods
† Calling a method in objects is similar to referring to its instance variables: method
calls also use dot notation
† The object whose method you're calling is on the left side of the dot; the name of
the method and its arguments is on the right side of the dot:
e.g. myObject.methodOne(arg1, arg2, arg3);
† all methods must have parentheses after them, even if that method takes no
arguments:
e.g. myObject.methodNoArgs();
Third Java Example: Calling methods in String class

class TestString {
public static void main(String args[]) {
String str = "Now is the winter of our discontent";
System.out.println("The string is: " + str);
System.out.println("Length of this string: " +
str.length());
System.out.println("The character at position 5: " +
str.charAt(5));
System.out.println("The substring from 11 to 17: " +
str.substring(11, 17));
System.out.println("The index of the character d: " +
str.indexOf('d'));
System.out.print("The index of the beginning of the ");
System.out.println("substring \"winter\":" +
str.indexOf("winter"));
System.out.println("The string in upper case: "
+ str.toUpperCase());
}
}

Answer:

The string is: Now is the winter of our discontent


Length of this string: 35
The character at position 5: s
The substring from positions 11 to 17: winter
The index of the character d: 25
The index of the beginning of the substring "winter": 11
The string in upper case: NOW IS THE WINTER OF OUR DISCONTENT

N.B. All spaces are , and the counting starts at position “0”
Fourth Java Example: The TestPoint Class.

import java.awt.Point;

class TestPoint {

public static void main(String args[]) {


Point thePoint = new Point(10,10);

System.out.println("X is " + thePoint.x);


System.out.println("Y is " + thePoint.y);

System.out.println("Setting X to 5.");
thePoint.x = 5;
System.out.println("Setting Y to 15.");
thePoint.y = 15;

System.out.println("X is " + thePoint.x);


System.out.println("Y is " + thePoint.y);
}
}

Answer:

X is 10
Y is 10
Setting X to 5.
Setting Y to 15.
X is 5
Y is 15
SmartSoft
ITWorx
IBM
Link
Orascom
Java Programming Language
Session 3/4
Scope of variables
 Instance Variables (Non-Static Fields): objects store their individual states in
"non-static fields", that is, fields declared without the static keyword. Non-static
fields have values that are unique to each instance of a class (to each object); the
currentSpeed of one bicycle is independent from the currentSpeed of another.

 Class Variables (Static Fields): A class variable is any field declared with the
static modifier; this tells the compiler that there is exactly one copy of this variable
in existence; regardless of how many times the class has been instantiated. A field
defining the number of gears for a bicycle could be marked as static since the same
number of gears will apply to all instances, e.g. static int numGears = 6 (static
field). Additionally, the keyword final could be added to indicate that the number of
gears will never change.

 Local Variables: a method stores its temporary state in local variables, e.g. int
count = 0;). Local variables are only visible to the methods in which they are
declared; they are not accessible from the rest of the class.

N.B. String objects are immutable, which means that once created, their values
cannot be changed e.g. String s = "this is a string";
They are instantiated from the java.lang.String class

Arrays
An array is a container object that holds a fixed number of values of a single type. The
length of an array is established when the array is created. After creation, its length is
fixed.

An array of ten elements

Each item in an array is called an element, and each element is accessed by its numerical
index. Numbering begins with 0. The 9th element, for example, would therefore be
accessed at index 8.
Declaring a Variable to Refer to an Array

Like declarations for variables, an array declaration has two components: the array's
type and the array's name.

 An array's type is written as type[], where type is the data type of the
contained elements;
 the square brackets are special symbols indicating that this variable holds an
array.
 The size of the array is not part of its type (which is why the brackets are
empty).
 The declaration does not actually create an array — it simply tells the
compiler that this variable will hold an array of the specified type.

e.g. byte[] anArrayOfBytes;


boolean[] anArrayOfBooleans;
String[] anArrayOfStrings;
You can also place the square brackets after the array's name:
float anArrayOfFloats[]; // this form is discouraged

Creating, Initializing, and Accessing an Array


1. One way to create an array is with the new operator.
Int[] anArray = new int[10];
It allocates an array with enough memory for 10 integer elements and assigns the array
to the anArray variable.
If this statement were missing, the compiler would print an error, and compilation would
fail:
ArrayDemo.java:4: Variable anArray may not have been initialized.
To assign values to each element of the array:
anArray[0] = 100;
Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + anArray[0]);
2. The shortcut syntax can be used to create and initialize an array:
int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
Here the length of the array is determined by the number of values provided between {
and }.

Example

The following program, ArrayDemo, creates an array of integers, puts some values in it,
and prints each value to standard output.
class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declares an array of integers

anArray = new int[3]; // allocates memory for 3 integers

anArray[0] = 100; // initialize first element


anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.

System.out.println("Element at index 0: " + anArray[0]);


System.out.println("Element at index 1: " + anArray[1]);
System.out.println("Element at index 2: " + anArray[2]);
}
}

Answer:
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300

It’s easier to use one of the looping constructs (for, while, and do-while) to iterate
through each element of the array, rather than write each line individually as shown
above, as will be shown later.

Multi Dimensional Arrays

You can also declare an array of arrays (also known as a multidimensional array) by
using two or more sets of square brackets, such as String[][] names. Each element,
therefore, must be accessed by a corresponding number of index values.

In the Java programming language, a multidimensional array is simply an array whose


components are themselves arrays. A consequence of this is that the rows are allowed to
vary in length, as shown in the following MultiDimArrayDemo program:

class MultiDimArrayDemo
{
public static void main(String[] args) {
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}};
System.out.println(names[0][0] + names[1][0]);
System.out.println(names[0][2] + names[1][1]);
System.out.println(names.length);
}
}
Answer:
Mr. Smith
Ms. Jones

To determine the size of any array use the built-in length property:

System.out.println(anArray.length);

N.B.
- length of single array gives number of elements
- length of multi dimensional array gives number of single arrays
- string.length() array.length

Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data
from one array into another:
public static void arraycopy (Object src,
int srcPos,
Object dest,
int destPos,
int length)
The two Object arguments specify the array to copy from and the array to copy to. The
three int arguments specify the starting position in the source array, the starting position
in the destination array, and the number of array elements to copy.

The following program, ArrayCopyDemo, declares an array of char elements, spelling the
word "decaffeinated". It uses arraycopy to copy a subsequence of array components into
a second array:

class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];

System.arraycopy(copyFrom, 2, copyTo, 0, 7);


System.out.println(new String(copyTo));
}
}

Answer:

Caffein.
(mention VECTORS)
Operators
Operators are special symbols that perform specific operations on one, two, or three
operands, and then return a result.

Assignment Operator
The simple assignment operator "="
 assigns the value on its right to the operand on its left e.g.
int speed = 0;
 can also be used on objects to assign object references e.g.
Point originOne = new Point(23, 94);

Arithmetic Operators
+ addition operator (also used for String concatenation)
- subtraction operator
* multiplication operator
/ division operator
% remainder operator: divides one operand by another and returns the
remainder as its result
e.g.

class ArithmeticDemo {
public static void main (String[] args){
int result = 1 + 2; // result is now 3
result = result - 1; // result is now 2
result = result * 2; // result is now 4
result = result / 2; // result is now 2
result+=8; // result is now 10
result = result % 7; // result is now 3
System.out.println(result);
}
}

 The + operator can also be used for concatenating (joining) two strings together
e.g.
class ConcatDemo {
public static void main(String[] args){
String firstString = "This is";
String secondString = " a concatenated string.";
String thirdString = firstString+secondString;
System.out.println(thirdString);
}
}
 You can also combine the arithmetic operators with the assignment operator to
create compound assignments. e.g.
result+=1 is the same as result=result+1

Expression Meaning

x += y x=x+y
x —= y x=x—y
x *= y x=x*y
x /= y x=x/y

The Unary Operators


+ Unary plus operator; indicates positive value (numbers are positive without this,
however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a boolean
e.g.
class UnaryDemo {
public static void main(String[] args){
int result = +1; // result is now 1
result--; // result is now 0
result++; // result is now 1
result = -result; // result is now -1
boolean success = false;
System.out.println(success); // false
System.out.println(!success); // true
}
}

N.B.
 result = +1 is different from result+=1
 The increment/decrement operators can be applied before (prefix) or after (postfix)
the operand. The code result++; and ++result; will both end in result being
incremented by one. The only difference is that the prefix version (++result)
evaluates to the incremented value, whereas the postfix version
(result++) evaluates to the original value.
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
System.out.println(i); // "4"
++i;
System.out.println(i); // "5"
System.out.println(i++); // "5"
System.out.println(++i); // "7"
System.out.println(i); // "7"
}
}

The Equality and Relational Operators


The equality and relational operators determine if one operand is greater than, less than,
equal to, or not equal to another operand.
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
e.g.

class ComparisonDemo {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
if(value1 == value2) System.out.println("value1 == value2");
if(value1 != value2) System.out.println("value1 != value2");
if(value1 > value2) System.out.println("value1 > value2");
if(value1 < value2) System.out.println("value1 < value2");
if(value1 <= value2) System.out.println("value1 <= value2");
}
}
Answer:
value1 != value2
value1 < value2
value1 <= value2
The Conditional Operators
 The && and || operators perform Conditional-AND and Conditional-OR operations
on two boolean expressions.
class ConditionalDemo1 {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
if((value1 == 1) && (value2 == 2))
System.out.println("value1 is 1 AND value2 is 2");
if((value1 == 1) || (value2 == 1)) System.out.println("value1
is 1 OR value2 is 1");
}
}

 Another conditional operator is ?. It can be thought of as shorthand for an if-then-


else statement. Also known as the ternary operator because it uses three operands
to be read as follows:
"If someCondition is true, assign the value of value1 to result. Otherwise,
assign the value of value2 to result."
e.g.
class ConditionalDemo2 {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;
System.out.println(result);
}
}
Operator Precedence
 Operators with higher precedence are evaluated before operators with relatively
lower precedence.
 Operators on the same line have equal precedence. When operators of equal
precedence appear in the same expression, a rule must govern which is evaluated
first.
 See table below
Operator Precedence
Operators Precedence

postfix expr++ expr--

unary ++expr --expr +expr -expr ~ !

multiplicative * / %

additive + -

relational < > <= >= instanceof

equality == !=

logical AND &&

logical OR ||

ternary ? :

assignment = += -= *= /= ^=

Expressions, Statements, and Blocks

 Semicolons end each statement in a method e.g.

aValue = 8933.234; // assignment statement


aValue++; // increment statement
System.out.println("Hello World!"); // method invocation statement
Bicycle myBike = new Bicycle(); // object creation statement
double aValue = 8933.234; //declaration statement

 If a statement returns a value , it is called an expression e.g. when you add two
numbers together or test to see whether one value is equal to another
 A statement is called a block if complex lines surrounded by parentheses e.g. loop,
array, if condition

N.B. x + y / 100 // ambiguous


x + (y / 100) // unambiguous, recommended
When writing compound expressions, be explicit and indicate with
parentheses which operators should be evaluated first. This practice makes
code easier to read and to maintain.
N.B.
Bitwise Operators
There are variables that represent a 1 bit value only. These do not get assigned a
number or character (which consist of a byte=8 bits not an individual bit). This is used in
―systems programming‖ to represent ―on=1‖ and ―off=0‖.

Operators that deal with bits are less commonly used. For example:

"~"
This inverts a bit pattern; making every "0" a "1" and every "1" a "0". For example, a
byte contains 8 bits "00000000" would change its pattern to "11111111".

“|” “&”
The single OR and AND operators work on bits in the following way:
bit 1 bit 2 OR (|) AND (&) XOR (^)
0 0 0 0 0
1 0 1 0 1
0 1 1 0 1
1 1 1 1 0

―|‖ Bitwise OR returns one in all cases except where the corresponding bits of both
operands are zero. The resulting bit pattern is the "set" (1 or true) bits of any of the two
operands. This property can be used to "set" or "turn on" a "flag" (bit set to one) in the
―flags‖ variable regardless of whether that flag was set previously or not.
// To set or turn on a flag bit(s)
flags = flags | MASK;

―&‖Bitwise AND sets a bit to 1 if and only if both of the corresponding bits in its operands
are 1, and to 0 if the bits differ or both are 0. In other words, a one ANDed with any bit
is that bit and a zero ANDed with any bit is zero. This operator can be used to check the
state of a flag in e.g. ―flags‖ variable. When you AND the ―flags‖ variable with the
―MASK‖, all zeroes in the ―MASK‖ will return zero for the corresponding position in ―flags‖
and all ones in the ―MASK‖ will return whatever the corresponding bit is set to in the
―flags‖ variable.
// To check the state of a flag bit(s)
if (flags & MASK) == MASK) { N.B. we can’t say:
// flag is set or turned on if (flags & 1) == 1)
... because 1 here is a character
} not a bit
else {
//flag is not set or is turned off
...
}
―&‖ can also be used, RARELY, as a logical operator but this single
ampersand always evaluates both arguments whereas the double
ampersand ―&&‖ will only evaluate the second argument if the first
argument is true – thus it’s faster.

Flag refers to one or more bits that are used to store a binary value or code
that has an assigned meaning.
 One common use of flags is to mark or designate data structures for
future processing.
 Within microprocessors and other logic devices, flags are commonly
used to control or indicate the intermediate or final state or outcome of
different operations. Microprocessors typically have, for example, a
status register that is composed of such flags, and the flags are used to
indicate various post-operation conditions, such as when there has
been an arithmetic overflow.
The Type Comparison Operator
The instanceof operator compares an object to a specified type. You can use it to test if
an object is
 an instance of a class,
 an instance of a subclass, or
 an instance of a class that implements a particular interface.

class InstanceofDemo {
public static void main(String[] args) {
Parent obj1 = new Parent();
Parent obj2 = new Child();

System.out.println("obj1 instanceof Parent: " + (obj1 instanceof


Parent));
System.out.println("obj1 instanceof Child: " + (obj1 instanceof
Child));
System.out.println("obj1 instanceof MyInterface: " + (obj1
instanceof MyInterface));
System.out.println("obj2 instanceof Parent: " + (obj2 instanceof
Parent));
System.out.println("obj2 instanceof Child: " + (obj2 instanceof
Child));
System.out.println("obj2 instanceof MyInterface: " + (obj2
instanceof MyInterface));
}
}

class Parent{}

class Child extends Parent implements MyInterface{}

interface MyInterface{}

Answer:
obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true
Control Flow Statements

The statements inside source files are generally executed from top to bottom, in the
order that they appear. Control flow statements break up the flow of execution by
enabling the program to conditionally execute particular blocks of code using:

 decision-making statements (if-then, if-then-else, switch),


 looping statements (for, while, do-while),
 branching statements (break, continue, return)

IF-THEN-ELSE Statement
 It executes a certain section of code only if a particular condition occurs.
E.g.

The Bicycle class could allow the brakes to decrease the bicycle's speed only if the
bicycle is already in motion. If this test evaluates to false (meaning that the
bicycle is not in motion), control jumps to the end of the if-then statement

void applyBrakes(){
if (isMoving) { // the "if" clause: bicycle must be moving
currentSpeed--; // the "then" clause: decrease current speed
}
}

N.B. it is better to include the opening and closing braces for the ―then‖ clause

 The if-then-else statement provides a secondary path of execution when an "if"


clause evaluates to false.
E.g.
void applyBrakes(){
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}

e.g. The following program, IfElseDemo, assigns a grade based on the value of a
test score: an A for a score of 90% or above, a B for a score of 80% or above, and
so on:
class IfElseDemo
{
public static void main(String[] args)
{
int testscore = 76;
char grade;

if (testscore >= 90)


{
grade = 'A';
}
else if (testscore >= 80)
{
grade = 'B';
}
else if (testscore >= 70)
{
grade = 'C';
}
else if (testscore >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}

Answer:
Grade = C

N.B.
The value of testscore can satisfy more than one expression in the compound
statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the
appropriate statements are executed (grade = 'C';) and the remaining
conditions are not evaluated.
If we don’t use ―else if‖ and only ―if‖ , the program will run all feasible conditions
Is the character a digit ?

It is possible to test a character to see if it is a digit by checking if it is within a range of


characters within the character set. For example, in JavaScript you can test to see if a
character is a digit this way:

if (chr >= "0" && chr <= "9")…… alert("It is a digit!")

class IfInteger {
static int x=5;
static String y="not number";

public static void main(String[] args)


{

IfInteger newOne= new IfInteger();

if(x>=0 && x<=9) {


System.out.println(x);
}
else {
System.out.println(y);
}
}
}

The SWITCH Statement


This is similar in function to the IF-THEN.
An if-then-else statement can be used to make decisions based on ranges of values or
conditions, whereas a switch statement can make decisions based only on a single
integer or enumerated value

e.g. The following program, SwitchDemo, declares an int named month whose value
represents a month out of the year. The program displays the name of the month, based
on the value of month, using the switch statement.
class SwitchDemo
{
public static void main(String[] args)
{
int month = 8;
switch (month)
{
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}
}
}

Answer:

August

N.B. Each break statement terminates the enclosing switch statement. Control flow
continues with the first statement following the switch block. The break statements are
necessary because without an explicit break, control will flow sequentially through
subsequent case statements.

The same function could also be implemented with if-then-else statements:

int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
. . . // and so on
class SwitchDemo2 {
public static void main(String[] args) {

int month = 2;
int year = 2000;
int numDays = 0;

switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = " + numDays);
}
}

Answer:

Number of Days = 29
The WHILE and DO-WHILE Statements

 The while statement continually executes a block of statements while a particular


condition is true. Its syntax can be expressed as:
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If
the expression evaluates to true, the while statement executes the statement(s) in
the while block. The while statement continues testing the expression and
executing its block until the expression evaluates to false.
e.g.
class WhileDemo
{
public static void main(String[] args)
{
int count = 1;
while (count < 11)
{
System.out.println("Count is: " + count);
count++;
}
}
}

 The difference between do-while and while is that do-while evaluates its
expression at the bottom of the loop instead of the top. Therefore, the statements
within the do block are always executed at least once:

do {
statement(s)
} while (expression);
e.g.
class DoWhileDemo
{
public static void main(String[] args)
{
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
}
while (count < 11);
}
}
The FOR Statement
 The FOR statement is called "for loop" because it repeatedly loops until
a particular condition is satisfied. The general form of the FOR
statement is as follows:
for (initialization; termination; increment) {
statement(s)
}

 The initialization expression initializes the loop; it's executed once, as the loop
begins.
 When the termination expression evaluates to false, the loop terminates.
 The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.
 GO BACK TO “class ArrayCopyDemo” EXERCISE
e.g.
class ForDemo
{
public static void main(String[] args)
{
for(int i=1; i<6; i++)
{
System.out.println("Count is: " + i);
}
}
}

Answer:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

 the code declares a local variable within the initialization expression. The scope of
this variable extends from its declaration to the end of the block governed by the
for statement, so it can be used in the termination and increment expressions as
well
 The names i, j, and k are often used to control for loops; declaring them within the
initialization expression limits their life span and reduces errors

 The FOR statement has another form designed for iteration through arrays referred to
as the enhanced FOR statement, and makes loops more compact.

e.g. the following array, holds the numbers 1 through 10:


int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, EnhancedForDemo, uses the enhanced for to loop through the
array:

class EnhancedForDemo
{
public static void main(String[] args)
{
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item=0; item<numbers.length; item++)
System.out.println("Item in array is: " + numbers[item]);
}
}

In this example, the variable item holds the current value from the numbers array. The
output from this program is the same as before:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

 This form of the for statement is recommended instead of the general form
whenever possible – this way the number of iterations is dynamic.

The BREAK Statement

The break statement has two forms: labeled and unlabeled.

 An unlabeled break can be used to terminate a switch, for, while, or do-while


loop.
 We don’t need to break an “IF” statement because it already contains
choices

e.g. This program searches for the number 12 in an array. The break statement, shown
in boldface, terminates the for loop when that value is found. Control flow then transfers
to the print statement at the end of the program.
class BreakDemo
{
public static void main(String[] args)
{
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;

for (i = 0; i < arrayOfInts.length; i++)


{
if (arrayOfInts[i] == searchfor)
{
foundIt = true;
break;
}
}

if (foundIt)
{
System.out.println("Found " + searchfor + " at index " + i);
}
else
{
System.out.println(searchfor + " not in the array");
}

}
}

Answer:
Found 12 at index 4

 a labeled break terminates an outer statement.

e.g. The following program, BreakWithLabelDemo, is similar to the previous program,


but uses nested for loops to search for a value in a two-dimensional array. When the
value is found, a labeled break terminates the outer for loop (labeled "search"):
DRAW ALGORITHM:

class BreakWithLabelDemo {
public static void main(String[] args) {

int[][] arrayOfInts = { { 32, 87, 3, 589 },


{ 12, 1076, 2000, 8 } };
int searchfor = 12;

int i;
int j = 0;
boolean foundIt = false;

search:
for (i = 0; i < arrayOfInts.length; i++)
{
for (j = 0; j < arrayOfInts[i].length; j++)
{
if (arrayOfInts[i][j] == searchfor)
{
foundIt = true;
break search;
}
}
}

if (foundIt) {
System.out.println("Found " + searchfor +
" at " + i + ", " + j);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}

Answer:

Found 12 at 1, 0

N.B. It stores values of ―i‖ and ―j‖ just before the break. They are seen by the fnal ―if‖
statement because they were declared outside the ―search‖ block.
The CONTINUE Statement

The continue statement skips the current iteration of a for, while , or do-while loop.

 The unlabeled continue skips to the end of the innermost loop's body and
evaluates the boolean expression that controls the loop.
e.g. The following program, ContinueDemo , steps through a String, counting the
occurences of the letter "p". If the current character is not a p, the continue statement
skips the rest of the loop and proceeds to the next character. If it is a "p", the program
increments the letter count.

class ContinueDemo {
public static void main(String[] args) {

String searchMe = "peter piper picked a peck of pickled


peppers";
int max = searchMe.length();
int numPs = 0;

for (int i = 0; i < max; i++) {


//interested only in p's
if (searchMe.charAt(i) != 'p')
continue;

//process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}

On removing the continue statement and recompiling, the count will be wrong,
saying that it found 35 p's instead of 9

Answer:
Found 9 p's in the string

 A labeled continue statement skips the current iteration of an outer loop marked
with the given label

e.g. The following program, ContinueWithLabelDemo, uses nested loops to search for a
substring within another string. Two nested loops are required: one to iterate over the
substring and one to iterate over the string being searched. The following program,
ContinueWithLabelDemo, uses the labeled form of continue to skip an iteration in the
outer loop.
public static void main(String[] args)
{
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() - substring.length();

test:
for (int i = 0; i <= max; i++)
{
int n = substring.length();
int k = 0;

while (n-- != 0)
{

if (searchMe.charAt(i)!= substring.charAt(k))
{
continue test;
}

i++;
k++;

}
foundIt = true;
break test;
}

System.out.println(foundIt ? "Found it":"Didn't find it");


}
}
Answer:
Found it

The RETURN Statement


The return statement exits from the current method, and control flow returns to where
the method was invoked. The return statement has two forms: one that returns a value,
and one that doesn't. To return a value, simply put the value (or an expression that
calculates the value) after the return keyword.
return ++count;
The data type of the returned value must match the type of the method's declared return
value. When a method is declared void, use the form of return that doesn't return a
value.
return;
Java Programming Language
Session 5
Ex.: Arrange a set of numbers in order

Return Statement
class ReturnClass
{
static boolean t = true;

public static void main(String args[])


{
method1();
int z= method2(10,20);
System.out.println(z);
}

static void method1()


{
System.out.println("void return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}

static int method2(int x, int y)


{
return (x+y); // return to caller
}
}

Advanced FOR loop


public class Main
{
public static void main(String[] args)
{
int[] numbers = {1,2,3,4,5,6,7,8,9,10};

/*for each "int" object in "numbers".Here the variable ―i‖ is used to point to the current
instance of Employee in the collection. Because of the "for each" wording, the
enhanced-for construct is also referred to as the for-each construct.*/

for (int i : numbers)


{
System.out.println("The item is: " + item);
}
}}

Vectors

import java.util.*;
public class VectorDemo{
public static void main(String[] args){

Vector<Object> vector = new Vector<Object>();

int int1 = 10;


Integer int2 = new Integer(20);
String str = "more numbers";

vector.addElement(int1); vector.add(int2);
vector.add(str);
vector.add(2, new Integer(30)); // addElement cannot be used to put object in
specific place in vector

System.out.println("the elements of vector: " + vector);


System.out.println("The size of vector are: " + vector.size());
System.out.println("The elements at position 2 is: " +
vector.elementAt(2));
System.out.println("The first element of vector is: " +
vector.firstElement());
System.out.println("The last element of vector is: " +
vector.lastElement());
vector.removeElementAt(2);

}
}

A class hierarchy
Each class has a superclass (above it in the hierarchy), and each class can have one
or more subclass (below it in the hierarchy)
 Subclasses inherit all the methods and variables from their superclasses further
up in the hierarchy - subclassing
 Each class farther down in the hierarchy adds more information and is more
tailored to a specific purpose
 At the top of the Java class hierarchy is the class Object; all classes inherit from
this one superclass.
 Using subclassing, you only need to define the differences between your class
and its parent

Creating a Class Hierarchy

 factor out information common to multiple classes in superclasses, and then


reuse that superclass's information over and over in subclasses e.g.

Vehicle

Engine Person
powered powered
vehicle vehicle

Two wheeled Four wheeled Bicycle

Motorcycle Scooter Car Truck

Single and Multiple Inheritance

 Single inheritance means that each Java class can have only one superclass
 In C++, classes can have more than one superclass, and they inherit combined
variables and methods from all those classes. This is called multiple inheritance.

Interface

 An interface is a collection of method names, without actual definitions


 Although a Java class can have only one superclass (due to single inheritance),
that class can also implement any number of interfaces.
 By implementing an interface, a class provides method implementations
(definitions) for the method names defined by the interface
 If two different classes implement the same interface, they can both respond to
the same method calls (as defined by that interface), although what each class
actually does in response to those method calls may be very different.

Packages & Importing


 Packages in Java are a way of grouping together related classes and interfaces
 The class libraries in the Java Developer's Kit are contained in a package called
java
 The classes in the java package are guaranteed to be available in any Java
implementation
 The java package itself contains other packages for classes that define
o the language itself,
o the input and output classes,
o some basic networking,
o and the window toolkit functions.
 By default, Java classes have access to only the classes in java.lang (the base
language package inside the java package). To use classes from any other
package,
o refer to them explicitly by package name e.g.
“ public class HelloAgainApplet extends java.applet.Applet {} “
o import them in source file e.g.
“ import java.awt.Graphics; “
 E.g., the Color class, which is contained in the awt package (Abstract Windowing
Toolkit). The awt package is inside the java package: java.awt.Color.

 class packages that are part of the Java class library:

 java.lang: Classes that apply to the language itself, which includes the Object
class, the String class, and the System class. It also contains the special classes
for the primitive types (Integer, Character, Float, and so on).
 java.util: Utility classes, such as Date, as well as simple collection classes, such
as Vector and Hashtable.
N.B. a general subsequent level of classes can be imported by “*”, but
not classes inside a subsequent level of packages e.g.
java.util.* OR java.util.Vector - imports the Vector class
java.util.regex.* OR java.util.regex.Matcher - imports Matcher class
 java.io: Input and output classes for writing to and reading from streams (such
as standard input and output) and for handling files.
 java.net: Classes for networking support, including Socket and URL (a class to
represent references to documents on the World Wide Web).
 java.awt: (the Abstract Window Toolkit): Classes to implement a graphical user
interface, including classes for Window, Menu, Button, Font, CheckBox, and so
on. This package also includes classes for processing images (in the
java.awt.Image package).
 java.applet: Classes to implement Java applets, including the Applet class itself,
as well as the AudioClip interface
Defining Classes
 to define a normal class
class MyClassName {
...
}

 to define subclass of another class, use extends to indicate the superclass


of this class:
class MyClassName extends MySuperClassName {
...}

 to implement a specific interface, use implements to refer to that interface:


class MyRunnableClassName implements Runnable {
...
}

Casting and Converting Objects and Primitive Types


You may have a value stored somewhere that is the wrong type or you want to
change it for a reason.

 Casting is a mechanism of converting the type of an object or primitive


type into another type.
 The result of a cast is a new reference or value
 casting does not affect the original object or value
There are three forms of casts:

1. Casting between primitive types: int to float

2. Casting between object types: an instance of a class to an instance of another


class

3. Converting primitive types to objects and then extracting primitive values back
out of those objects

Casting Primitive Types


 Casting between primitive types most commonly occurs with the numeric types;
boolean values cannot be cast to any other primitive type.
 if the type you are casting to is "larger" than the type of the value you're
converting e.g. int to long, you may not have to use an explicit cast - no loss of
information occurs (e.g. You can treat a byte or a character as an int, anything
as a double etc.)
 To convert a large value to smaller type, you must use an explicit cast, because
converting that value may result in a loss of precision :
(typename) value
 typename is the name of the type you're converting to (short, int,
float)
 value is an expression that results in the value you want to convert
e.g. int a= (int) (x / y);
e.g. char c = (char)numericValue;

Casting Objects
Instances of classes can also be cast to instances of other classes, with one restriction:
the class of the object you're casting and the class you're casting it to must be related
by inheritance; that is, you can cast an object only to an instance of its class's sub- or
superclass—not to any random class.

(classname) object
e.g.
GreenApple a= new GreenApple();
Apple a2;
a2 = (Apple) a;

N.B. Casting an object to an instance of one of that object's superclasses loses the
information the original subclass provided

N.B. In addition to casting objects to classes, you can also cast objects to interfaces—
but only if that object's class or one of its superclasses actually implements that
interface. Casting an object to an interface then enables you to call one of that
interface's methods even if that object's class does not directly implement that
interface.

Changing to and from STRING


int to string: int num = 1; String aString = Integer.toString(num);
String to int: String s = "78"; int aInt = Integer.parseInt(s);
double to string: double num = 1; String aString = Double.toString(num);
String to double: String s = "78"; double db = Double.parseDouble(s);
Float to string: float num = 1; String aString = Float.toString(num);
String to float: string s= “1” float f = Float.valueOf(s).floatValue();
Char to String: char c = “a” String.valueOf(c);
String to char: String s= “hi” char c = s.charAt(0);

Constants
A constant variable or constant is a variable whose value never changes (Constants
are useful for defining shared values for all the methods of an object)

To declare a constant:
 use the final keyword before the variable declaration
 include an initial value for that variable:
e.g. final float pi = 3.141592;

Class Variables (Static Fields): A class variable is any field declared with the static
modifier; this tells the compiler that there is exactly one copy of this variable in
existence; regardless of how many times the class has been instantiated. Additionally,
the keyword final could be added to indicate that it will never change.

e.g. static final int maxObjects = 10;

The THIS Keyword


THIS refers to the current object. It can be used in dot notation to refer to the object's
instance variables, as an argument to a method, as the return value for the current
method etc.

e.g. t = this.x // the x instance variable for this object


this.myMethod(this) // call the mymethod method, defined in
// this class, and pass to it the current object
return this; // return the current object

Although sometimes it can be omitted depending on whether there are no variables


with the same name declared in the local method

e.g.
t=x // the x instance variable for this object
myMethod(this) // call the myMethod method, defined in this class
class Student
{
String stName;
int stAge;
String stAddress;

Method1(String stName, int stAge, String stAddress)


{
this.stName = stName;
this.stAge = stAge;
this.stAddress = stAddress;
}
}
Variable Scope
On referring to a variable within your method definitions, Java checks for its definition:
 first in the current block
 then in the current method definition (local variable)
 then as an instance or class variable in the current class
 finally, in each superclass
e.g.

class ScopeTest {
int test = 10;
void printTest () {
int test = 20;
System.out.println("test = " + test);
}
}
Because the local variable hides the instance variable, the println() method will print
that test is 20
You can get around this particular problem by using “this.test” to refer to the
instance variable, and just “test” to refer to the local variable

Calling Methods

 The object whose method you're calling is on the left side of the dot; the name of
the method and its arguments is on the right side of the dot:
e.g. calling some methods defined in the String class
str.length() / str.charAt(5)

Method Definition
Method definitions have four basic parts:
 The name of the method
 The type of object or primitive type the method returns
 A list of parameters
 The body of the method
Method signature is a combination of
 the name of the method,
 the type of object or base type this method returns, and
 a list of parameters.

returntype methodname(type1 arg1, type2 arg2, type3 arg3..) {...}

returntype is the type of the of the value this method returns. It can be:
 one of the primitive types,
 a class name, or
 void if the method does not return a value at all.
 if this method returns an array object, the array brackets can go either after the
return type or after the parameter list

int[] makeRange(int lower, int upper) {...}

 If the method has a return type (not declared to return void), somewhere inside
the body of the method you need to return a value. Use the return keyword to
do this

Parameter list is a set of variable declarations, separated by commas, inside


parentheses. These parameters become local variables in the body of the method,
whose values are the objects or values of primitives passed in when the method is
called

e.g.
class RangeClass {

int[] makeRange(int lower, int upper)


{
int arr[] = new int[ (upper - lower) + 1 ]; // works for any 2
values not just 1 and 10
for (int i = 0; i < arr.length; i++) {
arr[i] = lower++;
}
return arr;
}

public static void main(String arg[]) {


int theArray[];
RangeClass theRange = new RangeClass();
theArray = theRange.makeRange(1, 10);
/*it can work without creating the object and just writing name of method,
but this is good practice if in different class*/
System.out.print("The array: [ ");
for (int i = 0; i < theArray.length; i++) {
System.out.print(theArray[i] + " ");
}
System.out.println("]");
}
}
Answer:

The array: [ 1 2 3 4 5 6 7 8 9 10 ]

The main() method in this class tests the makeRange() method by creating a range
where the lower and upper boundaries of the range are 1 and 10, and then uses a for
loop to print the values of the new array.

Passing Arguments & Arrays to Methods


When you call a method with object parameters, the variables you pass into the body
of the method are passed by reference, which means that whatever you do to those
objects inside the method affects the original objects as well. This includes arrays and
all the objects that arrays contain; when you pass an array into a method and modify
its contents, the original array is affected and changed.

e.g.
The following class includes a method called OneToZero() which does two things:
 It counts the number of ones in the array and returns that value.
 If it finds a one, it substitutes a zero in its place in the array.
the main() method for the PassByReference class tests the onetoZero() method
class PassByReference {
public static void main (String arg[]) {
int arr[] = { 1, 3, 4, 5, 1, 1, 7 };
PassByReference test = new PassByReference();

System.out.print("Values of the array: [ ");


for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("]");

int numOnes = test.onetoZero(arr);


System.out.println("Number of Ones = " + numOnes);
System.out.print("New values of the array: [ ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("]");
}

int onetoZero(int arg[]) {


int count = 0;

for (int i = 0; i < arg.length; i++) {


if (arg[i] == 1) {
count++;
arg[i] = 0;
}
}
return count;
}
}
Answer:
Values of the array: [ 1 3 4 5 1 1 7 ]
Number of Ones = 3
New values of the array: [ 0 3 4 5 0 0 7 ]

Class Methods
 Like class and instance variables, there are class and instance methods
 Class methods are available to any instance of the class itself and can be made
available to other classes – these are general utility methods and do not directly
affect an instance of that class
e.g. the Java class libraries include a class called Math containing mathematical
methods:
float root = Math.sqrt(453.0);
System.out.print("The larger of x and y is " + Math.max(x, y));
 To define class methods, use the “static” keyword in front of the method
definition, just as you would create a class variable.
e.g. static int max(int arg1, int arg2) { ... }

 Some class methods convert to and from primitive types.


e.g. the “parseInt()” class method in the Integer class takes a string and returns
the value of that string as an integer
int count = Integer.parseInt(x);
e.g. an example to input 2 numbers from the user as strings, then convert them to
numbers, add them and output the result

import javax.swing.JOptionPane;

public class InputNumbers {

public static void main(String[] args) {


String x=JOptionPane.showInputDialog(null,"Please enter a
number?","Adding Numbers",
JOptionPane.QUESTION_MESSAGE);

String y=JOptionPane.showInputDialog(null,"Please enter another


number?","Adding Numbers",
JOptionPane.QUESTION_MESSAGE);

int numberx = Integer.parseInt(x);


int numbery = Integer.parseInt(y);
int answer= numberx+numbery;

JOptionPane.showMessageDialog(null, "The total is "+answer,


"Answer", JOptionPane.INFORMATION_MESSAGE);
}
}
Overloading Methods
This is, creating methods with different signatures and definitions but with the same
name.
 When you call a method in an object, Java matches up the method name and
the number and type of arguments to choose which method definition to
execute
 To do it create several different method definitions in your class, all with the
same name, but with
 Different parameter lists (either in number or type of arguments)
 NOT different return types of the methods or names of parameters
e.g.

import java.awt.Point;
class MyRect {
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = 0;
MyRect buildRect(int x1, int y1, int x2, int y2)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
return this;
}

MyRect buildRect(Point topLeft, Point bottomRight)


{
x1 = topLeft.x;
y1 = topLeft.y;
x2 = bottomRight.x;
y2 = bottomRight.y;
return this;
}

MyRect buildRect(Point topLeft, int w, int h) {


x1 = topLeft.x;
y1 = topLeft.y;
x2 = (x1 + w);
y2 = (y1 + h);
return this;
}

void printRect(){
System.out.print("MyRect: <" + x1 + ", " + y1);
System.out.println(", " + x2 + ", " + y2 + ">");
}
public static void main(String args[]) {
MyRect rect = new MyRect();
System.out.println("Calling buildRect with coordinates 25,25 50,50:");
rect.buildRect(25, 25, 50, 50);
rect.printRect();
System.out.println("—————");
System.out.println("Calling buildRect w/points (10,10), (20,20):");
rect.buildRect(new Point(10,10), new Point(20,20));
rect.printRect();
System.out.println("—————");
System.out.print("Calling buildRect w/1 point (10,10),");
System.out.println(" width (50) and height (50)");
rect.buildRect(new Point(10,10), 50, 50);
rect.printRect();
System.out.println("—————");
}
}

Answer:
Calling buildRect with coordinates 25,25 50,50:
MyRect: <25, 25, 50, 50>
—————
Calling buildRect w/points (10,10), (20,20):
MyRect: <10, 10, 20, 20>
—————
Calling buildRect w/1 point (10,10), width (50) and height (50)
MyRect: <10, 10, 60, 60>

All the buildRect() methods work based on the arguments with which they are called
Java Programming Language
Session 6
Revision: Class Declaration
class MyClass {

//field, constructor, and method declarations

class declarations include these components in order:

1. Modifiers e.g. public, private (explained later)


2. Class name, with the initial letter capitalized by convention.
3. The name of the class's parent -superclass, preceded by the keyword extends. (A
class can inherit only one superclass)
4. A comma-separated list of interfaces implemented by the class, preceded by the
keyword implements. (A class can implement more than one interface)
5. The class body, surrounded by braces, {} containing:
 declarations for the fields that provide the state of the class and its objects,
 constructors for initializing new objects,
 methods to implement the behavior of the class and its objects

Access Modifiers (Controlling Access to Members of a Class)

Access modifiers determine whether other classes can use a particular field or invoke a
particular method:

 Public: A class declared with the modifier public, is visible to all classes everywhere
inside and outside its package. The public field or method is accessible from all
classes.
 No modifier (package private): If a class has no modifier (the default, also
known as package-private), is visible only within its own package
 Private: specifies that the member (field / method ) can only be accessed in its
own class. A standard design strategy is to make all fields private and provide public getter
methods for them.
N.B. a class can only use public or package private (no modifier). Private cannot be
used for classes and Interfaces. It also cannot be used for fields and methods within an
interface.
 Protected: specifies that the member can only be accessed within its own package
(as with package-private) and, in addition, by a subclass of its class in another
package
Access Levels
Class(access Package(classes in the same Subclass (of the class — World (all classes
Modifier to its package as the class have declared outside this package have access to the
members) access to the member) — have access to the member) member)
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Private
protected Y N Y N

Tips:

 Unless an instance variable is constant, it should be private.

FINAL

 When the final modifier is applied to a class, it means that the class cannot be
subclassed.

 When it is applied to a variable, it means that the variable is constant.


 When it is applied to a method, it means that the method cannot be overridden by
subclasses.

N.B. private methods are effectively final, as are all methods declared in a final
class. Marking these latter methods final is legal, but redundant; the compiler
already treats them as final.

Constructor Methods

A constructor method is a special kind of method that determines how an object is


initialized when it's created.

Basic Constructors

Constructors look a lot like regular methods, with two basic differences:
 Constructors always have the same name as the class.
 Constructors don't have a return type.

Why need it?

To use the methods of a class you must create(instantiate) an object/instance of that


class first in the main method, then use this object‘s methods e.g. car.getname()
 All classes have at least one constructor.
 If a class does not declare any, the Java compiler automatically provides a no-
argument constructor, called the default constructor. This default constructor calls
the class parent's no-argument constructor, or the Object class constructor if the
class has no other parent.
 If the parent has no constructor (Object does have one), the compiler will reject the
program.

when you use ―new‖ to create a new instance of a class, Java does three things:
 Allocates memory for the object
 Calls the class's constructor method
 Initializes that object's instance variables, either to their initial values or to a default
(0 for numbers, null for objects, false for booleans, '\0' for characters)

e.g. public Bicycle() {


gear = 1;
cadence = 10;
speed = 0;
}
Bicycle yourBike = new Bicycle();

‗New‘ invokes the no-argument constructor to create a new Bicycle object called yourBike.

e.g. public Bicycle(int startCadence, int startSpeed, int startGear) {


gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
Bicycle myBike = new Bicycle(30, 0, 8);

To create a new Bicycle object called myBike, a constructor is called by the new operator.

If the constructor was not there , it sets the variable to „0‟ ,null and false

e.g. a class called Person, with a constructor that initializes its instance variables based
on the arguments to new. The class also includes a method for the object to introduce
itself, and a main() method to test each of these things

class Person {
String name;
int age;
Person(String n, int a) { // constructor method
name = n;
age = a;
}
void printPerson() {
System.out.print("Hi, my name is " + name);
System.out.println(". I am " + age + " years old.");
}

public static void main (String args[]) {


Person p = new Person("Laura", 20);
p.printPerson();
System.out.println("————");
p = new Person("Tommy", 3);
p.printPerson();
System.out.println("————");
}
}
Answer
Hi, my name is Laura. I am 20 years old.
————
Hi, my name is Tommy. I am 3 years old.
If the constructor was not there it would give the following
Hi, my name is null. I am 0 years old.
————
Hi, my name is null. I am 0 years old.

If the constructor was not there then we would have more coding lines to
add to give the correct results:

class PersonAdjusted {
String name;
int age;

void printPerson() {
System.out.print("Hi, my name is " + name);
System.out.println(". I am " + age + " years old.");
}

public static void main (String args[]) {


//PersonAdjusted p = new PersonAdjusted("Laura", 20);
PersonAdjusted p = new PersonAdjusted();
p.name="Laura";
p.age=20;
p.printPerson();
System.out.println("————");
//p = new PersonAdjusted("Tommy", 3);
p.name="Tommy";
p.age=3;
p.printPerson();
System.out.println("————");
}
}
STATIC
Using the ―static‖ keyword, the variables and methods become class
variables and methods so we don‘t need to call them by object name e.g.
‗name‘ instead of ‗p.name‘.
Class Example
public class Bicycle {
// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has four methods
public void setCadence(int newValue) {
cadence = newValue;
}

public void setGear(int newValue) {


gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}

Subclass Example
public class MountainBike extends Bicycle {
// the MountainBike subclass has one field
public int seatHeight;

// the MountainBike subclass has one constructor


public MountainBike(int startHeight, int startCadence, int startSpeed, int
startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
// the MountainBike subclass has one method
public void setHeight(int newValue) {
seatHeight = newValue; }}
Constructor Overloading

Like methods, constructors can also take varying numbers and types of parameters,
enabling you to create your object with exactly the properties you want it to have, or for
it to be able to calculate properties from different kinds of input, thus “overloading the
constructor”

e.g. a class , MyRect2, that has all the same functionality of the original class MyRect,
except with overloaded constructor methods instead of the buildRect() method

import java.awt.Point;
class MyRect2 {
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = 0;

MyRect2(int x1, int y1, int x2, int y2) {


this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}

MyRect2(Point topLeft, Point


bottomRight) {
x1 = topLeft.x;
y1 = topLeft.y;
x2 = bottomRight.x;
y2 = bottomRight.y;
}

MyRect2(Point topLeft, int w, int h)


{
x1 = topLeft.x;
y1 = topLeft.y;
x2 = (x1 + w);
y2 = (y1 + h);
}

void printRect() {
System.out.print("MyRect: <" + x1 + ", " + y1);
System.out.println(", " + x2 + ", " + y2 + ">");
}
public static void main(String args[]) {
System.out.println("Calling MyRect2 with coordinates 25,25 50,50:");
MyRect2 rect = new MyRect2(25, 25, 50,50);
rect.printRect();
System.out.println("—————");
System.out.println("Calling MyRect2 w/points (10,10), (20,20):");
rect= new MyRect2(new Point(10,10), new Point(20,20));
rect.printRect();
System.out.println("—————");
System.out.print("Calling MyRect2 w/1 point (10,10),");
System.out.println(" width (50) and height (50)");
rect = new MyRect2(new Point(10,10), 50, 50);
rect.printRect();
System.out.println("—————");
}
}

Same answer as before:

Calling MyRect2 with coordinates


25,25 50,50:
MyRect: <25, 25, 50, 50>
—————
Calling MyRect2 w/points (10,10),
(20,20):
MyRect: <10, 10, 20, 20>
—————
Calling MyRect2 w/1 point (10,10),
width (50) and height (50)
MyRect: <10, 10, 60, 60>

Passing Information to a Method or a Constructor


Notice that the return type of the following example is double even though one of the
parameters is an int. If the data types were different , it would be better to use a
constructor

public double computePayment(double loanAmt,


double rate,
double futureValue,
int numPeriods) {
double interest = rate / 100.0;
double partial1 = Math.pow((1 + interest), -numPeriods);
double denominator = (1 - partial1) / interest;
double answer = (-loanAmt / denominator)
- ((futureValue * partial1) / denominator);
return answer;
}
Returning a Value from a Method

A method returns to the code that invoked it when it :


 completes all the statements in the method,
 reaches a ―return statement‖ (if the method has a return type), or
 throws an exception (explained later),
whichever occurs first.

 You can‘t return a value from a method that is declared void, you will get a
compiler error.
 Any method not declared void must contain a return statement with a
corresponding return value, like this:
return returnValue;
 The data type of the return value must match the method's declared return type;
you can't return an integer value from a method declared to return a boolean.
e.g. return integer:

public int getArea() {


return width * height;
}

e.g. return a reference type:

public Bicycle seeWhosFastest(Bicycle myBike, Bicycle yourBike, Environment


env) {
Bicycle fastest;
// code to calculate which bike is faster
return fastest;
}

Overriding Methods
There may be times when you want an object to respond to the same methods but have
different behavior when that method is called. Overriding a method involves defining a
method in a subclass that has the same signature as a method in a superclass. When that
method is called, the method in the subclass is found and executed instead of the one in
the superclass.

Creating Overriding methods

Create a method in your subclass that has the same signature (name, return type, and
parameter list) as a method defined by one of your class's superclasses, but change the
body arguments

e.g. (2 different classes in 2 different java files)


class PrintClass {
int x = 0;
int y = 1;
void printMe() {
System.out.println("X is " + x + ", Y is " + y);
System.out.println("I am an instance of the class " +
this.getClass().getName());
}
}

class PrintSubClass extends PrintClass {


int z = 3;
public static void main(String args[]) {
PrintSubClass obj = new PrintSubClass();
obj.printMe();
}
}

Answer:

X is 0, Y is 1
I am an instance of the class PrintSubClass

In the main() method of PrintSubClass, a PrintSubClass object is created and the


printMe() method is called. Note that PrintSubClass doesn't define this method, so Java
looks for it in each of PrintSubClass's superclasses—and finds it, in this case, in PrintClass.
Unfortunately, because printMe() is still defined in PrintClass, it doesn't print the z
instance variable.

A third class PrintSubClass2 is nearly identical to PrintSubClass, but you override the
printMe() method to include the z variable

class PrintSubClass2 extends PrintClass {


int z = 3;
void printMe() {
System.out.println("x is " + x + ", y is " + y +
", z is " + z);
System.out.println("I am an instance of the class " +
this.getClass().getName());
}
public static void main(String args[]) {
PrintSubClass2 obj = new PrintSubClass2();
obj.printMe();
}
}
Now, when you instantiate this class and call the printMe() method, the version of
printMe() you defined for this class is called instead of the one in the superclass PrintClass
:
Answer:

x is 0, y is 1, z is 3
I am an instance of the class PrintSubClass2

Calling the Original Method

Usually, there are two reasons why you want to override a method that a superclass has
already implemented:

 To replace the definition of that original method completely (hide it) – done above
 To augment the original method with additional behavior - This is particularly useful
where you end up duplicating behavior in both the original method and the method
that overrides it; by being able to call the original method in the body of the
overridden method, you can add only what you need – using the word
“super”

e.g. continuing the last example:

Rather than duplicating most of the behavior of the superclass's method in the subclass,
you can rearrange the superclass's method (PrintClass) so that additional behavior can
easily be added:

// from PrintClass
void printMe() {
System.out.println("I am an instance of the class" +
this.getClass().getName());
System.out.println("X is " + x);
System.out.println("Y is " + y);
}

Then, in the subclass, when you override printMe, you can merely call the original method
and then add the extra commands:

// From PrintSubClass2
void printMe() {
super.printMe();
System.out.println("Z is " + z);
}

Answer:

I am an instance of the class PrintSubClass2


X is 0
Y is 1
Z is 3
N.B. about Superclasses and Subclasses

 A subclass automatically inherits all methods and variables defined in its superclass.
 We only use the command ―super‖ :
 To instantiate the constructor of the superclass from the subclass e.g.1 p5
or
 To call a method from the superclass instead of the compiler by hierarchy
default calling the one in the subclass e.g.2 p10

Difference between “==” and “.equals”

operator is the equality operator

equals() is for content comparison

**operator checks if both object references refer to the same memory location

eg: if (a==b) means it verifies whether both a and b refer to the same location in
memory.

**equals() if for content comparison.

eg:String a chandra ; String b chandra ;

if ( a.equals(b)) returns true because both contain the same content.

1) If you want to compare two basic types are equal, please use the = =;
2) If you want to compare two object references are equal, please use the = =;
3) If you want to compare two objects logically, please use the equals;

E.g.
1 String s1 = "STRING ME";
2 String s2 = "STRING ME";
3
4 System.out.println("s1: " + s1);
5 System.out.println("s2: " + s2);
6 System.out.println("s1 == s2 is " + (s1 == s2));

This would output:


s1: STRING ME
s2: STRING ME
s1 == s2 is true
1 s1 += "2";
2 s2 += "2";
3
4 System.out.println("s1: " + s1);
5 System.out.println("s2: " + s2);
6 System.out.println("s1 == s2 is " + (s1 == s2));

The output is now:

s1: STRING ME2


s2: STRING ME2
s1 == s2 is false
Java Programming Language
Session 7
Previously: constructors / access modifiers / overriding / overloading

Nested Classes
The Java programming language allows you to define a class within another class. Such
a class is called a nested class

e.g.

class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}

 Non-static nested classes (inner classes)


 have access to other members of the enclosing class, even if they are
declared private
 Static nested classes:
 do not have access to other members of the enclosing class
 a static nested class cannot refer directly to instance variables or methods
defined in its enclosing class — it can use them only through an object
reference (instantiate an object)
 A static nested class interacts with the instance members of its outer class
(and other classes) just like any other top-level class. It is behaviorally a
top-level class that has been nested in another top-level class for packaging
convenience

Why Use Nested Classes?

 Logical grouping of classes—If a class is useful to only one other class, then it
is logical to embed it in that class and keep the two together.
 Increased ENCAPSULATION—Consider two top-level classes, A and B, where B
needs access to members of A that would otherwise be declared private. By hiding
class B within class A, A's members can be declared private and B can access
them. In addition, B itself can be hidden (private) from the outside world and only
seen by A.
 More readable, maintainable code—Nesting small classes within top-level
classes places the code closer to where it is used.
 The most common use of inner classes is as event handlers for GUI-based
applications. These classes are usually declared anonymously and as needed for
each component that requires an event handler. The advantage of using an inner
class for event handling is that you can avoid large If/else statements to decide
which component is being handled. Each component gets its own event handler,
so each event handler knows implicitly the component for which it's working.

Example:
In the following example, we will create an array, fill it with integer values (using a
constructor) and then output only values of even indices of the array in ascending order.

GROUPWORK: create an algorithm & pseudo code for the above

The DataStructure class below consists of:

 The DataStructure outer class, which includes methods to add an integer onto the
array and print out values of even indices of the array.
 The InnerEvenIterator inner class, which is similar to a standard Java iterator
interface. Iterators are used to step through a data structure and typically have
methods to test for the last element, retrieve the current element, and move to
the next element.
 A main method that instantiates a DataStructure object (ds) and uses it to fill the
arrayOfInts array with integer values (0, 1, 2, 3, etc.), then calls a printEven
method to print out values of even indices of arrayOfInts.

N.B. Iterators and other specific commands are outside scope of this course which is to
understand basic OOP concepts in Java and how to logically create coding.

class DataStructure {
//create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];

private DataStructure() {
//fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
private void printEven() {
//print out values of even indices of the array
InnerEvenIterator iterator = this.new InnerEvenIterator();
while (iterator.hasNext()) {
System.out.println(iterator.getNext() + " ");
}
}

public static void main(String s[]) {


//fill the array with integer values and print out only values of even
indices
DataStructure ds = new DataStructure();
ds.printEven();
}

//inner class implements the Iterator pattern

private class InnerEvenIterator {


//start stepping through the array from the beginning
private int next = 0;

private boolean hasNext() {


//check if a current element is the last in the array
return (next <= SIZE - 1);
}
private int getNext() {
//record a value of an even index of the array
int retValue = arrayOfInts[next];
//get the next even element
next += 2;
return retValue;
}
}

}
Answer:
0 2 4 6 8 10 12 14

Note that the InnerEvenIterator class refers directly to the arrayOfInts instance variable
of the DataStructure object.

N.B.

1. You cannot put the main method in the inner class


2. You can declare the inner class private or protected but not outer classes
(only their members)
To separate the above nested classes:
(the underlined words are the changes from the last coding) – instead of ―public‖ we can
use no modifier but not private or protected for methods and variables

public class DataStructure1 {


//create an array
public final static int SIZE = 15;
public static int[] arrayOfInts = new int[SIZE];

public DataStructure1() {
//fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
//print out values of even indices of the array
InnerEvenIterator1 iterator = new InnerEvenIterator1();
while (iterator.hasNext()) {
System.out.println(iterator.getNext() + " ");
}
}
public static void main(String s[]) {
//fill the array with integer values and print out values of even indices
DataStructure1 ds = new DataStructure1();
ds.printEven();
}
}

//inner class implements the Iterator pattern


public class InnerEvenIterator1 {
//start stepping through the array from the beginning
public int next = 0;

public boolean hasNext() {


//check if a current element is the last in the array
return (next <= DataStructure1.SIZE - 1);
}
public int getNext() {
//record a value of an even index of the array
int retValue = DataStructure1.arrayOfInts[next];
//get the next even element
next += 2;
return retValue;
}
}
Programming in the Large
Packages
Packages are Java's way of doing large-scale design and organization:
 They are used both to categorize and group classes
 As the number of classes grows, the likelihood of wanting to reuse the short,
simple name of some class increases. Being able to "hide" a class inside a package
becomes useful.

Creating a Package

e.g.
package myFirstPackage.mySecondPackage;
public class MyPublicClass extends ItsSuperclass {
...
} guidance

 The package is a folder that would contain classes. There can be several packages,
and thus folders, inside each other.
 First declare the name of the package in a class by using a package statement,
then define the class
 By convention, package names tend to begin with a lowercase letter to distinguish
them from class names
 Any other classes also declared inside this same package name, are grouped
together
 Packages can be organized into a hierarchy analogous to the inheritance hierarchy,
where each "level" usually represents a smaller, more specific grouping of classes
e.g. the java class library: The top level is called ―java‖  the next level e.g.
packages ―io, net, util, and awt‖  an even lower level, e.g. the package ―image‖
 next e.g. the ColorModel class which can be referred to anywhere in Java code
as java.awt.image.ColorModel
 The first level of the hierarchy specifies the (globally unique) name of the company
or software
 The top-level package name reserves, all the uppercase abbreviations used for
top-level domains on the Internet (EDU, COM, GOV, FR, US, and so on). These
reserved names form the first part of all new package names
 When the compiler generates the
―.class‖ file of a ―.java‖ file, it places it
into this same directory so that the java
interpreter can find it. Both the compiler
and the interpreter expect the hierarchy
 When classes are defined without a
package statement, the compiler places
such classes in a default, unnamed
package, and their ―.java‖ and ―.class‖
files can be located in the current directory (or in the directory called classes below
it). On some systems, the Java class library's .class files are now located in an
archive file named classes.zip in the lib directory

Using a Packaged Class


 if you refer to the class you created in a package like this:

MyPublicClass ;

the compiler complains—because the class MyPublicClass is not defined in the


package java.lang which compiles by default, neither is it a subclass of the
―Object‖ class which classes inherit by default. To solve this problem, Java allows
any class name to be prefixed by the name of the package in which it was defined
to form a unique reference to the class:

myFirstPackage.MyPublicClass ;
 If we want to use a class from a certain package many times, we can "import" the
name of that class into the beginning of the class coding
e.g.
import packagename.ClassName;
ClassName anObject;
// and you can use ClassName directly as many times as you like

N.B.

 All import statements must appear after any package statement but before
any class definitions

e.g.

package javaapplication1;
import java.util.*;
public class VectorDemo{

 You can only import public classes

 If we want to use several classes from the same package, this is how to write it at
the beginning of the coding:
import packagename.*;
e.g.
import javax.swing.*;

Programming in the Small


INHERITANCE
As mentioned, Inheritance is the capability of a class to use the properties and
methods of another class while adding its own functionality and overriding its methods.

e.g. an employee records system:


 Create a generic employee class with states and actions that are common to
all employees.
 Then more specific classes could be defined for salaried, commissioned and
hourly employees.

 The generic class is known as the parent (or superclass or base class) and the
specific classes as children (or subclasses or derived classes).
 The concept of inheritance greatly enhances the ability to reuse code as well as
making design a much simpler and cleaner process
 Java uses the extends keyword to set the relationship between a child class and a
parent class
 You can reuse the superclass constructor and overridden superclass methods by
using the reserved word super. Note that this reference must come first in the
subclass constructor. The reserved word this is used to distinguish between the
object's property and the passed in parameter.
 You cannot override final methods, methods in final classes, private
methods or static methods

ABSTRACTION - ABSTRACT Methods and Classes


Often, the superclass will be set up as an abstract class which does not allow objects of
its prototype to be created. In this case only objects of the subclass are used. Thus:
 abstract classes can create no instances, but they can contain anything a normal
class can contain
 abstract classes are allowed to prefix any of their methods with the modifier
―abstract‖
 other classes extend an abstract class
public abstract class MyFirstAbstractClass {
int anInstanceVariable;
public abstract int aMethodMyNonAbstractSubclassesMustImplement();
public void doSomething() {
. . . // a normal method
}
}
public class AConcreteSubClass extends MyFirstAbstractClass {
public int aMethodMyNonAbstractSubclassesMustImplement() {
. . . // we *must* implement this method
}
}
 the abstract class provides the template for the methods, which are implemented
by others later
 a class does not have to implement all methods (or even any methods) in an
abstract class).
 However all classes that subclass a parent must implement all abstract
methods declared in the parent class or declare them abstract themselves
 Abstract methods have no method statements
INTERFACES
Interfaces pass on only method descriptions to their children and constants, not method
implementations nor instance variables.
 Interfaces are used when programmers want to write their code without any
knowledge of how the other group's code is written e.g. used in GUI for event
handling.
An interface is a reference type, similar to a class:
 It can contain only constants, method signatures.
 There are no method bodies - all methods are abstract
 Interfaces cannot be instantiated
 they can only be implemented by classes or extended by other interfaces

Interfaces as APIs

 Application Programming Interfaces (APIs) are common in commercial


software products. Typically, a company sells a software package that contains
complex methods that another company wants to use in its own software product.
An example would be a package of digital image processing methods that are sold
to companies making end-user graphics programs. The image processing company
writes its classes to implement an interface, which it makes public to its
customers. The graphics company then invokes the image processing methods
using the signatures and return types defined in the interface. While the image
processing company's API is made public (to its customers), its implementation of
the API is kept as a closely guarded secret—in fact, it may revise the
implementation at a later date as long as it continues to implement the original
interface that its customers have relied on.

Defining an Interface
e.g.
public interface OperateCar extends Interface1, Interface2, Interface3 {
// constant declarations, if any
// method signatures

intchangeLanes(Direction direction, double startSpeed, double endSpeed);


intsignalTurn(Direction direction, boolean signalOn);
intgetRadarFront(double distanceToCar, double speedOfCar);
intgetRadarRear(double distanceToCar, double speedOfCar);
......
// more method signatures
}

 An interface declaration consists of


 Modifiers (public indicates that the interface can be used by any class in any
package not just its own package)
 the keyword interface,
 the interface name,
 a comma-separated list of parent interfaces (if any),
 the interface body containing constants and method signatures
 An interface can extend any number of other interfaces, however a class can be a
subclass and extend only one other class
 Method signatures have no braces and are terminated with a semicolon (because
an interface does not provide implementations for the methods declared within it.)
 All methods declared in an interface are public, so the public modifier can be
omitted.
 All constant values defined in an interface are public, static, and final. Once
again, these modifiers can be omitted.

Implementing an Interface
To declare a class that implements an interface:
 Include ―implements‖ in the class declaration
 Your class can implement more than one interface, so the implements keyword is
followed by a comma-separated list of the interfaces implemented by the class
 the ―implements‖ clause follows the ―extends‖ clause
 Implementing an interface means implementing all the methods specified in it
 This means you cannot modify an interface later on by e.g. adding methods to it
because these will have to be implemented by its subclasses too.

Using an Interface as a Type


If you define the type of a variable as an interface, any object you assign to it must be
an instance of a class that implements the interface.

E.g., here is a method for finding the largest object in a pair of objects, for any objects
that are instantiated from a class that implements Relatable:

public Object findLargest(Object object1, Object object2) {


Relatable obj1 = (Relatable)object1;
Relatable obj2 = (Relatable)object2;
if ( (obj1).isLargerThan(obj2) > 0)
return object1;
else
return object2;
}

By casting object1 to a Relatable type, it can invoke the isLargerThan method.


e.g. a six class application is used to generate an array of objects, three specific
shapes’ classes implementing the exact names of methods in a general shape class

public interface Shape {


void draw() ;
void erase() ;
}
class Circle implements Shape {
public void draw() {
System.out.println("Circle object");
}
public void erase() {
System.out.println("Circle erase");
}
}
class Square implements Shape {
public void draw() {
System.out.println("Square object");
}
public void erase() {
System.out.println("Square erase()");
}
}
class Triangle implements Shape {
public void draw() {
System.out.println("Triangle object");
}
public void erase() {
System.out.println("Triangle erase");
}
}

public class ShapesDemo {


private static RandomShapeGenerator gen = new RandomShapeGenerator();

public static void main(String[] args) {


Shape[] s = new Shape[9];
// Fill up the array with shapes:
for (int i = 0; i < s.length; i++)
s[i] = gen.next();
// Make polymorphic method calls:
for (int i = 0; i < s.length; i++)
s[i].draw();
}
}
import java.util.Random;
public class RandomShapeGenerator {
private Random rand = new Random();

public Shape next() {


switch (rand.nextInt(3)) {
default:
case 0:
return new Circle(); Since Interfaces cannot be
case 1: instantiated, interface class
return new Square(); ―SHAPE‖ is not being
case 2:
instantiated; If the random
return new Triangle();
} number is zero, shape gets
} instantiated as a new CIRCLE
} object, and so on

N.B. nextInt(int n) Returns a random number, uniformly distributed int value between 0 (inclusive) and
the specified value (exclusive), drawn from this random number generator's sequence.

POLYMORPHISM
As mentioned, Polymorphism refers to “One Object, Many forms”

 It is the ability of one object to be treated and used like other objects
 It is manifested in several forms:
1. “method overriding” and “method overloading” (multiple methods having
the same name)
o Method Overloading or compile time polymorphism allows having
same method name in a class or a subclass, with different argument types
or numbers.
 Overloaded methods may all be defined in the same class, or they
may be defined in different classes as long as those different
classes share a superclass - subclass relationship.
o Method Overriding means creating a new set of method statements for
the same method signature (name, number of parameters and parameter
types) within inherited subclasses, in 2 ways:
 Replacement occurs when the code of the inherited method is not
executed at all, i.e. it is completely superceded by the code in the
overriding method.
 Refinement augments an inherited method. This is accomplished
by calling, from within the overriding method, a superclass method
using the keyword ―super” or explicitly calling an ancestor method
with its fully qualified name (dot notation); thus the inherited code
is executed in the context of the subclass code
o N.B.
 Overriding: java determines the proper methods to call at the
program’s run time
 Overloading: java determines the proper methods to call at the
program’s compile time
2. ―late/dynamic method binding”
o Consider the shapes example above. The decision to fill the shape array
with a certain type does not occur until runtime. This is a special feature of
Java called ―late binding.‖ It is late binding that allows polymorphism to
work
3. Interfaces Increase Polymorphism: it stretches the ability of polymorphism
over many families of classes
Java Programming Language
Session 8
Abstract Classes - continued

 Abstract classes’ importance is in having:


• the advantage of being a normal class with normal methods and
• the advantage of interfaces of having abstract methods but without having to
implement them all
 An abstract class cannot be instantiated
 Any class with an abstract method must be declared abstract
 A subclass of an abstract class can be instantiated only if it overrides all abstract
methods of its superclass and provides an implementation (i.e., a method body) for
all of them. Such a class is often called a concrete subclass
 If a subclass of an abstract class does not implement all the abstract methods it
inherits, that subclass is itself abstract.
 static, private, and final methods cannot be abstract, since these types of methods
cannot be overridden by a subclass. Similarly, a final class cannot contain any
abstract methods.
 A class can be declared abstract even if it does not actually have any abstract
methods. Declaring such a class abstract indicates that the implementation is
somehow incomplete and is meant to serve as a superclass for one or more
subclasses that will complete the implementation. Such a class cannot be instantiated
 It is only possible to call a concrete method of an abstract class when the method is
instantiated through a concrete subclass. The method must also have a public or
package visibility modifier that makes it accessible to the calling class.

Case Study 1
Create a package called “abstractApplication” and create five classes inside it to fill an
array with shapes and calculate their areas and parameters:

/*****abstract class containing methods to be inherited by its subclasses


and implemented for different usage in each subclass******/
public abstract class Shapes {
public double getRadius(double r) { return r; } // Accessor
public double getWidth(double w) { return w; } // Accessor method
public double getHeight(double h) { return h; } // Another accessor

public abstract double area(); // Abstract methods: note


public abstract double circumference(); // semicolon instead of body

/******subclass extending "shapes" thus using normal methods inside it


and implementing abstract methods in it******/
class Circles extends Shapes {
public static final double PI = 3.14159265358979323846;
protected double r; // Instance data
public Circles(double radius) {
r = radius;
getRadius(r);} // Constructor

public double area() { return PI*r*r; } // Implementations of


public double circumference() { return 2*PI*r; } // abstract methods.
/******subclass extending "shapes" thus using normal methods inside it
and implementing abstract methods in it******/
class Rectangles extends Shapes {
protected double w, h; // Instance data
public Rectangles(double w, double h) { // Constructor
this.w = w; this.h = h;
}

public double area() { return w*h; } // Implementations of


public double circumference() { return 2*(w + h); } // abstract methods.
}

/******subclass extending "shapes" thus using normal methods inside it


and implementing abstract methods in it******/
package abstract_Application;
import java.lang.Math;

class Triangles extends Shapes {


protected double w, h; // Instance data
public Triangles(double w, double h) { // Constructor
this.w = w; this.h = h;
}

public double area() { return w*h/2; } // Implementations of abstract methods


public double circumference() {
double x=((w/2)*(w/2)) + (h*h);
return ((Math.sqrt(x))*2)+w;
}
}

/******* class of business logic ***********/


import javax.swing.JOptionPane;
public class CalculateTotalArea {

public static void main(String[] args) {

String noOfShapesString=JOptionPane.showInputDialog(null,"How many shapes


do you want to calculate the total area and perimeter of?","Adding Areas",
JOptionPane.QUESTION_MESSAGE);
int noOfShapes=Integer.parseInt(noOfShapesString); // take input of
how many shapes
Shapes[] shapeArray = new Shapes[noOfShapes]; // Create an array to
hold shapes
String[] choices = {"circle", "rectangle", "triangle"}; // create an array of
options for option dialog box

for (int i=0;i<shapeArray.length;i++){

//... Text to put on the buttons of option dialog box

int response = JOptionPane.showOptionDialog(


null // Center in window.
, "Choose shape "+(i+1) // Message
, "Adding Areas" // Title in titlebar
, JOptionPane.YES_NO_OPTION // Option type
, JOptionPane.PLAIN_MESSAGE // messageType
, null // Icon (none)
, choices // Button text as above.
, "None" ); // Default button's label
switch (response) {
case 0: // if choice is circle, ask for its radius, add it
to array and display its radius
String circleRadiusString=JOptionPane.showInputDialog(null,"Please enter shape
"+(i+1)+" circle radius","Adding Areas",
JOptionPane.QUESTION_MESSAGE);
double circleRadius = Double.parseDouble(circleRadiusString);
shapeArray[i] = new Circles(circleRadius); // Fill in the array
System.out.println("the radius of the circle shape "+(i+1)+" is " +
shapeArray[i].getRadius(circleRadius));
break;
case 1: // if choice is rectangle, ask for its width,height, add
it to array and display its parameters
String shapeWidthString=JOptionPane.showInputDialog(null,"Please enter shape
"+(i+1)+" rectangle width","Adding Areas",
JOptionPane.QUESTION_MESSAGE);
double shapeWidth = Double.parseDouble(shapeWidthString);
String shapeHeightString=JOptionPane.showInputDialog(null,"Please enter shape
"+(i+1)+" rectangle height","Adding Areas",
JOptionPane.QUESTION_MESSAGE);
double shapeHeight = Double.parseDouble(shapeHeightString);

shapeArray[i] = new Rectangles(shapeWidth, shapeHeight);


System.out.println("the width of the rectangle shape "+(i+1)+" is " +
shapeArray[i].getWidth(shapeWidth));
System.out.println("the height of the rectangle shape "+(i+1)+" is " +
shapeArray[i].getHeight(shapeHeight));
break;
case 2: // if choice is triangle, ask for its width,height, add it to
array and display its parameters
shapeWidthString=JOptionPane.showInputDialog(null,"Please enter shape
"+(i+1)+" triangle width","Adding Areas",
JOptionPane.QUESTION_MESSAGE);
shapeWidth = Double.parseDouble(shapeWidthString);
shapeHeightString=JOptionPane.showInputDialog(null,"Please enter shape
"+(i+1)+" triangle height","Adding Areas",
JOptionPane.QUESTION_MESSAGE);
shapeHeight = Double.parseDouble(shapeHeightString);
shapeArray[i] = new Triangles(shapeWidth, shapeHeight);
System.out.println("the width of the triangle shape "+(i+1)+" is " +
shapeArray[i].getWidth(shapeWidth));
System.out.println("the height of the triangle shape "+(i+1)+" is " +
shapeArray[i].getHeight(shapeHeight));
break;
}
}
double total_area = 0;
double total_circumference=0;
for(int i = 0; i < shapeArray.length; i++)
{total_area += shapeArray[i].area();
total_circumference+=shapeArray[i].circumference();
} // Compute the area & circumference of
the shapes
int final_area =(int)total_area;
int final_circumference=(int)total_circumference; // cast result to integers

JOptionPane.showMessageDialog(null, "total area of shapes is "


+final_area+"cm2" //output to messagebox
+ "\ntotal perimeter of shapes is "+final_circumference+"cm");

}}
Case Study 2: Payroll System Using Polymorphism

Create a payroll program


Use abstract methods and polymorphism
Problem statement
4 types of employees, paid weekly
1. Salaried (fixed salary, no matter the hours)
2. Hourly (overtime [>40 hours] pays time and a half)
3. Commission (paid percentage of sales)
4. Base-plus-commission (base salary + percentage of sales)
• Boss wants to raise pay by 10%
Superclass Employee (generic)
Abstract method earnings (returns pay)
• abstract because need to know employee type
• Cannot calculate for generic employee
Other classes extend Employee
Last class performs the business logic

N.B. note the usage of the question mark colon operator question e.g. :
result = someCondition ? value1 : value2;
N.B.
 “Constructors” don't create objects. They initialize them. The “new” operator
creates objects
 Therefore All classes including abstract classes can have constructors.
 Abstract class constructor will be called only when its concrete subclass is
instantiated. But you cannot create a new object of an abstract class using the
“new” operator
6 classes :

/***** employee abstract superclass *******/


package payroll;

public abstract class Employee {


private String firstName;
private String lastName;
private String socialSecurityNumber;
// constructor
public Employee( String first, String last, String ssn )
{
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
}

// set first name


public void setFirstName( String first )
{
firstName = first;
}

// return first name


public String getFirstName()
{
return firstName;
}

// set last name


public void setLastName( String last )
{
lastName = last;
}

// return last name


public String getLastName()
{
return lastName;
}

// set social security number


public void setSocialSecurityNumber( String number )
{
socialSecurityNumber = number; // should validate
}

// return social security number


public String getSocialSecurityNumber()
{
return socialSecurityNumber;
}

// return String representation of Employee object


public String toString()
{
return getFirstName() + " " + getLastName() +
"\nsocial security number: " + getSocialSecurityNumber();
}
// abstract method overridden by subclasses
public abstract double earnings();

} // end abstract class Employee

/***** subclass of "salaried employee" *****/


package payroll;

public class SalariedEmployee extends Employee {


private double weeklySalary;// used only for Salaried Emploee

// constructor
public SalariedEmployee( String first, String last,
String socialSecurityNumber, double salary )
{
super( first, last, socialSecurityNumber );
setWeeklySalary( salary );
}

// set salaried employee's salary


public void setWeeklySalary( double salary )
{
// if salary is less than 0 then make weeklySalary =0 otherwise make it
equal to salary
weeklySalary = salary< 0.0 ? 0.0 : salary;
}

// return salaried employee's salary


public double getWeeklySalary()
{
return weeklySalary;
}

// calculate salaried employee's pay;


// override abstract method earnings in Employee
public double earnings()
{
return getWeeklySalary();
}

// return String representation of SalariedEmployee object


public String toString()
{
return "\nsalaried employee: " + super.toString();
}
} // end class SalariedEmployee
/***** subclass of "Hourly Employees" *****/
package payroll;

public class HourlyEmployee extends Employee {


private double wage; // wage per hour
private double hours; // hours worked for week

// constructor
public HourlyEmployee( String first, String last,
String socialSecurityNumber, double hourlyWage, double hoursWorked )
{
super( first, last, socialSecurityNumber );
setWage( hourlyWage );
setHours( hoursWorked );
}

// set hourly employee's wage


public void setWage( double wageAmount )
{
wage = wageAmount < 0.0 ? 0.0 : wageAmount;
}

// return wage
public double getWage()
{
return wage;
}

// set hourly employee's hours worked


public void setHours( double hoursWorked )
{
hours = ( hoursWorked >= 0.0 && hoursWorked <= 168.0 ) ?
hoursWorked : 0.0;
}

// return hours worked


public double getHours()
{
return hours;
}

// calculate hourly employee's pay;


// override abstract method earnings in Employee
public double earnings()
{
if ( hours <= 40 ) // no overtime
return getWage() * getHours();
else
return 40 * getWage() + ( getHours() - 40 ) * getWage() * 1.5;
}
// return String representation of HourlyEmployee object
public String toString()
{
return "\nhourly employee: " + super.toString();
}
} // end class HourlyEmployee

/***** subclass of "Commissioned Employees" *****/


package payroll;

public class CommissionEmployee extends Employee {


private double grossSales; // gross weekly sales
private double commissionRate; // commission percentage

// constructor
public CommissionEmployee( String first, String last,
String socialSecurityNumber,
double grossWeeklySales, double percent )
{
super( first, last, socialSecurityNumber );
setGrossSales( grossWeeklySales );
setCommissionRate( percent );
}

// set commission employee's rate


public void setCommissionRate( double rate )
{
commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0;
}

// return commission employee's rate


public double getCommissionRate()
{
return commissionRate;
}

// set commission employee's weekly base salary


public void setGrossSales( double sales )
{
grossSales = sales < 0.0 ? 0.0 : sales;
}

// return commission employee's gross sales amount


public double getGrossSales()
{
return grossSales;
}

// calculate commission employee's pay;


// override abstract method earnings in Employee
public double earnings()
{
return getCommissionRate() * getGrossSales();
}

// return String representation of CommissionEmployee object


public String toString()
{
return "\ncommission employee: " + super.toString();
}
} // end class CommissionEmployee

/***** subclass of "Base Plus Commissioned Employees" *****/


package payroll;

public class BasePlusCommissionEmployee extends CommissionEmployee {


private double baseSalary; // base salary per week

// constructor
public BasePlusCommissionEmployee( String first, String last,
String socialSecurityNumber, double grossSalesAmount,
double rate, double baseSalaryAmount )
{
super( first, last, socialSecurityNumber, grossSalesAmount, rate );
setBaseSalary( baseSalaryAmount );
}

// set base-salaried commission employee's base salary


public void setBaseSalary( double salary )
{
baseSalary = salary < 0.0 ? 0.0 : salary;
}

// return base-salaried commission employee's base salary


public double getBaseSalary()
{
return baseSalary;
}

// calculate base-salaried commission employee's earnings;


// override method earnings in CommissionEmployee
public double earnings()
{
return getBaseSalary() + super.earnings();
}
// return String representation of BasePlusCommissionEmployee
public String toString()
{
return "\nbase-salaried commission employee: " +
super.getFirstName() + " " + super.getLastName() +
"\nsocial security number: " + super.getSocialSecurityNumber();
}
} // end class BasePlusCommissionEmployee

/***** Business Logic Class *****/


package payroll;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;

public class PayrollSystemTest {

public static void main( String[] args )


{
DecimalFormat twoDigits = new DecimalFormat( "0.00" );

// create Employee array


Employee employees[] = new Employee[ 4 ];

// initialize array with Employees


employees[ 0 ] = new SalariedEmployee( "John", "Smith","111-11-1111",
800.00 );
employees[ 1 ] = new CommissionEmployee( "Sue", "Jones","222-22-2222",
10000, .06 );
employees[ 2 ] = new BasePlusCommissionEmployee( "Bob", "Lewis","333-33-
3333", 5000, .04, 300 );
employees[ 3 ] = new HourlyEmployee( "Karen", "Price","444-44-4444",
16.75, 40 );

String output = "";

// generically process each element in array employees


for ( int i = 0; i < employees.length; i++ ) {
output += employees[ i ].toString();

// determine whether element is a BasePlusCommissionEmployee


if ( employees[ i ] instanceof BasePlusCommissionEmployee ) {
/* operator instanceof checks the type of the object to which its left operand
refers and determines whether this type has an is-a relationship with the type
specified as its right operand . */

// downcast Employee reference to BasePlusCommissionEmployee reference


BasePlusCommissionEmployee currentEmployee = (
BasePlusCommissionEmployee ) employees[ i ];

double oldBaseSalary = currentEmployee.getBaseSalary();


output += "\nold base salary: $" + oldBaseSalary;

currentEmployee.setBaseSalary( 1.10 * oldBaseSalary );


output += "\nnew base salary with 10% increase is: $" +
currentEmployee.getBaseSalary();
} // end if

output += "\nearned $" + employees[ i ].earnings() + "\n";


} // end for
// get type name of each object in employees array
for ( int j = 0; j < employees.length; j++ )
output += "\nEmployee " + j + " is a " +
employees[ j ].getClass().getName();

JOptionPane.showMessageDialog( null, output ); // display output


System.exit( 0 );

} // end main
} // end class
Case Study 3 : create several musical instrument classes which inherit from the
abstract class “instruments”
// Abstract class and methods
abstract class Instrument {
public abstract void play();
public String what() {
return "Instrument";
}
public abstract void adjust();
}

// subclass
package music;
class Wind extends Instrument {
public void play() {
System.out.println("Wind.play()");
}
public String what() { return "Wind"; }
public void adjust() {}
}

// subclass
package music;
class Percussion extends Instrument {
public void play() {
System.out.println("Percussion.play()");
}
public String what() { return "Percussion"; }
public void adjust() {}
}

// subclass
package music;
class Strings extends Instrument {
public void play() {
System.out.println("Strings.play()");
}
public String what() { return "Strings"; }
public void adjust() {}
}

// subclass
package music;
class Brass extends Wind {
public void play() {
System.out.println("Brass.play()");
}
public void adjust() {
System.out.println("Brass.adjust()");
}
}

// subclass
package music;
class Woodwind extends Wind {
public void play() {
System.out.println("Woodwind.play()");
}
public String what() { return "Woodwind"; }
}
Search Functions for Arrays & Dynamic Array

import java.util.*;
public class ArraySearchTest {
public static void main(String args[])
throws Exception {
int array[] = {2, 5, -2, 6, -3, 8, 0, -
7, -9, 4};

// Ensure array sorted


Arrays.sort(array);
printArray("Sorted array", array);

// Search for element in array


int index = Arrays.binarySearch(array, 2);
System.out.println("Found 2 @ " + index);

// Search for element not in array.....


// A negative return value indicates that the element is not in the list....
// However, the actual return value can be used to determine where that
non-existent element should be inserted in the list if that were desired
index = Arrays.binarySearch(array, 1);
System.out.println("Didn't find 1 @ " + index);

// Insert
int newIndex = -index - 1;
array = insertElement(array, 1, newIndex);
printArray("With 1 added", array);

}
private static void printArray(String message, int array[]) {
System.out.println(message + ": [length: " + array.length + "]");
// Print out sorted array elements
for (int i=0, n=array.length; i<n; i++) {
if (i != 0) System.out.print(", ");
System.out.print(array[i]);
}
System.out.println();
}
private static int[] insertElement(int original[], int element, int index) {
int length = original.length;
int destination[] = new int[length+1];
System.arraycopy(original, 0, destination, 0, index);
destination[index] = element;
System.arraycopy(original, index, destination, index+1, length-index);
return destination;
}
}
Selection Sort for Arrays

This uses the idea of finding the biggest item in the list and moving it to the end. Once
the biggest item is in its correct location, you can then apply the same idea to the
remaining items. That is, find the next-biggest item, and move it into the next-to-last
space, and so forth. This algorithm is called selection sort

static void selectionSort(int[] A) {

// Sort A into increasing order, using selection sort

for (int lastPlace = A.length-1; lastPlace > 0; lastPlace--) {


// Find the largest item among A[0], A[1], ...,
// A[lastPlace], and move it into position lastPlace
// by swapping it with the number that is currently
// in position lastPlace.

int maxLoc = 0; // Location of largest item seen so far.

for (int j = 1; j <= lastPlace; j++) {


if (A[j] > A[maxLoc]) {
// Since A[j] is bigger than the maximum we've seen
// so far, j is the new location of the maximum value
// we've seen so far.
maxLoc = j;
}
}

int temp = A[maxLoc]; // Swap largest item with A[lastPlace].


A[maxLoc] = A[lastPlace];
A[lastPlace] = temp;

} // end of for loop

}
Vectors
 Vectors (the java.util.Vector class) are commonly used instead of arrays, because
they expand automatically when new data is added to them.
 Vectors can hold only Objects and not primitive types (eg, int). If you want to put
a primitive type in a Vector, put it inside an object (eg, define your own class)
 You must import either import java.util.Vector; or import java.util.*
 Create a Vector with default initial size
Vector v = new Vector();
 Create a Vector with an initial size
Vector v = new Vector(300);
 To Add elements to the end of a Vector
v.add(s); // adds s to the end of the Vector v
v.addElement(new Float(1.9999));
 To get the elements from a Vector (ListIterator)
You can use a for loop to get all the elements from a Vector, but another very
common way to go over all elements in a Vector is to use a ListIterator. The
advantage of an iterator is that it can be used with other data structures, so that if
you later change to using a linked list for example, you won't have to change your
code. Here is an example of using an iterator to print all elements (Strings) in a
vector. The two most useful methods are hasNext(), which returns true if there
are more elements, and next(), which returns the next element.
ListIterator iter = v.listIterator();
while (iter.hasNext()) {
System.out.println((String)iter.next());
}

 Common Vector Methods


v is a Vector, i is an int index, o is an Object
Method Description
v.add(o) adds Object o to Vector v
Inserts Object o at index i, shifting elements up as
v.add(i, o)
necessary.
v.clear() removes all elements from Vector v
v.contains(o) Returns true if Vector v contains Object o
v.firstElement(i) Returns the first element.
v.get(i) Returns the object at int index i.
v.lastElement(i) Returns the last element.
Returns a ListIterator that can be used to go over the
v.listIterator()
Vector. This is a useful alternative to the for loop.
Removes the element at position i, and shifts all
v.remove(i)
following elements down.
v.set(i,o) Sets the element at index i to o.
v.size() Returns the number of elements in Vector v.
myVector.insertElementAt(my_object, 5) Insert an element at a certain position
Java Programming Language
Session 10

Laying Out Components within a Container


Layout Managers are used to

o Calculate the minimum/preferred/maximum sizes for a container.


o Lay out the container's children (arrange components within a graphical
interface).

There are many standard Layout Managers available:

BorderLayout

The content pane is the main container in all frames, applets, and dialogs. A
BorderLayout places components in up to five areas: top, bottom, left,
right, and center. All extra space is placed in the center area.
/*
* BorderLayoutDemo.java
*
*/
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;

public class BorderLayoutDemo {

public static void addComponentsToPane(Container pane) {

JButton button = new JButton("Button 1 (PAGE_START)");


pane.add(button, BorderLayout.NORTH);
//Make the center component big, since that's the
//typical usage of BorderLayout.
button = new JButton("Button 2 (CENTER)");
button.setPreferredSize(new Dimension(200, 100));
pane.add(button, BorderLayout.CENTER);

button = new JButton("Button 3 (LINE_START)");


pane.add(button, BorderLayout.WEST);

button = new JButton("Long-Named Button 4 (PAGE_END)");


pane.add(button, BorderLayout.SOUTH);

button = new JButton("5 (LINE_END)");


pane.add(button, BorderLayout.EAST);
}

/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {

//Create and set up the window.


JFrame frame = new JFrame("BorderLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Use the content pane's default BorderLayout.
//Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {


createAndShowGUI();
}
}

BoxLayout
The BoxLayout class puts components in a
single row or column. It respects the
components' requested maximum sizes and
also lets you align components
think of it as a version of FlowLayout, but with greater functionality
/*
* BoxLayoutDemo.java requires no other files.
*/
import java.awt.Component;
import java.awt.Container;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;

public class BoxLayoutDemo {


public static void addComponentsToPane(Container pane) {
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));

addAButton("Button 1", pane);


addAButton("Button 2", pane);
addAButton("Button 3", pane);
addAButton("Long-Named Button 4", pane);
addAButton("5", pane);
}

private static void addAButton(String text, Container container) {


JButton button = new JButton(text);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
container.add(button);
}

/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("BoxLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set up the content pane.


addComponentsToPane(frame.getContentPane());

//Display the window.


frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {

//creating and showing this application's GUI.


createAndShowGUI();
}
}
CardLayout

The CardLayout class lets you implement an area that contains different
components at different times. A CardLayout is often controlled by a combo
box, with the state of the combo box determining which panel (group of
components) the CardLayout displays.
/*
* CardLayoutDemo.java
*
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CardLayoutDemo implements ItemListener {


JPanel cards; //a panel that uses CardLayout
final static String BUTTONPANEL = "Card with JButtons";
final static String TEXTPANEL = "Card with JTextField";

public void addComponentToPane(Container pane) {


//Put the JComboBox in a JPanel to get a nicer look.
JPanel comboBoxPane = new JPanel(); //use FlowLayout
String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL };
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);

//Create the "cards".


JPanel card1 = new JPanel();
card1.add(new JButton("Button 1"));
card1.add(new JButton("Button 2"));
card1.add(new JButton("Button 3"));

JPanel card2 = new JPanel();


card2.add(new JTextField("TextField", 20));

//Create the panel that contains the "cards".


cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);

pane.add(comboBoxPane, BorderLayout.NORTH);
pane.add(cards, BorderLayout.CENTER);
}

public void itemStateChanged(ItemEvent evt) {


CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)evt.getItem());
}

/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("CardLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.


CardLayoutDemo demo = new CardLayoutDemo();
demo.addComponentToPane(frame.getContentPane());

//Display the window.


frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {


createAndShowGUI();
}
}

FlowLayout

FlowLayout is the default layout manager for every JPanel. It simply lays
out components in a single row, starting a new row if its container is not
sufficiently wide. Both panels in CardLayoutDemo, shown previously, use
FlowLayout
/*
*
* FlowLayoutDemo.java
*
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class FlowLayoutDemo extends JFrame{


JRadioButton RtoLbutton;
JRadioButton LtoRbutton;
FlowLayout experimentLayout = new FlowLayout();
final String RtoL = "Right to left";
final String LtoR = "Left to right";
JButton applyButton = new JButton("Apply component orientation");

public FlowLayoutDemo(String name) {


super(name);
}

public void addComponentsToPane(final Container pane) {


final JPanel compsToExperiment = new JPanel();
compsToExperiment.setLayout(experimentLayout);
experimentLayout.setAlignment(FlowLayout.TRAILING);
JPanel controls = new JPanel();
controls.setLayout(new FlowLayout());

LtoRbutton = new JRadioButton(LtoR);


LtoRbutton.setActionCommand(LtoR);
LtoRbutton.setSelected(true);
RtoLbutton = new JRadioButton(RtoL);
RtoLbutton.setActionCommand(RtoL);

//Add buttons to the experiment layout


compsToExperiment.add(new JButton("Button 1"));
compsToExperiment.add(new JButton("Button 2"));
compsToExperiment.add(new JButton("Button 3"));
compsToExperiment.add(new JButton("Long-Named Button 4"));
compsToExperiment.add(new JButton("5"));
//Left to right component orientation is selected by default
compsToExperiment.setComponentOrientation(
ComponentOrientation.LEFT_TO_RIGHT);

//Add controls to set up the component orientation in the experiment layout


final ButtonGroup group = new ButtonGroup();
group.add(LtoRbutton);
group.add(RtoLbutton);
controls.add(LtoRbutton);
controls.add(RtoLbutton);
controls.add(applyButton);

//Process the Apply component orientation button press


applyButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String command = group.getSelection().getActionCommand();
//Check the selection
if (command.equals("Left to right")) {
compsToExperiment.setComponentOrientation(
ComponentOrientation.LEFT_TO_RIGHT);
} else {
compsToExperiment.setComponentOrientation(
ComponentOrientation.RIGHT_TO_LEFT);
}
//update the experiment layout
compsToExperiment.validate();
compsToExperiment.repaint();
}
});
pane.add(compsToExperiment, BorderLayout.CENTER);
pane.add(controls, BorderLayout.SOUTH); ;
}

/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Create and set up the window.
FlowLayoutDemo frame = new FlowLayoutDemo("FlowLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
frame.addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {


createAndShowGUI();
}
}

GridBagLayout
GridBagLayout is a sophisticated, flexible
layout manager. It aligns components by
placing them within a grid of cells,
allowing components to span more than one cell. The rows in the grid can
have different heights, and grid columns can have different widths.

GridLayout

GridLayout simply makes a bunch of


components equal in size and
displays them in the requested
number of rows and columns

/*
* GridLayoutDemo.java
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GridLayoutDemo extends JFrame {


static final String gapList[] = {"0", "10", "15", "20"};
final static int maxGap = 20;
JComboBox horGapComboBox;
JComboBox verGapComboBox;
JButton applyButton = new JButton("Apply gaps");
GridLayout experimentLayout = new GridLayout(3,2);

public GridLayoutDemo(String name) {


super(name);
setResizable(false);
}

public void initGaps() {


horGapComboBox = new JComboBox(gapList);
verGapComboBox = new JComboBox(gapList);
}

public void addComponentsToPane(final Container pane) {


initGaps();
final JPanel compsToExperiment = new JPanel();
compsToExperiment.setLayout(experimentLayout);
JPanel controls = new JPanel();
controls.setLayout(new GridLayout(2,3));

//Set up components preferred size


JButton b = new JButton("Just fake button");
Dimension buttonSize = b.getPreferredSize();
compsToExperiment.setPreferredSize(new Dimension((int)(buttonSize.getWidth()
* 2.5)+maxGap,
(int)(buttonSize.getHeight() * 3.5)+maxGap * 2));
//Add buttons to experiment with Grid Layout
compsToExperiment.add(new JButton("Button 1"));
compsToExperiment.add(new JButton("Button 2"));
compsToExperiment.add(new JButton("Button 3"));
compsToExperiment.add(new JButton("Long-Named Button 4"));
compsToExperiment.add(new JButton("5"));

//Add controls to set up horizontal and vertical gaps


controls.add(new Label("Horizontal gap:"));
controls.add(new Label("Vertical gap:"));
controls.add(new Label(" "));
controls.add(horGapComboBox);
controls.add(verGapComboBox);
controls.add(applyButton);

//Process the Apply gaps button press


applyButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Get the horizontal gap value
String horGap = (String)horGapComboBox.getSelectedItem();
//Get the vertical gap value
String verGap = (String)verGapComboBox.getSelectedItem();
//Set up the horizontal gap value
experimentLayout.setHgap(Integer.parseInt(horGap));
//Set up the vertical gap value
experimentLayout.setVgap(Integer.parseInt(verGap));
//Set up the layout of the buttons
experimentLayout.layoutContainer(compsToExperiment);
}
});
pane.add(compsToExperiment, BorderLayout.NORTH);
pane.add(new JSeparator(), BorderLayout.CENTER);
pane.add(controls, BorderLayout.SOUTH);
}
/**Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Create and set up the window.
GridLayoutDemo frame = new GridLayoutDemo("GridLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
frame.addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
}
}
Java Programming Language
Session 11

GUI Without Layout Managers – Absolute Positioning

Uses

If a container holds components whose size is not affected by the container's size or by
font, look-and-feel, or language changes. Desktop panes, which contain internal frames,
are in this category. The size and position of internal frames does not depend directly on
the desktop pane's size. The programmer determines the initial size and placement of
internal frames within the desktop pane, and then the user can move or resize the
frames. A layout manager is unnecessary in this situation.

Steps

1. Set the container's layout manager to null by calling setLayout(null).


2. Call the Component class's setbounds method for each of the container's children.
3. Call the Component class's repaint method.

/*
* AbsoluteLayoutDemo.java
*/

import java.awt.Container;
import java.awt.Insets;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;

public class AbsoluteLayoutDemo {

public static void addComponentsToPane(Container pane) {


pane.setLayout(null);

JButton b1 = new JButton("one");


JButton b2 = new JButton("two");
JButton b3 = new JButton("three");

pane.add(b1);
pane.add(b2);
pane.add(b3);

Insets insets = pane.getInsets();


Dimension size = b1.getPreferredSize(); // default size (50,25)
size.width=60;
size.height=30;
b1.setBounds(25 + insets.left, 5 + insets.top,
size.width, size.height);
size = b2.getPreferredSize();
b2.setBounds(55 + insets.left, 40 + insets.top,
size.width, size.height);
size = b3.getPreferredSize();
b3.setBounds(150 + insets.left, 15 + insets.top,
size.width + 50, size.height + 20);
}

/**
* Create the GUI and show it.
*/

private static void createAndShowGUI() {


//Create and set up the window.
JFrame frame = new JFrame("AbsoluteLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set up the content pane.


addComponentsToPane(frame.getContentPane());

//Size and display the window.


Insets insets = frame.getInsets();
frame.setSize(300 + insets.left + insets.right,
125 + insets.top + insets.bottom);
frame.setVisible(true);
}

public static void main(String[] args) {


//Schedule a job
//creating and showing this application's GUI.
createAndShowGUI();
}
}

Event Listeners

1. Beeper
• a button that beeps when you click it
• The Beeper class implements the ActionListener interface, which contains
one method: actionPerformed. Once the Beeper has been registered using
the Button addActionListener method, the Beeper's actionPerformed method
is called every time the button is clicked.
/*Beeper.java
*/
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JComponent;

import java.awt.Toolkit;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Beeper extends JPanel implements ActionListener {


JButton button;

public Beeper() {
super(new BorderLayout());
button = new JButton("Click Me");
button.setPreferredSize(new Dimension(200, 80));
add(button, BorderLayout.CENTER);
button.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {


Toolkit.getDefaultToolkit().beep();
}
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Beeper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.


JComponent newContentPane = new Beeper();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);

//Display the window.


frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job
createAndShowGUI();
}
}
Listeners Supported by Swing Components
You can tell what kinds of events a component can fire by looking at the kinds of event
listeners you can register on it. For example, the JComboBox class defines these listener
registration methods:

• addActionListener
• addItemListener
• addPopupMenuListener

Thus a combo box supports action, item, and popup menu listeners in addition to the
listener methods it inherits from JComponent

Listeners supported by Swing components fall into two categories:

• Listeners that All Swing Components Support


• Other Listeners that Swing Components Support

Because all Swing components descend from the AWT Component class, you can
register the following listeners on any Swing component:

component listener

Listens for changes in the component's size, position, or visibility.

focus listener

Listens for whether the component gained or lost the keyboard focus.

key listener

Listens for key presses; key events are fired only by the component that has the
current keyboard focus.

mouse listener

Listens for mouse clicks, mouse presses, mouse releases and mouse movement
into or out of the component's drawing area.

mouse-motion listener

Listens for changes in the mouse cursor's position over the component.

mouse-wheel listener

Listens for mouse wheel movement over the component.


Action Listeners
Action listeners are probably the easiest — and most common — event handlers to
implement. You implement an action listener to define what should be done when an
user performs certain operation

Examples: When the user clicks a button, chooses a menu item, presses Enter in a text
field. The result is that an actionPerformed message is sent to all action listeners that
are registered on the relevant component.

Steps:

1. Declare an event handler class and specify that the class either implements an
ActionListener interface or extends a class that implements an ActionListener
interface. For example:

public class MyClass implements ActionListener {

Register an instance of the event handler class as a listener on one or more components
using the addActionListener method. When the user clicks the onscreen button, the
button fires an action event. This results in the invocation of the action listener's
actionPerformed method (the only method in the ActionListener interface). The single
argument to the method is an ActionEvent object that gives information about the event
and its source.

2. . For example:

someComponent.addActionListener(instanceOfMyClass);

3. Include code that implements the methods in listener interface. For example:

public void actionPerformed(ActionEvent e) { ...//code that reacts to the action...


}

E.G.

import java.awt.*;
import java.awt.event.*;

public class AL extends Frame implements


WindowListener,ActionListener {
TextField text = new TextField(20);
Button b;
private int numClicks = 0;

public static void main(String[] args) {


AL myWindow = new AL("My first window");
myWindow.setSize(350,100);
myWindow.setVisible(true);
}

public AL(String title) {

super(title);
setLayout(new FlowLayout());
addWindowListener(this);
b = new Button("Click me");
add(b);
add(text);
b.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {


numClicks++;
text.setText("Button Clicked " + numClicks + " times");
}

public void windowClosing(WindowEvent e) {


dispose();
System.exit(0);
}

public void windowOpened(WindowEvent e) {}


public void windowActivated(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}

Internal Frame
Event
/*
InternalFrameEventDemo
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import
javax.swing.event.*;

public class
InternalFrameEventDemo
extends
JFrame
implements InternalFrameListener,
ActionListener {
JTextArea display;
JDesktopPane desktop;
JInternalFrame displayWindow;
JInternalFrame listenedToWindow;
static final String SHOW = "show";
static final String CLEAR = "clear";
String newline = "\n";
static final int desktopWidth = 500;
static final int desktopHeight = 300;

public InternalFrameEventDemo(String title) {


super(title);

//Set up the GUI.


desktop = new JDesktopPane();
desktop.putClientProperty("JDesktopPane.dragMode",
"outline");
//Because we use pack, it's not enough to call setSize.
//We must set the desktop's preferred size.
desktop.setPreferredSize(new Dimension(desktopWidth, desktopHeight));
setContentPane(desktop);

createDisplayWindow();
desktop.add(displayWindow); //DON'T FORGET THIS!!!
Dimension displaySize = displayWindow.getSize();
displayWindow.setSize(desktopWidth, displaySize.height);
}

//Create the window that displays event information.


protected void createDisplayWindow() {
JButton b1 = new JButton("Show internal frame");
b1.setActionCommand(SHOW);
b1.addActionListener(this);

JButton b2 = new JButton("Clear event info");


b2.setActionCommand(CLEAR);
b2.addActionListener(this);

display = new JTextArea(3, 30);


display.setEditable(false);
JScrollPane textScroller = new JScrollPane(display);
//Have to supply a preferred size, or else the scroll
//area will try to stay as large as the text area.
textScroller.setPreferredSize(new Dimension(200, 75));
textScroller.setMinimumSize(new Dimension(10, 10));

displayWindow = new JInternalFrame("Event Watcher",


true, //resizable
false, //not closable
false, //not maximizable
true); //iconifiable
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
contentPane.setLayout(new BoxLayout(contentPane,
BoxLayout.X_AXIS));
b1.setAlignmentX(CENTER_ALIGNMENT);
contentPane.add(b1);
contentPane.add(Box.createRigidArea(new Dimension(0, 5)));
contentPane.add(textScroller);
contentPane.add(Box.createRigidArea(new Dimension(0, 5)));
b2.setAlignmentX(CENTER_ALIGNMENT);
contentPane.add(b2);

displayWindow.setContentPane(contentPane);
displayWindow.pack();
displayWindow.setVisible(true);
}
public void internalFrameClosing(InternalFrameEvent e) {
displayMessage("Internal frame closing", e);
}
public void internalFrameClosed(InternalFrameEvent e) {
displayMessage("Internal frame closed", e);
}
public void internalFrameOpened(InternalFrameEvent e) {
displayMessage("Internal frame opened", e);
}
public void internalFrameIconified(InternalFrameEvent e) {
displayMessage("Internal frame iconified", e);
}
public void internalFrameDeiconified(InternalFrameEvent e) {
displayMessage("Internal frame deiconified", e);
}
public void internalFrameActivated(InternalFrameEvent e) {
displayMessage("Internal frame activated", e);
}

public void internalFrameDeactivated(InternalFrameEvent e) {


displayMessage("Internal frame deactivated", e);
}
//Add some text to the text area.
void displayMessage(String prefix, InternalFrameEvent e) {
String s = prefix + ": " + e.getSource();
display.append(s + newline);
display.setCaretPosition(display.getDocument().getLength());
}
//Handle events on the two buttons.
public void actionPerformed(ActionEvent e) {
if (SHOW.equals(e.getActionCommand())) {
//They clicked the Show button.

//Create the internal frame if necessary.


if (listenedToWindow == null) {
listenedToWindow = new JInternalFrame("Event Generator",
true, //resizable
true, //closable
true, //maximizable
true); //iconifiable
//We want to reuse the internal frame, so we need to
//make it hide (instead of being disposed of, which is
//the default) when the user closes it.
listenedToWindow.setDefaultCloseOperation(
WindowConstants.HIDE_ON_CLOSE);

//Add an internal frame listener so we can see


//what internal frame events it generates.
listenedToWindow.addInternalFrameListener(this);

//And we mustn't forget to add it to the desktop pane!


desktop.add(listenedToWindow);

//Set its size and location. We'd use pack() to set the size
//if the window contained anything.
listenedToWindow.setSize(300, 100);
listenedToWindow.setLocation(
desktopWidth/2 - listenedToWindow.getWidth()/2,
desktopHeight - listenedToWindow.getHeight());
}
//Show the internal frame.
listenedToWindow.setVisible(true);

} else { //They clicked the Clear button.


display.setText("");
}
}
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);

//Create and set up the window.


JFrame frame = new InternalFrameEventDemo(
"InternalFrameEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Display the window.


frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job
createAndShowGUI();
}

}
Mouse Listener
Mouse events notify when the user uses the mouse (or similar input device) to interact
with a component. Mouse events occur when the cursor enters or exits a component's
onscreen area and when the user presses or releases one of the mouse buttons.

/*
* BlankArea.java is used by:
* MouseEventDemo.java.
* MouseMotionEventDemo.java
*/

import javax.swing.*;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Graphics;

public class BlankArea extends JLabel {


Dimension minSize = new Dimension(100, 50);

public BlankArea(Color color) {


setBackground(color);
setOpaque(true);
setBorder(BorderFactory.createLineBorder(Color.black));
}

public Dimension getMinimumSize() {


return minSize;
}

public Dimension getPreferredSize() {


return minSize;
}
}
/*
* MouseEventDemo.java
*/

import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

import javax.swing.*;

public class MouseEventDemo extends JPanel


implements MouseListener {
BlankArea blankArea;
JTextArea textArea;
static final String NEWLINE = System.getProperty("line.separator");

public static void main(String[] args) {


/* Use an appropriate Look and Feel */
try {

//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLoo
kAndFeel");
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel")
;

UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("MouseEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.


JComponent newContentPane = new MouseEventDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);

//Display the window.


frame.pack();
frame.setVisible(true);
}

public MouseEventDemo() {
super(new GridLayout(0,1));
blankArea = new BlankArea(Color.green);
add(blankArea);
textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(200, 75));
add(scrollPane);

//Register for mouse events on blankArea and the panel.


blankArea.addMouseListener(this);
addMouseListener(this);
setPreferredSize(new Dimension(450, 450));
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}

void eventOutput(String eventDescription, MouseEvent e) {


textArea.append(eventDescription + " detected on "
+ e.getComponent().getClass().getName()
+ "." + NEWLINE);
textArea.setCaretPosition(textArea.getDocument().getLength());
}

public void mousePressed(MouseEvent e) {


eventOutput("Mouse pressed (# of clicks: "
+ e.getClickCount() + ")", e);
}

public void mouseReleased(MouseEvent e) {


eventOutput("Mouse released (# of clicks: "
+ e.getClickCount() + ")", e);
}

public void mouseEntered(MouseEvent e) {


eventOutput("Mouse entered", e);
}

public void mouseExited(MouseEvent e) {


eventOutput("Mouse exited", e);
}

public void mouseClicked(MouseEvent e) {


eventOutput("Mouse clicked (# of clicks: "
+ e.getClickCount() + ")", e);
}
}
 

Java Programming 
Test Assignment 2            Due: Sat 13/2/10  
Create a class called Salaries to contain and do the following: 

1. Create 4 single dimensional arrays containing the following information: 

Names  Ages Salaries Addresses 


Ahmed Moussa  65  5500 Heliopolis,Cairo 
Hadeer Hassab  23  2000 ElHaram,Giza 
Ziad Amr  42  4000 Mohandeseen,Cairo
Maha Allenby  35  3500 Tanta,ElGharbia 
Mohamed Abdou  75  NasrCity,Cairo 
 
2. If the age of the employee is from 40 to 65, add a bonus for him of 2200 
LE, then reduce 10% from this total sum for taxes. Print out the name 
and final salary of each employee 

3. If the age of the employee is from 20 to 39, add a bonus for him of 1100 
LE, then reduce 20% from this total sum for taxes. Print out the name 
and final salary of each employee 

4. If the age of the employee is not in the above categories, then print out 
his name and say that he is not an employee 

5. Find out how many people live in Cairo and print it out ( hint: use the 
comma in your search /  You can also use e.g. array[2].length()). 

N.B. marks will be allocated for  
• suitable names of variables,  
• proper organization of coding and  
• adding comments 

 
/*
Salaries class
/*
Salaries class
*/

package salaries;
public class Main {
public static void main(String[] args) {
String[] names={"Ahmed Moussa","Hadeer Hassab","Ziad Amr","Maha Ellenby","Mohammed Abdou"} ;//names
array
int[]ages={65,23,42,35,75};//ages array
double[]salary={5500,2000,4000,3500,0};//salary array
String[]adreslocation={"Heliopolis","Elharam","Mohandseen","Tanta","Nasr city"};//location array
String[]adrescity={"Cairo","Giza","Cairo","Elgharbia","Cairo"};//citiesarray

//declaring variables
int agesi;
int empage;
String searchfor="Cairo";
System.out.println("******The Answers Of Q2, Q3 And Q4 :******");
for(agesi=0;agesi<ages.length;agesi++)
{
//any employee abpve 65 doesn't match any category
if (ages[agesi]>65)
System.out.println("Q4-"+"For "+ names[agesi]+"he is not an employee ");
// for employees above or equal 40 salary increase by 2200 having 10 % as taxes
else if (ages[agesi]>=40)
{salary[agesi]=((salary[agesi]+2200)*0.9);
System.out.println("Q2-"+"For "+ names[agesi]+" the new salary is : "+salary[agesi]);
}
//any employee above 39 doesn't match with having 40 criteria already specified
else if(ages[agesi] > 39)
System.out.println("Q4-"+"For "+ names[agesi]+"he is not an employee ");
// for employees above or equal 20 salary increase by 1100 having 20 % as taxes
else if (ages[agesi]>=20)
{salary[agesi]=((salary[agesi]+1100)*0.8);
System.out.println("Q3-"+"For "+ names[agesi]+" the new salary is : "+salary[agesi]);
}
}

//end of if statment
System.out.println(" ");
System.out.println("******The Answer Of Q5 :******");
for(agesi=0;agesi<adrescity.length;agesi++)
{if (adrescity[agesi]=="Cairo")
System.out.println("This employees lives in cairo :"+names[agesi]);
}
}
}

file:///D|/java/Assignment2.txt[1/5/2011 8:18:03 PM]


Java Programming
Test Assignment 3
Create an automated cashier application - for ordering and paying for Chinese food from a standard menu.
The application should contain 5 classes as follows (the following coding procedures can be changed):
1. Create a package called “ChineseFood” to put the classes inside it
2. An abstract superclass called “Items” containing:
a) the general attributes for any food item: name, serial number
b) constructor
c) concrete methods to set & return the name, serial number and food item object
d) abstract method to calculate the price of any chosen food item
3. A subclass called “Food” containing:
a) attribute for number of orders required by customer
b) a single dimensional array containing number of side dishes in each order taken from
customer
c) two single dimensional arrays as follows (acting as a menu) showing price of an order with
different numbers of side dishes
Number of side 1 2 3 4
dishes
Serial number F01 F02 F03 F04
price 15.99LE 20.99LE 25.99LE 30.99LE

d) constructor
e) methods to set and get number of orders required by customer and number of side orders in
each order(hint: this info should be taken from customer in an array), method to calculate
total price of number of orders (by searching in both arrays for number of required side
dishes for each order and their prices), and method to represent the food object item
4. A subclass called “Beverages” containing:
a) attribute for number of drink orders required by customer
b) a single dimensional array containing type of beverage in each order taken from customer
c) two single dimensional arrays as follows (acting as a menu) showing price of each type of
beverage
Type of Fizzy (e.g. cola) Juice Water Milkshake
beverage
Serial number B01 B02 B03 B04
price 3.99LE 5.99LE 2.99LE 6.99LE

d) constructor
e) methods to set and get number of orders required by customer and type of beverage in each
order, method to calculate total price of number of orders (by searching in both arrays for
type of beverage for each order and their prices), and method to represent the beverage
object item

5. A subclass called “Desserts” containing:


a) attribute for number of dessert orders required by customer
b) a single dimensional array containing type of dessert in each order taken from customer
c) two single dimensional arrays as follows (acting as a menu) showing price of each type of
dessert
Type of dessert Apple pie Cake Cookie Ice cream
Serial number D01 D02 D03 D04
price 5.99LE 6.99LE 3.99LE 2.99LE

d) constructor
e) methods to set and get number of orders required by customer and type of dessert in each
order, method to calculate total price of number of orders (by searching in both arrays for
type of beverage for each order and their prices), and method to represent the beverage
object item
6. A class containing the business logic as follows:

a) Give the user a dialog box asking if he wants to order food, beverage or dessert

b) Whichever he chooses, make another dialog box appear asking him how many orders

c) Then make a dialog box appear for each order which allows him to choose the type of
food/beverage/dessert he wants

d) When these are finished give him another dialog box asking if he wants to order any more
items

e) If he says yes go back to point a) again and repeat the whole procedure. If he says no output
a message box containing the name / serial number / type of each order / its price. At the
very end of the message box show the total price of all the orders together obtained from:

f) Create a method to get the total orders’ prices returned from all the other classes and add
them all up

N.B. marks will be allocated for

• suitable names of variables, methods


• proper organization of coding and
• adding comments

Good Luck
what does java virtual machine do

how to write an interface and abstract class - public or private methods ?

why package, import, main method and methods

why use constructor

why use layouts, give me an example

how create an array, what positions exist in it

difference between 0 and null

difference between = , == and .equals

difference between x+(++y) and x+(y++)

what is *, /, %, &&, ||, !

can we use % with double

what does this mean z= x>y? 1: 10

difference between break; continue; return; and break() continue() return()

switch must have default case and break?

can you instantiate an object from abstract and interface classes?

can you have a constructor in abstract and interface classes?

a subclass of an abstract class must define its methods?

characteristics of an array

input arguments are passed to methods by reference or value

meaning of public/private/protected/no access modifier/final/static

what are keywords, case sensitive

extend and implement how many classes (multiple inheritance)

what is overriding, overloading, polymorphism (methods with same name in same class and superclass)

idea of IF statement

examples of code: arrays / for loops (nested) / while, continue , break / =,==,++, % /
types of variables / simple casting / &&, || / unreachable, non logic code

You might also like