Java Programming Handout for Btech
Java Programming Handout for Btech
PROGRAMMING WITH
JAVA
BACHELOR
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.
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.
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:
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.
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 ++.
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!");
}
}
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
*/
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;
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
}
}
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
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
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)
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”);
}
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
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
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
}
}
Outpout :
(Java.lang.ArithmeticException: / by zero at
DivdeBy0.main(DivdeBy0:3))
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();
}
}
}
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)
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;
dataType[] arrayVar = new dataType[size]; where size is the size of the array.
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);
}
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.
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.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
a) getConnection(String url): is used to establish the connection with the specified url.
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.
• 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.
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");
• 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:
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.
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.*;
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.*;
package jdbc1;
35 | P a g e
import java.sql.*;
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
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)
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.
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 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