0% found this document useful (0 votes)
12 views

Java Programming Handout for Btech

This document outlines a course on Object-Oriented Programming (OOP) with Java, targeting students with minimal programming experience. It covers essential Java concepts, including program structure, syntax, data types, flow control, and OOP principles, along with practical applications such as database connectivity and GUI development. The course aims to equip students with the skills to write, compile, and execute Java programs using various development environments.

Uploaded by

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

Java Programming Handout for Btech

This document outlines a course on Object-Oriented Programming (OOP) with Java, targeting students with minimal programming experience. It covers essential Java concepts, including program structure, syntax, data types, flow control, and OOP principles, along with practical applications such as database connectivity and GUI development. The course aims to equip students with the skills to write, compile, and execute Java programs using various development environments.

Uploaded by

Big Fabiano
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

OBJECT ORIENTED

PROGRAMMING WITH
JAVA
BACHELOR

FECKOUNDO TCHINDA FABRICE SOFTWARE ENGINEER


Objectives
This course offers an introduction to the Java programming language for students who have had little
background in programming. Toward this goal students will learn how to:
- Write programs using the Java language. Basic topics considered are the following: java program
structure, Java syntax, data types, flow of control, classes, arrays, exception handling, recursion,
Database connectivity (JDBC), Basic Socket Programming and graphical user interfaces (GUIs).
- Compile and execute them under the Sun Microsystems, Inc. Java 2 Platform, Standard Edition,
or other Integrated Development Environments (IDEs) such as NetBeans.
- Implement various Object-Oriented concepts studied

Table of Contents
1 General Introduction on Object Oriented Programming ..................................................................................... 3
1.1 Benefits of OOP ............................................................................................................................................... 3
1.2 Features of OOP .............................................................................................................................................. 4
1.3 OOP Languages ............................................................................................................................................... 4
1.4 Applications of OOP ........................................................................................................................................ 5
2. INTRODUCTION TO JAVA PROGRAMMING.......................................................................................................... 6
2.1 What is java? ................................................................................................................................................... 6
2.2 Java Features................................................................................................................................................... 7
2.3 Types of java programs ................................................................................................................................... 8
2.4 Java Development Tools ................................................................................................................................. 8
a) The Java Development Kit (JDK)................................................................................................................... 8
b) Java Development Environments ................................................................................................................ 8
2.5 Basic Java Language Elements ........................................................................................................................ 9
a) Comments ..................................................................................................................................................... 9
B) Standard primitive types in Java .................................................................................................................. 9
C) Operators .................................................................................................................................................... 10
D) Variable Declarations ................................................................................................................................. 10
E) Constants..................................................................................................................................................... 10
2.6 Object Oriented Concepts ........................................................................................................................... 10
2.6.1 Classes and Objects................................................................................................................................ 10
2.6.2 Some java OOP terminalogies ............................................................................................................... 11
2.6.3 Access Modifiers .................................................................................................................................... 12
2.6.4 Inheritance ............................................................................................................................................. 12
2.6.5 Data Abstraction and Encapsulation ..................................................................................................... 14
2.6.6 Constructor Chaining ............................................................................................................................ 15

1|Page
2.6.7 Polyorphism ........................................................................................................................................... 16
2.6.8 Abstract Methods And Classes .............................................................................................................. 17
2.6.9 Interfaces ............................................................................................................................................... 18
2.6.10 Differences Between Interfaces and Abstract Classes ....................................................................... 18
2.6.11 Why Are Interfaces Important?........................................................................................................... 18
2.6.12 Packages and import statement ......................................................................................................... 19
2.7 Flow Controls ............................................................................................................................................ 19
2.8 Input And Output ..................................................................................................................................... 21
2.9 Data Conversion Functions ....................................................................................................................... 22
2.10 Java Exception Handling ......................................................................................................................... 23
2.11 Arrays ...................................................................................................................................................... 26
3. Java And Database ............................................................................................................................................. 30
3.1 Why Should We Use JDBC ............................................................................................................................ 30
3.2 Pre-Requisite ................................................................................................................................................. 30
3.3 Interfaces And Classes Provided By The JDBC ............................................................................................. 30
3.3.1 Commonly used methods of Statement interface: ............................................................................. 31
3.3.2 Commonly used methods of ResultSet interface ................................................................................. 31
3.3.3 Methods of PreparedStatement interface............................................................................................ 32
3.4 Connecting To A MySql Database ................................................................................................................ 33
3.5 Creating A Database ..................................................................................................................................... 33
3.6 Creating A Table In The Database ................................................................................................................ 34
3.7 Inserting Data Into A Table (Simple Method) .............................................................................................. 34
3.8 Inserting Data Into A Table Using Prepared Statements ............................................................................. 35
3.9 Selecting Data From The Table Using The Table Header ............................................................................. 35
3.10 Selecting Data From The Table Using The Table Index .............................................................................. 36
TUTORIALS............................................................................................................................................................... 37

2|Page
1 General Introduction on Object Oriented Programming
With the advent of languages such as c, structured programming became very popular and was
the main technique of the 1980’s. Structured programming was a powerful tool that enabled
programmers to write moderately complex programs fairly easily. However, as the programs grew
larger, even the structured approach failed to show the desired result in terms of bug-free, easy-
to-maintain, and reusable programs. Object Oriented Programming (OOP) is an approach to
program organization and development that attempts to eliminate some of the pitfalls of
conventional programming methods by incorporating the best of structured programming features
with several powerful new concepts. It is a new way of organizing and developing programs and
has nothing to do with any language. However, not all languages are suitable to implement the
OOP concepts easily.

1.1 Benefits of OOP


OOP offers several benefits to both the program designer and the user. Object Orientation
contributes to the solution of many problems associated with the development and quality of
software products. The new technology promises greater programmer productivity, better quality
of software and lesser maintenance cost. The principal advantages are:
 It is possible to map object in the problem domain to those in the program.
 It is easy to partition the work in a project based on objects.
 The data-centered design approach enables us to capture more detail of a model can implemental form.
 Object-oriented system can be easily upgraded from small to large system.
 Message passing techniques for communication between objects makes to interface descriptions with
external systems much simpler.
 Software complexity can be easily managed.
 Through inheritance, we can eliminate redundant code extend the use of existing Classes.
 We can build programs from the standard working modules that communicate with one another, rather
than having to start writing the code from scratch. This leads to saving of development time and higher
productivity.
 The principle of data hiding helps the programmer to build secure program that cannot be invaded by
code in other parts of a programs.
 It is possible to have multiple instances of an object to co-exist without any interference.

While it is possible to incorporate all these features in an object-oriented system, their importance
depends on the type of the project and the preference of the programmer. There are a few issues
that need to be tackled to reap some of the benefits stated above. For instance, object libraries
must be available for reuse. The technology is still developing and current product may be

3|Page
superseded quickly. Strict controls and protocols need to be developed if reuse is not to be
compromised.

1.2 Features of OOP


 Emphasis is on data rather than procedure.
 Programs are divided into what are known as objects.
 Data structures are designed such that they characterize the objects.
 Functions that operate on the data of an object are ties together in the data structure.
 Data is hidden and cannot be accessed by external function.
 Objects may communicate with each other through function.
 New data and functions can be easily added whenever necessary.
 Follows bottom-up approach in program design.
1.3 OOP Languages
Object-oriented programming is not the right of any programming language. Like structured
programming, OOP concepts can be implemented using languages such as C and Pascal. However,
programming becomes clumsy and may generate confusion when the programs grow large. A
language that is specially id designed to support the OOP concepts makes it easier to implement
them.

The languages should support several of the OOP concepts to claim that they are object-
oriented. Depending upon the features they support, they can be classified into the following two
categories:

1. Object-based programming languages, and

2. Object-oriented programming languages.

Object-based programming is the style of programming that primarily supports encapsulation


and object identity. Major feature that are required for object-based programming are:
 Data encapsulation
 Data hiding and access mechanisms
 Automatic initialization and clear-up of objects
 Operator overloading
Languages that support programming with objects are said to the objects-based programming
languages. They do not support inheritance and dynamic binding. Ada is a typical object-based
programming language.

Object-oriented programming language incorporates all of object-based


programming features along with two additional features, namely, inheritance and dynamic binding.
Object-oriented programming can therefore be characterized by the following statements:

4|Page
1.4 Applications of OOP
OOP has become one of the programming buzzwords today. There appears to be a great deal
of excitement and interest among software engineers in using OOP. Applications of OOP are
beginning to gain importance in many areas. The most popular application of objectoriented
programming, up to now, has been in the area of user interface design such as window. Hundreds
of windowing systems have been developed, using the OOP techniques.

Real-business system are often much more complex and contain many more objects with
complicated attributes and method. OOP is useful in these types of application because it can
simplify a complex problem. The promising areas of application of OOP include:

 Real-time system
 Simulation and modeling
 Object-oriented data bases
 Hypertext and Hypermedia
 AI and expert systems
 Neural networks and parallel programming
 Decision support and office automation systems
 CAM/CAD systems

5|Page
2. INTRODUCTION TO JAVA PROGRAMMING
2.1 What is java?
Java is an Object-Oriented Programming Language developed by Sun Microsystems, similar to
C and C++, except without some of the confusing, poorly understood features of C++ (operator
overloading, pointers). It is a new way of organizing and developing programs and has nothing to
do with any particular language. However, not all languages are suitable to implement the OOP
concepts easily.

This course presents the main OOP concepts then study it use in some OOP languages like
JAVA, C++ and PHP.
At its first release, Java primarily was used as a language for writing applications to be
embedded in browsers (known as applets), but it has grown into many other areas (Applications
for server and enterprise computers, desktop computers, mobile phones …). Today, thousands of
programmers, Internet developers, Web publishers, and software houses are making use of Java.
Java includes three main platforms:
 Java Standard Edition (JSE): for desktop computers
 Java Mobile Edition (JME): it is the Java platform for consumer and embedded devices
such as mobile phones and personal organizers.
 Java Enterprise Edition (JEE):for servers and enterprise computers.
Java encompasses several distinct components:
- A high-level language: source code at a glance looks very similar to C and C ++ but is unique
in many ways. (The source file extension is “.java”)
- Java byte-code: A compiler transforms the Java language source code to files of binary
instructions and data called byte-code that run in the Java Virtual Machine.

6|Page
- Java Virtual Machine (JVM): It is a program that takes byte-code as input and interprets the
instructions just as if it were a physical processor executing machine code. The figure below
illustrates how a java program is compiled and run.

2.2 Java Features


 Compiler/interpreter combination
The source code is compiled to byte-code, which is interpreted by a Java Virtual Machine
(JVM). This provides portability and security to any base operating system platform for which a
virtual machine has been written.
 Garbage collection
Garbage collection means that there is an automatic functionality that regularly goes through
the object space and checks which objects are still referenced and which are not. Those which are
no longer referenced are unusable for the program, so it is safe to liberate the space they use. In
Java, there is no “delete” keyword, since a garbage collector in the JVM takes care of allocating
and reclaiming memory.
 Several drawbacks of C and C ++ eliminated - No accessible memory pointers, no
preprocessor.
- Array limits automatically checked.
- No operator overloading in Java.
 Multiple inheritance replaced by interfaces (Eliminates complexities of multiple
inheritance)
 Object-oriented
- Object-oriented programming (OOP) throughout – no coding outside of class
definitions.
 Robustness
- Exception handling built-in, strong type checking (that is, all variables must be assigned
an explicit data type), local variables must be initialized.
 Platform independence
- The byte-code runs on any platform with a compatible JVM.
- The “Write Once Run Anywhere” ideal has not been achieved (tuning for different
platforms usually required), but is closer than with other languages
- Portable: Write Once, Run Anywhere

7|Page
These features provide a number of benefits compared to program development in other
languages. For example, C/C++ programs are beset by bugs resulting from direct memory pointers,
which are eliminated in Java. Similarly, the array limit checking prevents another common source
of bugs. The garbage collector relieves the programmer of the big job of memory management.
It’s often said that these features lead to a significant speedup in program development and
debugging compared to working with C/C ++.

2.3 Types of java programs


• Application: Standalone Java program that can run independent of any Web browser
• Applet: Java program that runs within a Java-enabled Web browser
• Servlet: Java software that is loaded into a Web server to provide additional server
functionality alike CGI programs. (CGI=Common Gateway Interface. It’s a technique that
allows a client to run a specific program on a server)
2.4 Java Development Tools
a) The Java Development Kit (JDK)
The Java Development Kit (JDK) is the minimal file you need to develop in Java. The version
that is meant for the Windows environment contains an automatic installer that takes care of the
installation. Only setting up the Windows PATH may require some manual intervention.
The JDK contains many base tools:
javac: The Java Language Compiler that used to compile programs written in the Java
Programming Language into byte-codes.
Java: The Java Interpreter used to run programs written in Java.
JRE: The Java Runtime Interpreter that can be used to run Java applications. The jre tool is similar
to the java tool, but is intended primarily for end users who do not require all the development
related options available with the java tool.
Applet viewer: It is used to run applets without a web browser. jar:
Combines multiple files into a single Java Archive (JAR) file.

b) Java Development Environments


There are many java development environments: NetBeans, Eclipse, JBuilder, JDeveloper…
Example of java program
o Create source file (on any text editor):

8|Page
Hello.java
o Type the code below and save:
public class Hello { public static void main
(String args[]) {
System.out.println("Hello World!");
}
}

o Compile: javac Hello.java


o Run: java Hello (This last command will start up the JVM)
2.5 Basic Java Language Elements
Java syntax is very close to that of "C" and C++. This is true for Comments, variable names
and declarations and initializations, control flow (if, else, for, while) etc.

a) Comments
Type of comments Examples
//Single line comment
Line comment int cpt = 1//Counter
/* First line comment
Block comment
Second line comment*/
/**
*This subroutine computes the *area of a
rectangle
Automatic documentation comment *@param width the length of one *@param
height the length
*@return the area of the rectangle
*/

B) Standard primitive types in Java


boolean true or false
char 16-bit character, coded using Unicode 1.1.5
byte 8 bit signed integer ( -128 to +127)
short 16 bit signed integer (-32,768 to 32,767)
int 32 bit signed integer (-2.15E+9 to +2.15E+9)
long 64 bit signed integer (-4.61E+18 to +4.61E+18)
float floating point real number (1.0E-38 to
9|Page
1.0E+38) double floating point real number (-1.0E-
308 to 1.0E+308)

C) Operators
They are similar to C++ operator. However they are few differences:
 “+” can be usedto concatenate strings
 “instanceof” returns true or false depending on whether the left side object is an instance
of the right side object
 “>>>” shifts bits right, filling with zeros
D) Variable Declarations
Variable declarations consist of three parts: modifiers, followed by a type , followed by a list
of identifiers. The modifiers are optional, but the type and list of identifiers is not.
Example :
public int a, b, c; // "public" is a modifier
E) Constants
In C++, constants are defined using const or #define. In java they are defined through the
combination of “final” and “static”.
Syntax: public final <static><datatype><name> = <value>;
Example: public final static double PI = 3.14;
public final static int NumStudents = 60;

2.6 Object Oriented Concepts


2.6.1 Classes and Objects
A class is a collection of data (attributes) and methods that operate on that data, “In Java,
everything is a class”( that is classes provided by java and those that you write). Once a class has
been defined, we can create any number of objects belonging to that class. Each object is associated
with the data of type class with which they are created. A class is thus a collection of objects similar
types. For examples, Mango, Apple and orange members of class fruit. Classes are user-defined
that types and behave like the built-in types of a programming language. Example: we can create
an object mango belonging to the class fruit.
• All classes are derived from a single root class called Object.
• Every class (except Object) has exactly one immediate super class.

10 | P a g e
• Only single inheritance is supported
Objects are instances of a class. They are created with the “new” keyword, which returns a
reference to an object that represents an instance of the class. An object-oriented program consists
of a set of objects that communicate with each other.
The process of programming in an object-oriented language, involves the following basic steps:
1. Creating classes that define object and their behavior,
2. Creating objects from class definitions, and
3. Establishing communication among objects.
2.6.2 Some java OOP terminologies
- Member: either an attribute or a method of a class
- Object: an instance of a class. They may represent a person, a place, a bank account, a
table of data or any item that the program has to handle.
- Constructor: method that performs object initialization (not creation!)
- Object Reference: variable that holds a reference to (really the memory address of) an
object
- Instance Variable: attribute for which each object (instance) has its own copy
- Class Variable: attribute for which there is only one copy for the class. Each object
(instance) shares this copy. It is also called static variable
- Instance Method: method which operates on the attributes of an object (instance)
- Class Method: method which does not operate on a particular object, but performs some
utility function or operates on static variables. it is also called static method.
- Method Signature: the number, type and order of arguments of a method
- Method Overloading: defining a method with the same name but different
signature(number and type of parameter) as another method in the same class

class Adder
{
int add(int i, int j) {
return i + j;
}
double add(double i, double j) {
return i + j;
}
}

11 | P a g e
2.6.3 Access Modifiers
There are three access modifiers which can define the visibility of attributes, methods and
classes: public, private, protected.
Public: It indicates that a member or class is accessible anywhere by anyone.(In the philosophy of OOP,
attributes should not be declared public. It is preferable to use “getter” and “setter”)

Private: This modifier indicates that attributes and methods are accessible only from within the class where
they are declared. It is used for the internal operations of the object. This is called encapsulation in OOP.

Protected: When protected is applied as an access modifier to a member in a class, that member can be
used in subclasses of the class in which it is defined, but it cannot be used in non-subclasses. There is an
exception: A protected member can also be accessed by any class in the same package as the class that
contains the protected member.

Unspecified: If none of modifiers given above are used, the member has the default visibility or "package"
visibility.

2.6.4 Inheritance
The term inheritance refers to the fact that one class can inherit part or all of its structure and
behavior from another class(This mechanism ensures scalability and re-usability of the code).

12 | P a g e
Java supports single inheritance using the “extends” keyword as follow: public class B extends
A. Here, “A” is called the superclass and “B” the subclass.
• A subclass can override a method in its superclass by providing a new definition for a
method with the same name, return type and signature.
• All classes implicitly extend the Object class.
• A protected member of a class can be accessed by any method in the same class or a
subclass.
(It can also be access by any method in a class in the same package)
• Inside a method, the keyword “this” represents the current object, while “super” is a
variable that contains a reference of the current object’s super class.

Inheritance example

13 | P a g e
public class ABTest {
public static void
// A is the superclass public main(String[] argv) {
class A { //Polymorphism
protected int aData; A a = new A();
public A(int aData) B b = new B();
{this.aData =aData;} a. f(); // Invokes A's f()
public A() {aData = 0;} b. f();// Invokes B's f() A a1 =
b;
protected void f() {
a1.f(); // Invokes B's f()
System.out.println("This is A's // Up Casting
f"); } A a2 = (A) b; // Ok
}
// B is the subclass public // Down Casting
class B extends A { //B b1 = a; // Illegal at
protected int bData; public
//compile time,
B(int bData) {this.bData =
// explicit cast needed
bData;} public B()
{this(0);} protected void //B b2 = (B) a; // Ok at
f() { //compile time,
System.out.println("This is B's // exception at run time
f"); } // Other stuff
protected void g() { int i = a.aData; /* Ok, same package*/
System.out.println("This is B's //i = a.bData; /* Illegal at
g"); compile time */
} //bData not defined in A
} //a.g();
// Illegal at compile time,
// g() not found in A
}
}

2.6.5 Data Abstraction and Encapsulation


The wrapping up of data and function into a single unit (called class) is known as
encapsulation. Data and encapsulation is the most striking feature of a class. The data is not
accessible to the outside world, and only those functions which are wrapped in the class can access
it. These functions provide the interface between the object’s data and the program. This insulation
of the data from direct access by the program is called data hiding or information hiding.
Abstraction refers to the act of representing essential features without including the
background details or explanation. Classes use the concept of abstraction and are defined as a list
of abstract attributes such as size, wait, and cost, and function operate on these attributes. They
encapsulate all the essential properties of the object that are to be created.
14 | P a g e
The attributes are sometime called data members because they hold information. The functions
that operate on these data are sometimes called methods or member function.
2.6.6 Constructor Chaining
Java always invokes a superclass constructor when a subclass object is created (since the
superclass object is “part of” the subclass object). It is possible to explicitly call a superclass
constructor using a call to super(…) as the first line of a subclass constructor:
public B(int b) { super(); // Explicit call of superclass constructor
this.b = b;
}

If the superclass constructor isn’t explicitly invoked, then the no-arguments superclass
constructor is implicitly called for you. That is, Java inserts the call to "super()" automatically.
But, if the superclass constructors is defined while the no-argument one is not given, then
it is necessary to call the superclass constructor in the first line of the subclass constructor.
Superclass display Subclass
class Pointcol extends Point
class Point
{ public Pointcol (int x, int
{ public Point (int x, int y)
y, byte color)
{
{
this.x = x ; this.y = y ;
super (x, y) ; // must be the
}
//first instruction
public void move(int dx, int dy)
this.color = color ;
{ x += dx ;
} public void
y += dy ;
display()
}
{ super. display() ;
public void display() {
System.out.println ("and my
System.out.println (" my
color is: " + color) ;
position is " + x + " " + y) ;
} private byte
} private int x,
color ;
y;
}
}

However, If the first line of a constructor uses the "this(…)" syntax to invoke another
constructor of the class, then Java does not automatically insert the call to "super()" in the
constructor:
public B() {
this(0); // Call to super() not automatically inserted here.
}

15 | P a g e
2.6.7 Polymorphism
In programming languages, polymorphism is the capability of an action or method to perform
an action based on the object that it is acting upon. The three types of polymorphism are: method
overloading, method overriding, and dynamic method binding.
Overloaded methods are methods with the same name but either a different number of
parameters or different types in the parameter list.
Overridden methods are methods that are redefined within an inherited or subclass. They have
the same signature and the subclass definition is used.
Dynamic (or late) method binding is the ability of a program to resolve references to subclass
methods at runtime. An example of dynamic binding is given below.
class Point public class Poly
{ public Point (int x, int { public static void main (String args[])
y) {
{ this.x = x ; this.y System.out.println(“First
=y; Test”); Point p = new Point (3,
} public void move(int dx, 5) ; p. display() ;
int dy) // calls display() of Point
{ x += dx ; y += Pointcol pc = new
dy ; Pointcol (4, 8, (byte)2)
} public void ; p = pc ; // p references an
display() // instance of Pointcol p. display()
{ ;
System.out.println("my position // calls display() of Pointcol
is " + x + " " + y) ; p = new Point (5, 7) ;
} private int x, // p now references an
y; //instance of Point p.display()
} ;
// calls display() of Point
System.out.println(“Second Test”);

16 | P a g e
class Pointcol extends Point Point [] tabPts = new Point [4] ;
{ public Pointcol (int x, int tabPts [0] = new Point (0, 2) ; tabPts
y, byte color) [1] = new
{ Pointcol (1, 5, (byte)3) ;
super (x, y) ; /* must be the tabPts [2] = new
first instruction*/ Pointcol (2, 8, (byte)9)
this.color = color ; ; tabPts [3] = new Point (1, 2)
} public void ; for (int i=0 ; i<
display() tabPts.length ; i++)
{ tabPts[i].display() ;
super. display() ; }
System.out.print ("and my color }
is: " + color) ; Output
} private byte First Test my
color ; position is 3 5 my
position is 4 8
}
and my color is:
2 my position is 5
7 Second Test
my position is 0 2
my position is 1 5
and my color is:
3 my position is 2
8 and my color
is: 9 my position
is 1 2

2.6.8 Abstract Methods And Classes


An abstract method has no body. It is like a pure virtual function in C++. The abstract method
is expected to be overridden in a subclass with an actual implementation.
Any class with an abstract method is an abstract class and must be declared abstract. An abstract
class cannot be instantiated. Also, if a subclass of an abstract class does not provide
implementations for all of the abstract methods of its superclass, then the subclass itself is
abstract.

17 | P a g e
// Class Shape is an abstract base class for a public void renderScreen(Drawable d) {
geometric shape. // Render this Drawable on the screen.
public abstract class Shape { public abstract // It does not matter whether this is
DrawableRectangle, // DrawableCircle, etc. Since the
double area(); //area() has no body
object is a Drawable, it // MUST implement the Draw
} method. d.Draw();
// Class Rectangle is a concrete implementation of a
Shape.
}
public class Rectangle extends Shape
{ protected double w; protected double
h;
public Rectangle(double w, double h) {
this.w = w;
this.h = h;
}
public double area() { return (w * h); }
} 2.6.9 Interfaces
In Java, an interface is a specification of a set of
abstract methods.
 A class that implements the interface must provide an implementation for all of the
abstract methods in the interface.
 A class can implement many interfaces, but a class can only extend one class

// Interface Drawable provides the specification for a


drawable // graphics object. public interface Drawable {
public void Draw();
}
// Class DrawableRectangle implements the Drawable interface. public class
DrawableRectangle extends Rectangle implements Drawable { // Other
code here. public void Draw() {
// Body of Draw()
}
}

2.6.10 Differences Between Interfaces and Abstract Classes


 An abstract class can have non-abstract methods, while all methods of an interface are
implicitly (or explicitly) abstract.
 An abstract class can declare instance variables; an interface can not
 An abstract class can have a user-defined constructor, while an interface has no
constructors
 Every method of an interface is implicitly (or explicitly) public; an abstract class can have
non-public methods.
2.6.11 Why Are Interfaces Important?
An object's type essentially refers to the OO interface of its class. Then in Java, an object
of a class that implements several interfaces has many types. Also, objects from many different
18 | P a g e
classes can have the same type. This allows to write methods that can work on objects from many
different classes which can even be in different inheritance hierarchies.

2.6.12 Packages and import statement


Java classes can be grouped together into a package. Packages have several advantages:
- related classes can be grouped together (implies modularity)
- members can be accessible only to methods of classes in the same package
Rules
- The package statement must appear as the first statement of the Java source file:
packagein3;
(If no package statement is present, the code is made part of the unnamed default package) -
A fully qualified Java name for a class is:
<Package Name>.<Class Name> Example:in3.Polymorphism.Point

The import statement allows the use of abbreviated class names in a Java source file. Classes are
always available via their fully-qualified names: in3.Polymorphism.Point p = new
in3.Polymorphism.Point();
By using the “import” statement, the previous code is abbreviated as follow:
in3.Polymorphism.Point;
Point p = new Point();
It is possible to import all of the classes of a package using the following form of the import
statement:
import java.util.*;
(This imports all of the classes in the java.util package)

2.7 Flow Controls


 If statement

19 | P a g e
Example:
if (x < y && x < z) {//Assume x, y and z are integers
System.out.println (“followed by y and z in their correct order”);
}
else if (x > y && x > z) {
System.out.println (“output y and z in their correct order, followed by x”);
}
else {
System.out.println (“output x in between y and z in their correct order”);
}

 The for statement


Syntax Example
class ForDemo { public static
void main(String[] args){
for(int i=1; i<11; i++){
for (initialization; termination; increment) {
System.out.println("Count is: " + i);
statement(s);
}
}
}
}

 The while and do-while statements


Statement Example
class WhileDemo { public static void
main(String[] args){ int count = 1;
while (count < 11) {
While
System.out.println("Count is: " + count);
While (conditionTrue){
count++;
Statement(s);
}
}
}
}

class DoWhileDemo {
Do-while
public static void main(String[]
do{
args){ int count = 1; do {
Statement(s);
System.out.println("Count is: "+ count);
}while(conditionTrue);

20 | P a g e
count++;
} while (count < 11);
}
}

 Switch
Syntax Example
switch (<expression>) { switch ( N ) {
case <constant-1>: // Assume N is an integer case
<statements-1> break; 0:
case<constant-2>: System.out.println("The number is 1.");
<statements-2> break; break; case 1: case 2:
. System.out.println("The number is 1or
. // (more cases) 2."); break; case 3: case 4:
. case<constant-N>: System.out.println("The number is 3or 4.");
<statements-N> break; break; default:
default: // optional default System.out.println(" N>= 5."); }
case
<statements-(N+1)>
} // end of switch statement

2.8 Input And Output


To get input from the user, we use the Scanner class and it is found in the java.util package. To use
the Scanner class, create an object of the class and use any of the available methods found in the
Scanner class documentation. We need to first import the class by using the import
java.util.Scanner; Below are some methods found in the Scanner class.

Method Description
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user

21 | P a g e
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextShort() Reads a short value from the user

Example 1: Scanner with Integer values


int n;
Scanner sc = new Scanner(System.in); System.out.print("Enter a number"); n = sc.nextInt();
System.out.println("You entered "+n);

Example 2: Scanner with String values


String name;
Scanner sc = new Scanner(System.in); System.out.print("Enter your name"); name =
sc.nextLine();
System.out.println("Your name is "+name);

Example 3: Scanner with Doubles and Floats


double n; float k;
Scanner sc = new Scanner(System.in); System.out.print("Enter value for n"); n =
sc.nextDouble();
System.out.print("Enter value for k"); k = sc.nextFloat();
System.out.println("N "+n);
System.out.println("K "+k);

Exercise 1: Write a Java program to ask a user to enter a number N and calculates the sum of all
numbers from 1 to n.
Exercise 2: Write a calculator program that will receive 2 numbers from the user and ask the
user to select an operation from a list of operations (Add, Subtract, Divide and Multiply) and
performs the operation and displays the answer.
Using these is illustrated by the following example:
2.9 Data Conversion Functions
Java contains a robust set of classes to convert from one data type to another
Classes Example of conversion
Long String str1 = “488890001”;
long l = Long.parseLon(str1) ; // l=488890001 ;
Interger String str2 = “32776”;
int n = Interger.parseIn(str2) ; // n=32776
Float String str3 = “12.3”;
float f = Float.parseFloat(str3); // f=12.3

22 | P a g e
Double String str4 = “1.5”;
double d = Double.parseDouble(str4) ; // d = 1.5
Boolean String str5 = “true”
Boolean bool = Boolean.parseBoolean(str5); // bool = true

2.10 Java Exception Handling


An exception is an object that defines an unusual or erroneous situation. It is thrown by a
program or a runtime environment and can be caught and handled appropriately. Java supports
user-defined and predefined exceptions (ArithmeticException,
ArrayIndexOutOfBoundsException, FileNotFoundException, InstantiationException).
Exception handling allows a programmer to divide a program into a normal execution flow and
an exception execution flow. If an exception is not handled the program will terminate
(abnormally) and produce a message.
Example :
public class DivideBy0 {
public static void main (String[] args) {
System.out.println(10 / 0);

}
}
Outpout :
(Java.lang.ArithmeticException: / by zero at
DivdeBy0.main(DivdeBy0:3))

Try and Catch statements


Syntaxe Exemple

23 | P a g e
public class ExceptionExample {
public static void main(String arg []){
int n;
Scanner sc = new Scanner (System.in));
System.out.println("Enter an integer: "); try{
n = Integer.parseInt(sc.nextInt());
try {
System.out.println("You enter: "+n);
statement-list1
}catch(IOException e1){
} catch (exception-class1
System.out.println("IOException occurs");
variable1) { statement-list2
}
} catch (exception-class2
catch(NumberFormatException e2){
variable2) { statement-list3
System.out.println("You must enter an
} catch …. interger"); e2.printStackTrace();
}
}
}

If an exception is thrown in statement-list1, control is transferred to the appropriate catch


handler. After executing the statements in the catch clause, control transfers to the statement after
the entire try statement.
Exception Propagation
If an exception is not caught and handled where it occurs, it propagates to the calling method.
class Exception_Scope {
public void L3 ( ) {
System.out.println("Level3 beginning");
System.out.println(10/0);
System.out.println("Level3 ending");
}
public void L2 ( ) {
System.out.println("Level2 beginning");
L3( );
System.out.println("Level2 ending");

24 | P a g e
}
public void L1 ( ) {
System.out.println("Level1 beginning");
try { L2 ();
} catch (ArithmeticException problem) {
System.out.println(problem.getMessage( ));
System.out.println();
problem.printStackTrace ( );
}
System.out.println("Level1 ending");
}
} class
Demo {
public static void main (String[] args) {
Exception_Scope demo = new Exception_Scope();
System.out.println("Program beginning");
demo.L1( );
System.out.println("Program ending");
}
}
[Give the output after running this pseudocode]
Throwing an Exception
Example of method solving quadratic equation(A*x*x + B*x + C = 0)
static public double root( double A, double B, double C )
throwsIllegalArgumentException { if
(A == 0) {
throw new IllegalArgumentException("A can’t be zero.");
}
else {
double disc = B*B - 4*A*C;

if (disc < 0)

throw new IllegalArgumentException("Discriminant < zero.");

return (-B + Math.sqrt(disc)) / (2*A);

Finally clause
A try statement may have a finally clause. The finally clause defines a section of code that is
executed regardless of how the try block in executed.
25 | P a g e
try { statement-list1
} catch (exception-class1 variable1) { statement-
list2
….
} catch{ statement-listN}
} finally { statement-list //Always execute this
code. }

2.11 Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables
for each value. To declare an array, define the variable type with square brackets: Below is the
definition of an array.
dataType[] arrayName; dataType arrayRefVar[]; //
works but not preferred way.

Example:
double[] data;
String[] cars; int[]
numbers;

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


int[] numbers = {10, 20, 30, 40}; double[] cars =
{6.8,9.0,5.4,5.8};

Another way of creating an array is:

dataType[] arrayVar = new dataType[size]; where size is the size of the array.

String[] cars = new String[10];

2.11.1 Arrays With For Loop


When processing array elements, we often use either for loop or foreach loop because all of the
elements in an array are of the same type and the size of the array is known. An array index starts
at 0 and ends at n-1 where n is the size of the array. To know the length of an array, we use
arrayVar.length;. You can get any array element by using the arrayVar[arrayIndex];
26 | P a g e
Example: Let us consider the cars array
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; int
i;
for(i=0;i<cars.length;i++){ System.out.println(cars[i]);
}

Example: Let us consider the numbers array, we want to calculate the sum of all the numbers
int[] numbers = {10, 20, 30, 40};
int i, sum=0; for(i=0;
i<numbers.length;i++){ sum = sum+numbers[i];
}
System.out.println("Sum is "+sum);
}

2.11.2 Arrays With For Each Loop


The "for-each" loop is used exclusively to loop through elements in arrays. The syntax is as
follows:

for (datatype variableType : arrayName) {


...
}
Example: Let us consider the cars example once again

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for(String n:cars){ System.out.println(n);
}

Example: Let us consider the numbers array, we want to calculate the sum of all the numbers

27 | P a g e
int[] numbers = {10, 20, 30,
40}; int sum=0; for(int i:
numbers){ sum = sum+i;
}
System.out.println("Sum is "+sum);
}

Exercise 1: Write a Java program to calculate the average of numbers entered by a user.

Exercise 2: Write a Java program to find the largest and smallest of a series of numbers entered by
the user.

Exercise 3: Implement the following Algorithms using Arrays in Java:

Binary Search Algorithm , Sequential Search, Bubble Sort

2.11.3 Multidimension Arrays


It is an array in which data is stored in row and column (also known as matrix form). A
multidimensional array is an array containing one or more arrays. To create a two-dimensional
array, add each array within its own set of curly braces: dataType[][] arrayVar; int[][] numbers =
{ {1, 2, 3, 4}, {5, 6, 7} }; //2x2 array int[][] numbers2 = { {1, 2, 3, 4}, {5, 6, 7}, {8,9,0} }; //3x3
array

Example: Displaying a Matrix


int[][] numbers = {{1,2,3},{4,5,6}}; int
i, j;
for(i=0;i<3;i++){ for(j=0;j<3;j++){
System.out.print(numbers[i][j]+" ");
}
System.out.println();
}
Exercise 4: Write a Java program to display a matrix of the size nxm where the user enters all the
elements of the matrix and the size of the matrix.

28 | P a g e
Exercise 5: Write a Java program to calculate and display the sum and difference of 2 matrices
entered by the user.

Exercise 6: Write a Java program to calculate and display the product of 2 matrices A and B.

29 | P a g e
3. Java And Database
To connect to the database using Java, we can use the JDBC. JDBC Stands for Java Database
Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a part
of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database.
We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API,
we can save, update, delete and fetch data from the database. The java.sql package is used when using the
JDBC as it contains classes and interfaces for JDBC API.

3.1 Why Should We Use JDBC


We can use JDBC API to handle database using Java program and can perform the following
activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

3.2 Pre-Requisite
Before moving further, you need to have a good understanding of the following two subjects −
• Core JAVA Programming
• SQL or MySQL Database (PHPMYADMIN)
• Writing SQL Queries
3.3 Interfaces And Classes Provided By The JDBC
The JDBC API provides the following interfaces and classes −

• DriverManager: This class manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication sub protocol. The first
driver that recognizes a certain subprotocol under JDBC will be used to establish a database
Connection. The url can be as follows:
jdbc:mysql://localhost:3306/database_name where 3306 is the MySQL port OR

DriverManager.getConnection("jdbc:mysql://localhost/java","usernm","passwd"); Some

of the methods in this class includes:

a) getConnection(String url): is used to establish the connection with the specified url.

b) getConnection(String url, String username, String password) : is used to establish the

connection with the specified url, username and password.

c) getDriver(String url)
30 | P a g e
• Driver: This interface handles the communications with the database server. You will interact
directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages
objects of this type.
• Connection: This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection
object only. It is imported using import java.sql.Connection; and its object can be created using
Connection con = null;
Statement: You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored procedures.

The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
3.3.1 Commonly used methods of Statement interface:
The important methods of Statement interface are as follows:
1) executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet.

2) executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update,
delete etc.

3) execute(String sql): is used to execute queries that may return multiple results.

Example: Statement stmt = con.createStatement(); stmt.executeUpdate(sqlQuery);

• ResultSet: These objects hold data retrieved from a database after you execute an SQL query using
Statement objects. It acts as an iterator to allow you to move through its data.

3.3.2 Commonly used methods of ResultSet interface


1) next(): is used to move the cursor to the one row next from the current position.
2) previous(): is used to move the cursor to the one row previous from the current
position.
3) first(): is used to move the cursor to the first row in result set object.
4) last(): is used to move the cursor to the last row in result set object.
5) getInt(int columnIndex): is used to return the data of specified column index of the current row as
int.
6) getInt(String columnName): is used to return the data of specified column name of the current row as
int.

31 | P a g e
7) getString(int columnIndex): is used to return the data of specified column index of the current row as
String.
8) getString(String columnName): is used to return the data of specified column name of the current row as
String.
is used to move the cursor to the relative row number in the ResultSet object,
9) relative(int row):
it may be positive or negative.
is used to move the cursor to the specified row number in the ResultSet
10) absolute (int row):
object..

Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from t");

//getting the record of 3rd row


System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

• SQLException: This class handles any errors that occur in a database application. You can
get the error message by using the e.getMessage() method where e is the Exception object.
• PreparedStatement Interface:

The PreparedStatement is a sub interface of Statement. It is used to execute parameterized query.

Let's see the example of parameterized query:


String sql="insert into t values(?,?,?)";
we are passing parameter (?) for the values. Its value will be set by calling the setter methods of
PreparedStatement.

3.3.3 Methods of PreparedStatement interface


The important methods of PreparedStatement interface are given below:
Method Description
setInt(int paramIndex, int value) sets the integer value to the given parameter index.
setString(int paramIndex, String value) sets the String value to the given parameter index.
setFloat(int paramIndex, float value) sets the float value to the given parameter index.
setDouble(int paramIndex, double value) sets the double value to the given parameter index.
executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.
executeQuery() executes the select query. It returns an instance of
ResultSet.

32 | P a g e
3.4 Connecting To A MySql Database
Here, we shall create an empty database called bsc3 and we shall initiate connection to the
database.

import java.sql.*; public class DBConnection {


public static void main(String[] args) {
String DBURL = "jdbc:mysql://localhost:3306/bsc3";
String databseUserName = "root";
String databasePassword = ""; Connection con = null;
try {
con = DriverManager.getConnection(DBURL, databseUserName, databasePassword);
if (con != null) {
System.out.println("Database connection is successful !!!!");
}
} catch (Exception e) {
System.out.println("Connection error is !!!!"+e.getMessage());
}
}
}
3.5 Creating A Database
Here, we shall create a database directly from Java.
import java.sql.*; public
class CreateDB {
public static void main(String[] args) {
String DBURL = "jdbc:mysql://localhost:3306/bsc3";
String databseUserName = "root";
String databasePassword = "";
Connection con = null;
String query = "Create database hnd3";
try {
con = DriverManager.getConnection(DBURL, databseUserName, databasePassword);
if (con != null) {
System.out.println("Database connection is successful !!!!");
PreparedStatement p = con.prepareStatement(query);
p.execute();
System.out.println("Database Created !!!!");
}
} catch (Exception e) {
System.out.println("Connection error is !!!!"+e.getMessage());
}
}
}

33 | P a g e
3.6 Creating A Table In The Database
Here, you need to simply insert the table query inside the code and use a prepared statement to
create the table.
package jdbc1;
import java.sql.*;

public class CreateDBTable {


public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/bsc3";
String username = "root";
String password = "";
Connection con = null;
try{
String tableQuery = "create table students(\n" +
"id int(10) primary key auto_increment,\n" +
"name varchar(10),\n" +
"matricule varchar(15),\n" +
"telephone varchar(15)\n" +
")";
con = DriverManager.getConnection(url,username,password);
PreparedStatement ps = con.prepareStatement(tableQuery);
ps.execute();
System.out.println("Table Created Successfully");
}catch(Exception e){
System.out.println("Error Creating Table Because "+e.getMessage());
}
}
}
3.7 Inserting Data Into A Table (Simple Method)
Here, you need to simply insert the table query inside the code.
package jdbc1;
import java.sql.*;

public class SimpleInsert {


public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/bsc3";
String username = "root";
String password = "";
Connection con = null;
Statement stmt = null;

try{
con = DriverManager.getConnection(url,username,password);
stmt = con.createStatement();

34 | P a g e
String query = "insert into students (name,matricule,telephone) values
('peter','AGK91','678173')";
stmt.executeUpdate(query);
System.out.println("Data Inserted Successfully");
}catch(Exception e){
System.out.println("Error Inserting Data Because "+e.getMessage());
}
}
}
3.8 Inserting Data Into A Table Using Prepared Statements
Here, you need to simply insert the table query inside the code and use a prepared statement to
create the table.
package jdbc1;
import java.sql.*;

public class PreparedStatementInsert { public


static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/bsc3";
String username = "root";
String password = "";
Connection con = null;
try{
String query = "insert into students (name,matricule,telephone) values (?,?,?)";
con = DriverManager.getConnection(url,username,password);
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, "Feckoundo");//1 specifies the first parameter in the query
ps.setString(2, "softtech");
ps.setString(3, "670787724");
ps.executeUpdate();
System.out.println("Data Inserted Successfully");
}catch(Exception e){
System.out.println("Error Inserting Data Because "+e.getMessage());
}
}
}
3.9 Selecting Data From The Table Using The Table Header
To do this, we need to create a Statement object and assign it to the Connection
object.CreateStatement() method. Afterwaards, we create an SQL query and use a ResultSet
object and assign it to the Statement object.executeQuery() method. We use a while loop now to
get the next result set in the cursor. We the return the name of the table header in the result set
object.

package jdbc1;
35 | P a g e
import java.sql.*;

public class SelectFromDB {


public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/bsc3";
String username = "root";
String password = "";
Connection con = null;
Statement stmt = null;

try{
con = DriverManager.getConnection(url,username,password);
String query = "select * from students";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);

while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String matricule = rs.getString("matricule");
int telephone = rs.getInt("telephone");

//Display values
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.print(", Matricule: " + matricule);
System.out.println(", Telephone: " + telephone);
}
}catch(Exception e){
System.out.println("Error Inserting Data Because "+e.getMessage());
}
}
}
3.10 Selecting Data From The Table Using The Table Index
To do this, we need to create a Statement object and assign it to the Connection
object.CreateStatement() method. Afterwaards, we create an SQL query and use a ResultSet object
and assign it to the Statement object.executeQuery() method. We use a while loop now to get the
next result set in the cursor. We the return the index of the table header in the result set object.

package jdbc1;
import java.sql.*;

36 | P a g e
public class SelectFromDBUsingTableIndex { public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/bsc3";
String username = "root";
String password = "";
Connection con = null;
Statement stmt = null;

try{
con = DriverManager.getConnection(url,username,password);
String query = "select * from students";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+"
"+rs.getString(4));
}
}catch(Exception e){
System.out.println("Error Inserting Data Because "+e.getMessage());
}
}
}

TUTORIALS
1. Write a program to keep inputting integer values until –1 is entered.
2. Write a program using a while loop to display a message 10 times. Each message should
be on a separate line using the following format with numbering starting from
1: A message
2: A message
3: A message
……
3. Write a program that inputs the radius of a circle and displays its circumference and area.
(use Math.PI for π)

37 | P a g e
4. Write a program to read in a line of text as a String and output the number of characters
and words it contains. Spaces and tabs should not be counted as characters.
5. Write a program that reads a decimal integer and prints out its binary equivalent.
6. Write a program that counts the number of times a specified character appears in a line of
text.
7. Write a program that uses a recursive method to calculate the product of a sequence of
numbers specified by the user. For example, if the user specifies 4 to 8, the method
calculates 4*5*6*7*8.
8. Write a method to test if an integer of type long is a prime number. The method should
return a boolean.
9. Write a program to read in 10 integers and store them in an array. Then display the contents
of the array.
10. Write a program to read in a sequence of integers until ‘stop’ is entered. Store the integers
in an array. Then display the average of the numbers entered.
11. A matrix can be represented using a 2D array. Write methods to perform matrix addition,
subtraction and multiplication. Each method should take two 2D arrays as a parameter and
return a new 2D array containing the result. Use the methods in a test program to verify
that they work correctly.
12. Write a program to act as a simple address book, storing names and addresses in a data file.
13. Create an implementation of the interface Queue that throws exceptions appropriately.
Declare any exception classes needed and write a test class

Exercise 1: (Complex numbers)


The purpose of this exercise is to define a class “CN” so that it can be used to manipulate
complex numbers.

Part A
Follow the specification below to define the class CN:
1. Attributes
CN contains two attributes “re” and “im” representing respectively the real and imaginary
parts of the complex number.

38 | P a g e
2. Constructors
CN contains a no-argument constructor (it sets re and im to zero), and a 2-argument
constructor having as parameters initial values of real and imaginary parts of the complex
number.

3. Methods
• getRe: returns the real part of the complex number.
• getImg: returns the imaginary part of the complex number.
• setRel and setImg: respectively modify the value of real and imaginary parts.
• add, multiply and subtract: to add, multiply or subtract two complex numbers.
• getModule: return the module of an instance of CN
• equals: Tests if two complex numbers are equal.(2 complex numbers are equal if their
real and imaginary parts are the same)
• clone: returns a copy of an instance of CN (the new copy will not share the same
reference with the original one).

Part B
Propose now a class TestCN with the main method to illustrate how to use the class CN defined
above.

Exercise 2:
Consider three classes A, B, and C. Assume that:
• B extends A, B and C implement the interface I,
• B overrides the method meth() of A,
• and B and C define a method fonc() of the interface I
For instructions (on the block S1) below, specify which version of method “meth” or “fonc” is
called.
S1

39 | P a g e
A a; B b; C c; I i; a = b;
a = new A(); b = a.meth(); (3)
new B(); c = new
C(); i = b; i.fonc(); (4) i
= c; i.fonc(); (5)

a.meth(); (1)
b.meth(); (2)

Exercise 3: (Control flow)


1. Write a java program that reads a positive integer n, calculate and displays its factorial.
2. Suppose now that the value of n is passed as argument to the main function. Write a java
program that prints out n!.

Exercise 4: (Method random() of java.math.Math ) ***


Write a program that simulates rolling a pair of dice. You can simulate rolling one die by
choosing one of the integers 1, 2, 3, 4, 5, or 6 at random. The number you pick represents the
number on the die after it is rolled (Use the method random of java.math.Math. For example,
int n = (int)(Math.random()*6)+1 returns a random interger between 1 and
6).
You can assign this value to a variable to represent one of the dice that are being rolled. Do
this twice and add the results together to get the total roll. Your program should report the number
showing on each die as well as the total roll.

For example:
The first die comes up 3
The second die comes up 5
Your total roll is 8

40 | P a g e
Exercise 5:
Write a program that asks the user’s name, and then greets the user by name. Before
outputting the user’s name, convert it to upper case letters. For example, if the user’s name
is Fred, then the program should respond “Hello, FRED, nice to meet you!”.

Exercise 6: (StringTonizer) **
Write a program that reads one line of input text and breaks it up into words. The words should be
output one per line. Assume that words are separated by the blank character “ ”. For example, if
the user inputs the line “Hello Word! I am a student”, the program prints:
Hello
Word!
I
am
a student

Exercise 7:
Suppose that a file contains information about sales figures for a company in various cities. Each
line of the file contains a city name, followed by a colon (:) followed by the data for that city. The
data is a number of type double. However, for some cities, no data was available. In these lines,
the data is replaced by a comment explaining why the data is missing. For example, several lines
from the file might look like: San Francisco: 19887.32
Chicago: no report received
New York: 298734.12
Write a program that will compute and print the total sales from all the cities together. The program
should also report the number of cities for which data was not available.
The name of the file is “sales.dat”.

What output is produced by the following program segment? (Recall that name.charAt(i)is the ith
character in the string, name.)

String name;
int i;
41 | P a g e
boolean startWord; name = "Richard M.
Nixon"; startWord = true; for (i = 0; i <
name.length(); i++) { if (startWord)
System.out.println(name.charAt(i))
; if (name.charAt(i) == ’ ’) startWord = true; else
startWord = false; }
Exercise 8:
To “capitalize” a string means to change the first letter of each word in the string to upper case (if
it is not already upper case). For example, a capitalized version of “Now is the time to act!” is
“Now Is The Time To Act!”. Write a subroutine named printCapitalized that will print a
capitalized version of a string to standard output. The string to be printed should be a parameter to
the subroutine. Test your subroutine with a main() routine that gets a line of input from the user
and applies the subroutine to it. Note that a letter is the first letter of a word if it is not immediately
preceded in the string by another letter. Recall that there is a standard boolean-valued function
Character.isLetter(char) that can be used to test whether its parameter is a letter. There is another
standard char-valued function, Character.toUpperCase(char), that returns a capitalized version of
the single character passed to it as a parameter. That is, if the parameter is a letter, it returns the
upper-case version. If the parameter is not a letter, it just returns a copy of the parameter.

Exercise 9
1. Define a class named Point, with two attributes x and y representing its coordinates. The
constructor of class Point takes as parameters, initial values of x and y (Point(int x_init, int
y_init).
Its methods are described below:
- move(int dx, int dy) : this method adds dx to x and dy to y
- display() : Displays the point coordinates (x and y)
2. Suppose that your program must also manipulate colored points represented by a class named
PointCol Describes as follow:
- Class PointCol extends Point and has only one attribute color (representing the color of
its instances).
- Its constructor signature is PointCol(int x_init, int y_init, byte color).
42 | P a g e
- PointCol overrides the methods display() of its super class, to show its coordinates and
color .
Propose a definition of class PointCol.

3. Consider class TestPoint defined by:


Class TestPoint{
public static void main(String arg[]){
Point p = new Point(3, 2);
p.display(); (a)

PointCol pc = new PointCol(5, 5, (byte)3);


p = pc;
p.display(); (b)
}
}

What output is produced by instructions (a) and (b)?

Exercise 10:
The hexadecimal digits are the ordinary, base-10 digits ’0’through ’9’ plus the letters ’A’ through
’F’. In the hexadecimal system, these digits represent the values 0 through 15, respectively. Write
a function named hexValue that uses a switch statement to find the hexadecimal value of a given
character. The character is a parameter to the function, and its hexadecimal value is the return value
of the function. You should count lower case letters ’a’ through ’f’ as having the same value as the
corresponding upper case letters. If the parameter is not one of the legal hexadecimal digits, return
-1 as the value of the function.

Exercise 11: ***


Write a program that displays a window containing a button labeled “Say Hello”. When the user
clicks on that button, the program displays the message “Hello World”.

Exercise 12:
Implement a program with this interface:

43 | P a g e
Clicking the buttons increments or decrements the displayed counter value.

Exercise 13:
Write a Swing program to display this window:

When the button is clicked, the text typed into the JTextField at the top of the window is copied
into the label in the middle of the window.

Exercise 14:
Implement a calculator program (using GUI)

Exercise 14
1. Define a class named Point, with two attributes x and y representing its coordinates. The
constructor of class Point takes as parameters, initial values of x and y [Point(int
x_init, int y_init)]. Its methods are described below:
- move(int dx, int dy) : this method adds dx to x and dy to y
- display() : Displays the point coordinates (x and y)
2. Suppose that your program must also manipulate colored points represented by a class named
PointCol Describes as follow:
- Class PointCol extends Point and has only one attribute color
- Its constructor signature is PointCol(int x_init, int y_init, byte
color).
- PointCol overrides the methods display() of its super class, to show its coordinates
and color .
Propose a definition of class PointCol.
3. Consider class TestPoint defined by:

44 | P a g e
Class TestPoint{
public static void main(String arg[]){
Point p = new Point(3, 2); p.display();
(a)
PointCol pc = new PointCol(5, 5, (byte)3);
p = pc;
p.display(); (b)
}
}
What output is produced by instructions (a) and (b)?

Exercise 15
A class called MyPoint, which models a 2D point with x and y coordinates has the following
attributes and methods: • Two instance variables x (int) and y (int).
• A "no-argument" (or "no-arg") constructor that construct a point at (0, 0).
• A constructor that constructs a point with the given x and y coordinates.
• Getter and setter for the instance variables x and y. • A method setXY() to set
both x and y.
• A toString() method that returns a string description of the instance in the format "(x,
y)".
• A method called distance(int x, int y) that returns the distance from this point to
another point at the given (x, y) coordinates. 1
• An overloaded distance(MyPoint another) that returns the distance from this point
to the given MyPoint instance another.

1. You are required to Write the code for the class MyPoint.
2. Write the code of another class called MyTriangle, which models a triangle with 3 vertices
designed as follows. The MyTriangle class uses three MyPoint instances (created in the
earlier exercise) as the three vertices. The class contains:
• Three private instance variables v1, v2, v3 (instances of MyPoint), for the three vertices.
• A constructor that constructs a MyTriangle with three points v1=(x1, y1), v2=(x2, y2),
v3=(x3, y3). [Prototype: public MyTriangle(MyPoint v1, MyPoint v2, MyPoint
v3) ]
• A toString() method that returns a string description of the instance in the format
"Triangle @ (x1, y1), (x2, y2), (x3, y3)".
• A getPerimeter() method that returns the length of the perimeter in double. You should
use the distance() method of MyPoint to compute the perimeter.

45 | P a g e
• A method printType(), which prints "equilateral" if all the three sides are equal,
"isosceles" if any two of the three sides are equal, or "scalene" if the three sides are
different.

Exercise 16
You are asked to write a discount system for a beauty salon, which provides services and sells
beauty products. It offers 3 types of memberships: Premium, Gold and Silver. Premium, gold

and silver members receive a discount of 20%, 15%, and 10%, respectively, for all services

provided. Customers without membership receive no discount. All members receives a flat 10%
discount on products purchased (this might change in future). Your system shall consist of three
classes: Customer, DiscountRate and Visit, as shown in the class diagram below. It shall

compute the total bill if a customer purchases $x of products and $y of services, for a visit. Also
write a test program to exercise all the classes.

The class DiscountRate contains only static variables and methods (underlined in the class

diagram).

46 | P a g e

You might also like